TextView.java revision 0ad4f0963a47feafaaa92a756fb84caab5b6bddb
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.widget; 18 19import com.android.internal.util.FastMath; 20import com.android.internal.widget.EditableInputConnection; 21 22import org.xmlpull.v1.XmlPullParserException; 23 24import android.R; 25import android.content.ClipData; 26import android.content.ClipData.Item; 27import android.content.ClipboardManager; 28import android.content.Context; 29import android.content.pm.PackageManager; 30import android.content.res.ColorStateList; 31import android.content.res.Resources; 32import android.content.res.TypedArray; 33import android.content.res.XmlResourceParser; 34import android.graphics.Canvas; 35import android.graphics.Color; 36import android.graphics.Paint; 37import android.graphics.Path; 38import android.graphics.Rect; 39import android.graphics.RectF; 40import android.graphics.Typeface; 41import android.graphics.drawable.Drawable; 42import android.inputmethodservice.ExtractEditText; 43import android.net.Uri; 44import android.os.Bundle; 45import android.os.Handler; 46import android.os.Message; 47import android.os.Parcel; 48import android.os.Parcelable; 49import android.os.ResultReceiver; 50import android.os.SystemClock; 51import android.text.BoringLayout; 52import android.text.DynamicLayout; 53import android.text.Editable; 54import android.text.GetChars; 55import android.text.GraphicsOperations; 56import android.text.InputFilter; 57import android.text.InputType; 58import android.text.Layout; 59import android.text.ParcelableSpan; 60import android.text.Selection; 61import android.text.SpanWatcher; 62import android.text.Spannable; 63import android.text.SpannableString; 64import android.text.Spanned; 65import android.text.SpannedString; 66import android.text.StaticLayout; 67import android.text.TextPaint; 68import android.text.TextUtils; 69import android.text.TextWatcher; 70import android.text.method.ArrowKeyMovementMethod; 71import android.text.method.DateKeyListener; 72import android.text.method.DateTimeKeyListener; 73import android.text.method.DialerKeyListener; 74import android.text.method.DigitsKeyListener; 75import android.text.method.KeyListener; 76import android.text.method.LinkMovementMethod; 77import android.text.method.MetaKeyKeyListener; 78import android.text.method.MovementMethod; 79import android.text.method.PasswordTransformationMethod; 80import android.text.method.SingleLineTransformationMethod; 81import android.text.method.TextKeyListener; 82import android.text.method.TimeKeyListener; 83import android.text.method.TransformationMethod; 84import android.text.style.ClickableSpan; 85import android.text.style.ParagraphStyle; 86import android.text.style.URLSpan; 87import android.text.style.UpdateAppearance; 88import android.text.util.Linkify; 89import android.util.AttributeSet; 90import android.util.FloatMath; 91import android.util.Log; 92import android.util.TypedValue; 93import android.view.ActionMode; 94import android.view.ActionMode.Callback; 95import android.view.ContextMenu; 96import android.view.DragEvent; 97import android.view.Gravity; 98import android.view.HapticFeedbackConstants; 99import android.view.KeyCharacterMap; 100import android.view.KeyEvent; 101import android.view.LayoutInflater; 102import android.view.Menu; 103import android.view.MenuItem; 104import android.view.MotionEvent; 105import android.view.View; 106import android.view.ViewConfiguration; 107import android.view.ViewDebug; 108import android.view.ViewGroup; 109import android.view.ViewGroup.LayoutParams; 110import android.view.ViewParent; 111import android.view.ViewRoot; 112import android.view.ViewTreeObserver; 113import android.view.WindowManager; 114import android.view.accessibility.AccessibilityEvent; 115import android.view.accessibility.AccessibilityManager; 116import android.view.animation.AnimationUtils; 117import android.view.inputmethod.BaseInputConnection; 118import android.view.inputmethod.CompletionInfo; 119import android.view.inputmethod.CorrectionInfo; 120import android.view.inputmethod.EditorInfo; 121import android.view.inputmethod.ExtractedText; 122import android.view.inputmethod.ExtractedTextRequest; 123import android.view.inputmethod.InputConnection; 124import android.view.inputmethod.InputMethodManager; 125import android.widget.RemoteViews.RemoteView; 126 127import java.io.IOException; 128import java.lang.ref.WeakReference; 129import java.util.ArrayList; 130 131/** 132 * Displays text to the user and optionally allows them to edit it. A TextView 133 * is a complete text editor, however the basic class is configured to not 134 * allow editing; see {@link EditText} for a subclass that configures the text 135 * view for editing. 136 * 137 * <p> 138 * <b>XML attributes</b> 139 * <p> 140 * See {@link android.R.styleable#TextView TextView Attributes}, 141 * {@link android.R.styleable#View View Attributes} 142 * 143 * @attr ref android.R.styleable#TextView_text 144 * @attr ref android.R.styleable#TextView_bufferType 145 * @attr ref android.R.styleable#TextView_hint 146 * @attr ref android.R.styleable#TextView_textColor 147 * @attr ref android.R.styleable#TextView_textColorHighlight 148 * @attr ref android.R.styleable#TextView_textColorHint 149 * @attr ref android.R.styleable#TextView_textAppearance 150 * @attr ref android.R.styleable#TextView_textColorLink 151 * @attr ref android.R.styleable#TextView_textSize 152 * @attr ref android.R.styleable#TextView_textScaleX 153 * @attr ref android.R.styleable#TextView_typeface 154 * @attr ref android.R.styleable#TextView_textStyle 155 * @attr ref android.R.styleable#TextView_cursorVisible 156 * @attr ref android.R.styleable#TextView_maxLines 157 * @attr ref android.R.styleable#TextView_maxHeight 158 * @attr ref android.R.styleable#TextView_lines 159 * @attr ref android.R.styleable#TextView_height 160 * @attr ref android.R.styleable#TextView_minLines 161 * @attr ref android.R.styleable#TextView_minHeight 162 * @attr ref android.R.styleable#TextView_maxEms 163 * @attr ref android.R.styleable#TextView_maxWidth 164 * @attr ref android.R.styleable#TextView_ems 165 * @attr ref android.R.styleable#TextView_width 166 * @attr ref android.R.styleable#TextView_minEms 167 * @attr ref android.R.styleable#TextView_minWidth 168 * @attr ref android.R.styleable#TextView_gravity 169 * @attr ref android.R.styleable#TextView_scrollHorizontally 170 * @attr ref android.R.styleable#TextView_password 171 * @attr ref android.R.styleable#TextView_singleLine 172 * @attr ref android.R.styleable#TextView_selectAllOnFocus 173 * @attr ref android.R.styleable#TextView_includeFontPadding 174 * @attr ref android.R.styleable#TextView_maxLength 175 * @attr ref android.R.styleable#TextView_shadowColor 176 * @attr ref android.R.styleable#TextView_shadowDx 177 * @attr ref android.R.styleable#TextView_shadowDy 178 * @attr ref android.R.styleable#TextView_shadowRadius 179 * @attr ref android.R.styleable#TextView_autoLink 180 * @attr ref android.R.styleable#TextView_linksClickable 181 * @attr ref android.R.styleable#TextView_numeric 182 * @attr ref android.R.styleable#TextView_digits 183 * @attr ref android.R.styleable#TextView_phoneNumber 184 * @attr ref android.R.styleable#TextView_inputMethod 185 * @attr ref android.R.styleable#TextView_capitalize 186 * @attr ref android.R.styleable#TextView_autoText 187 * @attr ref android.R.styleable#TextView_editable 188 * @attr ref android.R.styleable#TextView_freezesText 189 * @attr ref android.R.styleable#TextView_ellipsize 190 * @attr ref android.R.styleable#TextView_drawableTop 191 * @attr ref android.R.styleable#TextView_drawableBottom 192 * @attr ref android.R.styleable#TextView_drawableRight 193 * @attr ref android.R.styleable#TextView_drawableLeft 194 * @attr ref android.R.styleable#TextView_drawablePadding 195 * @attr ref android.R.styleable#TextView_lineSpacingExtra 196 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 197 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 198 * @attr ref android.R.styleable#TextView_inputType 199 * @attr ref android.R.styleable#TextView_imeOptions 200 * @attr ref android.R.styleable#TextView_privateImeOptions 201 * @attr ref android.R.styleable#TextView_imeActionLabel 202 * @attr ref android.R.styleable#TextView_imeActionId 203 * @attr ref android.R.styleable#TextView_editorExtras 204 */ 205@RemoteView 206public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { 207 static final String LOG_TAG = "TextView"; 208 static final boolean DEBUG_EXTRACT = false; 209 210 private static final int PRIORITY = 100; 211 private int mCurrentAlpha = 255; 212 213 final int[] mTempCoords = new int[2]; 214 Rect mTempRect; 215 216 private ColorStateList mTextColor; 217 private int mCurTextColor; 218 private ColorStateList mHintTextColor; 219 private ColorStateList mLinkTextColor; 220 private int mCurHintTextColor; 221 private boolean mFreezesText; 222 private boolean mFrozenWithFocus; 223 private boolean mTemporaryDetach; 224 private boolean mDispatchTemporaryDetach; 225 226 private boolean mDiscardNextActionUp = false; 227 private boolean mIgnoreActionUpEvent = false; 228 229 private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); 230 private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); 231 232 private float mShadowRadius, mShadowDx, mShadowDy; 233 234 private static final int PREDRAW_NOT_REGISTERED = 0; 235 private static final int PREDRAW_PENDING = 1; 236 private static final int PREDRAW_DONE = 2; 237 private int mPreDrawState = PREDRAW_NOT_REGISTERED; 238 239 private TextUtils.TruncateAt mEllipsize = null; 240 241 // Enum for the "typeface" XML parameter. 242 // TODO: How can we get this from the XML instead of hardcoding it here? 243 private static final int SANS = 1; 244 private static final int SERIF = 2; 245 private static final int MONOSPACE = 3; 246 247 // Bitfield for the "numeric" XML parameter. 248 // TODO: How can we get this from the XML instead of hardcoding it here? 249 private static final int SIGNED = 2; 250 private static final int DECIMAL = 4; 251 252 class Drawables { 253 final Rect mCompoundRect = new Rect(); 254 Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight; 255 int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight; 256 int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight; 257 int mDrawablePadding; 258 } 259 private Drawables mDrawables; 260 261 private CharSequence mError; 262 private boolean mErrorWasChanged; 263 private ErrorPopup mPopup; 264 /** 265 * This flag is set if the TextView tries to display an error before it 266 * is attached to the window (so its position is still unknown). 267 * It causes the error to be shown later, when onAttachedToWindow() 268 * is called. 269 */ 270 private boolean mShowErrorAfterAttach; 271 272 private CharWrapper mCharWrapper = null; 273 274 private boolean mSelectionMoved = false; 275 private boolean mTouchFocusSelected = false; 276 277 private Marquee mMarquee; 278 private boolean mRestartMarquee; 279 280 private int mMarqueeRepeatLimit = 3; 281 282 class InputContentType { 283 int imeOptions = EditorInfo.IME_NULL; 284 String privateImeOptions; 285 CharSequence imeActionLabel; 286 int imeActionId; 287 Bundle extras; 288 OnEditorActionListener onEditorActionListener; 289 boolean enterDown; 290 } 291 InputContentType mInputContentType; 292 293 class InputMethodState { 294 Rect mCursorRectInWindow = new Rect(); 295 RectF mTmpRectF = new RectF(); 296 float[] mTmpOffset = new float[2]; 297 ExtractedTextRequest mExtracting; 298 final ExtractedText mTmpExtracted = new ExtractedText(); 299 int mBatchEditNesting; 300 boolean mCursorChanged; 301 boolean mSelectionModeChanged; 302 boolean mContentChanged; 303 int mChangedStart, mChangedEnd, mChangedDelta; 304 } 305 InputMethodState mInputMethodState; 306 307 int mTextSelectHandleLeftRes; 308 int mTextSelectHandleRightRes; 309 int mTextSelectHandleRes; 310 int mTextEditPasteWindowLayout, mTextEditSidePasteWindowLayout; 311 int mTextEditNoPasteWindowLayout, mTextEditSideNoPasteWindowLayout; 312 313 Drawable mSelectHandleLeft; 314 Drawable mSelectHandleRight; 315 Drawable mSelectHandleCenter; 316 317 private int mLastDownPositionX, mLastDownPositionY; 318 private Callback mCustomSelectionActionModeCallback; 319 320 private final int mSquaredTouchSlopDistance; 321 // Set when this TextView gained focus with some text selected. Will start selection mode. 322 private boolean mCreatedWithASelection = false; 323 324 /* 325 * Kick-start the font cache for the zygote process (to pay the cost of 326 * initializing freetype for our default font only once). 327 */ 328 static { 329 Paint p = new Paint(); 330 p.setAntiAlias(true); 331 // We don't care about the result, just the side-effect of measuring. 332 p.measureText("H"); 333 } 334 335 /** 336 * Interface definition for a callback to be invoked when an action is 337 * performed on the editor. 338 */ 339 public interface OnEditorActionListener { 340 /** 341 * Called when an action is being performed. 342 * 343 * @param v The view that was clicked. 344 * @param actionId Identifier of the action. This will be either the 345 * identifier you supplied, or {@link EditorInfo#IME_NULL 346 * EditorInfo.IME_NULL} if being called due to the enter key 347 * being pressed. 348 * @param event If triggered by an enter key, this is the event; 349 * otherwise, this is null. 350 * @return Return true if you have consumed the action, else false. 351 */ 352 boolean onEditorAction(TextView v, int actionId, KeyEvent event); 353 } 354 355 public TextView(Context context) { 356 this(context, null); 357 } 358 359 public TextView(Context context, 360 AttributeSet attrs) { 361 this(context, attrs, com.android.internal.R.attr.textViewStyle); 362 } 363 364 @SuppressWarnings("deprecation") 365 public TextView(Context context, 366 AttributeSet attrs, 367 int defStyle) { 368 super(context, attrs, defStyle); 369 mText = ""; 370 371 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 372 mTextPaint.density = getResources().getDisplayMetrics().density; 373 mTextPaint.setCompatibilityScaling( 374 getResources().getCompatibilityInfo().applicationScale); 375 376 // If we get the paint from the skin, we should set it to left, since 377 // the layout always wants it to be left. 378 // mTextPaint.setTextAlign(Paint.Align.LEFT); 379 380 mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 381 mHighlightPaint.setCompatibilityScaling( 382 getResources().getCompatibilityInfo().applicationScale); 383 384 mMovement = getDefaultMovementMethod(); 385 mTransformation = null; 386 387 TypedArray a = 388 context.obtainStyledAttributes( 389 attrs, com.android.internal.R.styleable.TextView, defStyle, 0); 390 391 int textColorHighlight = 0; 392 ColorStateList textColor = null; 393 ColorStateList textColorHint = null; 394 ColorStateList textColorLink = null; 395 int textSize = 15; 396 int typefaceIndex = -1; 397 int styleIndex = -1; 398 399 /* 400 * Look the appearance up without checking first if it exists because 401 * almost every TextView has one and it greatly simplifies the logic 402 * to be able to parse the appearance first and then let specific tags 403 * for this View override it. 404 */ 405 TypedArray appearance = null; 406 int ap = a.getResourceId(com.android.internal.R.styleable.TextView_textAppearance, -1); 407 if (ap != -1) { 408 appearance = context.obtainStyledAttributes(ap, 409 com.android.internal.R.styleable. 410 TextAppearance); 411 } 412 if (appearance != null) { 413 int n = appearance.getIndexCount(); 414 for (int i = 0; i < n; i++) { 415 int attr = appearance.getIndex(i); 416 417 switch (attr) { 418 case com.android.internal.R.styleable.TextAppearance_textColorHighlight: 419 textColorHighlight = appearance.getColor(attr, textColorHighlight); 420 break; 421 422 case com.android.internal.R.styleable.TextAppearance_textColor: 423 textColor = appearance.getColorStateList(attr); 424 break; 425 426 case com.android.internal.R.styleable.TextAppearance_textColorHint: 427 textColorHint = appearance.getColorStateList(attr); 428 break; 429 430 case com.android.internal.R.styleable.TextAppearance_textColorLink: 431 textColorLink = appearance.getColorStateList(attr); 432 break; 433 434 case com.android.internal.R.styleable.TextAppearance_textSize: 435 textSize = appearance.getDimensionPixelSize(attr, textSize); 436 break; 437 438 case com.android.internal.R.styleable.TextAppearance_typeface: 439 typefaceIndex = appearance.getInt(attr, -1); 440 break; 441 442 case com.android.internal.R.styleable.TextAppearance_textStyle: 443 styleIndex = appearance.getInt(attr, -1); 444 break; 445 } 446 } 447 448 appearance.recycle(); 449 } 450 451 boolean editable = getDefaultEditable(); 452 CharSequence inputMethod = null; 453 int numeric = 0; 454 CharSequence digits = null; 455 boolean phone = false; 456 boolean autotext = false; 457 int autocap = -1; 458 int buffertype = 0; 459 boolean selectallonfocus = false; 460 Drawable drawableLeft = null, drawableTop = null, drawableRight = null, 461 drawableBottom = null; 462 int drawablePadding = 0; 463 int ellipsize = -1; 464 boolean singleLine = false; 465 int maxlength = -1; 466 CharSequence text = ""; 467 CharSequence hint = null; 468 int shadowcolor = 0; 469 float dx = 0, dy = 0, r = 0; 470 boolean password = false; 471 int inputType = EditorInfo.TYPE_NULL; 472 473 int n = a.getIndexCount(); 474 for (int i = 0; i < n; i++) { 475 int attr = a.getIndex(i); 476 477 switch (attr) { 478 case com.android.internal.R.styleable.TextView_editable: 479 editable = a.getBoolean(attr, editable); 480 break; 481 482 case com.android.internal.R.styleable.TextView_inputMethod: 483 inputMethod = a.getText(attr); 484 break; 485 486 case com.android.internal.R.styleable.TextView_numeric: 487 numeric = a.getInt(attr, numeric); 488 break; 489 490 case com.android.internal.R.styleable.TextView_digits: 491 digits = a.getText(attr); 492 break; 493 494 case com.android.internal.R.styleable.TextView_phoneNumber: 495 phone = a.getBoolean(attr, phone); 496 break; 497 498 case com.android.internal.R.styleable.TextView_autoText: 499 autotext = a.getBoolean(attr, autotext); 500 break; 501 502 case com.android.internal.R.styleable.TextView_capitalize: 503 autocap = a.getInt(attr, autocap); 504 break; 505 506 case com.android.internal.R.styleable.TextView_bufferType: 507 buffertype = a.getInt(attr, buffertype); 508 break; 509 510 case com.android.internal.R.styleable.TextView_selectAllOnFocus: 511 selectallonfocus = a.getBoolean(attr, selectallonfocus); 512 break; 513 514 case com.android.internal.R.styleable.TextView_autoLink: 515 mAutoLinkMask = a.getInt(attr, 0); 516 break; 517 518 case com.android.internal.R.styleable.TextView_linksClickable: 519 mLinksClickable = a.getBoolean(attr, true); 520 break; 521 522 case com.android.internal.R.styleable.TextView_drawableLeft: 523 drawableLeft = a.getDrawable(attr); 524 break; 525 526 case com.android.internal.R.styleable.TextView_drawableTop: 527 drawableTop = a.getDrawable(attr); 528 break; 529 530 case com.android.internal.R.styleable.TextView_drawableRight: 531 drawableRight = a.getDrawable(attr); 532 break; 533 534 case com.android.internal.R.styleable.TextView_drawableBottom: 535 drawableBottom = a.getDrawable(attr); 536 break; 537 538 case com.android.internal.R.styleable.TextView_drawablePadding: 539 drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); 540 break; 541 542 case com.android.internal.R.styleable.TextView_maxLines: 543 setMaxLines(a.getInt(attr, -1)); 544 break; 545 546 case com.android.internal.R.styleable.TextView_maxHeight: 547 setMaxHeight(a.getDimensionPixelSize(attr, -1)); 548 break; 549 550 case com.android.internal.R.styleable.TextView_lines: 551 setLines(a.getInt(attr, -1)); 552 break; 553 554 case com.android.internal.R.styleable.TextView_height: 555 setHeight(a.getDimensionPixelSize(attr, -1)); 556 break; 557 558 case com.android.internal.R.styleable.TextView_minLines: 559 setMinLines(a.getInt(attr, -1)); 560 break; 561 562 case com.android.internal.R.styleable.TextView_minHeight: 563 setMinHeight(a.getDimensionPixelSize(attr, -1)); 564 break; 565 566 case com.android.internal.R.styleable.TextView_maxEms: 567 setMaxEms(a.getInt(attr, -1)); 568 break; 569 570 case com.android.internal.R.styleable.TextView_maxWidth: 571 setMaxWidth(a.getDimensionPixelSize(attr, -1)); 572 break; 573 574 case com.android.internal.R.styleable.TextView_ems: 575 setEms(a.getInt(attr, -1)); 576 break; 577 578 case com.android.internal.R.styleable.TextView_width: 579 setWidth(a.getDimensionPixelSize(attr, -1)); 580 break; 581 582 case com.android.internal.R.styleable.TextView_minEms: 583 setMinEms(a.getInt(attr, -1)); 584 break; 585 586 case com.android.internal.R.styleable.TextView_minWidth: 587 setMinWidth(a.getDimensionPixelSize(attr, -1)); 588 break; 589 590 case com.android.internal.R.styleable.TextView_gravity: 591 setGravity(a.getInt(attr, -1)); 592 break; 593 594 case com.android.internal.R.styleable.TextView_hint: 595 hint = a.getText(attr); 596 break; 597 598 case com.android.internal.R.styleable.TextView_text: 599 text = a.getText(attr); 600 break; 601 602 case com.android.internal.R.styleable.TextView_scrollHorizontally: 603 if (a.getBoolean(attr, false)) { 604 setHorizontallyScrolling(true); 605 } 606 break; 607 608 case com.android.internal.R.styleable.TextView_singleLine: 609 singleLine = a.getBoolean(attr, singleLine); 610 break; 611 612 case com.android.internal.R.styleable.TextView_ellipsize: 613 ellipsize = a.getInt(attr, ellipsize); 614 break; 615 616 case com.android.internal.R.styleable.TextView_marqueeRepeatLimit: 617 setMarqueeRepeatLimit(a.getInt(attr, mMarqueeRepeatLimit)); 618 break; 619 620 case com.android.internal.R.styleable.TextView_includeFontPadding: 621 if (!a.getBoolean(attr, true)) { 622 setIncludeFontPadding(false); 623 } 624 break; 625 626 case com.android.internal.R.styleable.TextView_cursorVisible: 627 if (!a.getBoolean(attr, true)) { 628 setCursorVisible(false); 629 } 630 break; 631 632 case com.android.internal.R.styleable.TextView_maxLength: 633 maxlength = a.getInt(attr, -1); 634 break; 635 636 case com.android.internal.R.styleable.TextView_textScaleX: 637 setTextScaleX(a.getFloat(attr, 1.0f)); 638 break; 639 640 case com.android.internal.R.styleable.TextView_freezesText: 641 mFreezesText = a.getBoolean(attr, false); 642 break; 643 644 case com.android.internal.R.styleable.TextView_shadowColor: 645 shadowcolor = a.getInt(attr, 0); 646 break; 647 648 case com.android.internal.R.styleable.TextView_shadowDx: 649 dx = a.getFloat(attr, 0); 650 break; 651 652 case com.android.internal.R.styleable.TextView_shadowDy: 653 dy = a.getFloat(attr, 0); 654 break; 655 656 case com.android.internal.R.styleable.TextView_shadowRadius: 657 r = a.getFloat(attr, 0); 658 break; 659 660 case com.android.internal.R.styleable.TextView_enabled: 661 setEnabled(a.getBoolean(attr, isEnabled())); 662 break; 663 664 case com.android.internal.R.styleable.TextView_textColorHighlight: 665 textColorHighlight = a.getColor(attr, textColorHighlight); 666 break; 667 668 case com.android.internal.R.styleable.TextView_textColor: 669 textColor = a.getColorStateList(attr); 670 break; 671 672 case com.android.internal.R.styleable.TextView_textColorHint: 673 textColorHint = a.getColorStateList(attr); 674 break; 675 676 case com.android.internal.R.styleable.TextView_textColorLink: 677 textColorLink = a.getColorStateList(attr); 678 break; 679 680 case com.android.internal.R.styleable.TextView_textSize: 681 textSize = a.getDimensionPixelSize(attr, textSize); 682 break; 683 684 case com.android.internal.R.styleable.TextView_typeface: 685 typefaceIndex = a.getInt(attr, typefaceIndex); 686 break; 687 688 case com.android.internal.R.styleable.TextView_textStyle: 689 styleIndex = a.getInt(attr, styleIndex); 690 break; 691 692 case com.android.internal.R.styleable.TextView_password: 693 password = a.getBoolean(attr, password); 694 break; 695 696 case com.android.internal.R.styleable.TextView_lineSpacingExtra: 697 mSpacingAdd = a.getDimensionPixelSize(attr, (int) mSpacingAdd); 698 break; 699 700 case com.android.internal.R.styleable.TextView_lineSpacingMultiplier: 701 mSpacingMult = a.getFloat(attr, mSpacingMult); 702 break; 703 704 case com.android.internal.R.styleable.TextView_inputType: 705 inputType = a.getInt(attr, mInputType); 706 break; 707 708 case com.android.internal.R.styleable.TextView_imeOptions: 709 if (mInputContentType == null) { 710 mInputContentType = new InputContentType(); 711 } 712 mInputContentType.imeOptions = a.getInt(attr, 713 mInputContentType.imeOptions); 714 break; 715 716 case com.android.internal.R.styleable.TextView_imeActionLabel: 717 if (mInputContentType == null) { 718 mInputContentType = new InputContentType(); 719 } 720 mInputContentType.imeActionLabel = a.getText(attr); 721 break; 722 723 case com.android.internal.R.styleable.TextView_imeActionId: 724 if (mInputContentType == null) { 725 mInputContentType = new InputContentType(); 726 } 727 mInputContentType.imeActionId = a.getInt(attr, 728 mInputContentType.imeActionId); 729 break; 730 731 case com.android.internal.R.styleable.TextView_privateImeOptions: 732 setPrivateImeOptions(a.getString(attr)); 733 break; 734 735 case com.android.internal.R.styleable.TextView_editorExtras: 736 try { 737 setInputExtras(a.getResourceId(attr, 0)); 738 } catch (XmlPullParserException e) { 739 Log.w(LOG_TAG, "Failure reading input extras", e); 740 } catch (IOException e) { 741 Log.w(LOG_TAG, "Failure reading input extras", e); 742 } 743 break; 744 745 case com.android.internal.R.styleable.TextView_textSelectHandleLeft: 746 mTextSelectHandleLeftRes = a.getResourceId(attr, 0); 747 break; 748 749 case com.android.internal.R.styleable.TextView_textSelectHandleRight: 750 mTextSelectHandleRightRes = a.getResourceId(attr, 0); 751 break; 752 753 case com.android.internal.R.styleable.TextView_textSelectHandle: 754 mTextSelectHandleRes = a.getResourceId(attr, 0); 755 break; 756 757 case com.android.internal.R.styleable.TextView_textEditPasteWindowLayout: 758 mTextEditPasteWindowLayout = a.getResourceId(attr, 0); 759 break; 760 761 case com.android.internal.R.styleable.TextView_textEditNoPasteWindowLayout: 762 mTextEditNoPasteWindowLayout = a.getResourceId(attr, 0); 763 break; 764 765 case com.android.internal.R.styleable.TextView_textEditSidePasteWindowLayout: 766 mTextEditSidePasteWindowLayout = a.getResourceId(attr, 0); 767 break; 768 769 case com.android.internal.R.styleable.TextView_textEditSideNoPasteWindowLayout: 770 mTextEditSideNoPasteWindowLayout = a.getResourceId(attr, 0); 771 break; 772 773 case com.android.internal.R.styleable.TextView_textIsSelectable: 774 mTextIsSelectable = a.getBoolean(attr, false); 775 break; 776 } 777 } 778 a.recycle(); 779 780 BufferType bufferType = BufferType.EDITABLE; 781 782 final int variation = 783 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 784 final boolean passwordInputType = variation 785 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); 786 final boolean webPasswordInputType = variation 787 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD); 788 final boolean numberPasswordInputType = variation 789 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 790 791 if (inputMethod != null) { 792 Class<?> c; 793 794 try { 795 c = Class.forName(inputMethod.toString()); 796 } catch (ClassNotFoundException ex) { 797 throw new RuntimeException(ex); 798 } 799 800 try { 801 mInput = (KeyListener) c.newInstance(); 802 } catch (InstantiationException ex) { 803 throw new RuntimeException(ex); 804 } catch (IllegalAccessException ex) { 805 throw new RuntimeException(ex); 806 } 807 try { 808 mInputType = inputType != EditorInfo.TYPE_NULL 809 ? inputType 810 : mInput.getInputType(); 811 } catch (IncompatibleClassChangeError e) { 812 mInputType = EditorInfo.TYPE_CLASS_TEXT; 813 } 814 } else if (digits != null) { 815 mInput = DigitsKeyListener.getInstance(digits.toString()); 816 // If no input type was specified, we will default to generic 817 // text, since we can't tell the IME about the set of digits 818 // that was selected. 819 mInputType = inputType != EditorInfo.TYPE_NULL 820 ? inputType : EditorInfo.TYPE_CLASS_TEXT; 821 } else if (inputType != EditorInfo.TYPE_NULL) { 822 setInputType(inputType, true); 823 // If set, the input type overrides what was set using the deprecated singleLine flag. 824 singleLine = !isMultilineInputType(inputType); 825 } else if (phone) { 826 mInput = DialerKeyListener.getInstance(); 827 mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE; 828 } else if (numeric != 0) { 829 mInput = DigitsKeyListener.getInstance((numeric & SIGNED) != 0, 830 (numeric & DECIMAL) != 0); 831 inputType = EditorInfo.TYPE_CLASS_NUMBER; 832 if ((numeric & SIGNED) != 0) { 833 inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; 834 } 835 if ((numeric & DECIMAL) != 0) { 836 inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; 837 } 838 mInputType = inputType; 839 } else if (autotext || autocap != -1) { 840 TextKeyListener.Capitalize cap; 841 842 inputType = EditorInfo.TYPE_CLASS_TEXT; 843 844 switch (autocap) { 845 case 1: 846 cap = TextKeyListener.Capitalize.SENTENCES; 847 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; 848 break; 849 850 case 2: 851 cap = TextKeyListener.Capitalize.WORDS; 852 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; 853 break; 854 855 case 3: 856 cap = TextKeyListener.Capitalize.CHARACTERS; 857 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; 858 break; 859 860 default: 861 cap = TextKeyListener.Capitalize.NONE; 862 break; 863 } 864 865 mInput = TextKeyListener.getInstance(autotext, cap); 866 mInputType = inputType; 867 } else if (mTextIsSelectable) { 868 // Prevent text changes from keyboard. 869 mInputType = EditorInfo.TYPE_NULL; 870 mInput = null; 871 bufferType = BufferType.SPANNABLE; 872 // Required to request focus while in touch mode. 873 setFocusableInTouchMode(true); 874 // So that selection can be changed using arrow keys and touch is handled. 875 setMovementMethod(ArrowKeyMovementMethod.getInstance()); 876 } else if (editable) { 877 mInput = TextKeyListener.getInstance(); 878 mInputType = EditorInfo.TYPE_CLASS_TEXT; 879 } else { 880 mInput = null; 881 882 switch (buffertype) { 883 case 0: 884 bufferType = BufferType.NORMAL; 885 break; 886 case 1: 887 bufferType = BufferType.SPANNABLE; 888 break; 889 case 2: 890 bufferType = BufferType.EDITABLE; 891 break; 892 } 893 } 894 895 // mInputType has been set from inputType, possibly modified by mInputMethod. 896 // Specialize mInputType to [web]password if we have a text class and the original input 897 // type was a password. 898 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 899 if (password || passwordInputType) { 900 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 901 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 902 } 903 if (webPasswordInputType) { 904 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 905 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD; 906 } 907 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) { 908 if (numberPasswordInputType) { 909 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 910 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD; 911 } 912 } 913 914 if (selectallonfocus) { 915 mSelectAllOnFocus = true; 916 917 if (bufferType == BufferType.NORMAL) 918 bufferType = BufferType.SPANNABLE; 919 } 920 921 setCompoundDrawablesWithIntrinsicBounds( 922 drawableLeft, drawableTop, drawableRight, drawableBottom); 923 setCompoundDrawablePadding(drawablePadding); 924 925 // Same as setSingleLine(), but make sure the transformation method and the maximum number 926 // of lines of height are unchanged for multi-line TextViews. 927 setInputTypeSingleLine(singleLine); 928 applySingleLine(singleLine, singleLine, singleLine); 929 930 if (singleLine && mInput == null && ellipsize < 0) { 931 ellipsize = 3; // END 932 } 933 934 switch (ellipsize) { 935 case 1: 936 setEllipsize(TextUtils.TruncateAt.START); 937 break; 938 case 2: 939 setEllipsize(TextUtils.TruncateAt.MIDDLE); 940 break; 941 case 3: 942 setEllipsize(TextUtils.TruncateAt.END); 943 break; 944 case 4: 945 setHorizontalFadingEdgeEnabled(true); 946 setEllipsize(TextUtils.TruncateAt.MARQUEE); 947 break; 948 } 949 950 setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000)); 951 setHintTextColor(textColorHint); 952 setLinkTextColor(textColorLink); 953 if (textColorHighlight != 0) { 954 setHighlightColor(textColorHighlight); 955 } 956 setRawTextSize(textSize); 957 958 if (password || passwordInputType || webPasswordInputType || numberPasswordInputType) { 959 setTransformationMethod(PasswordTransformationMethod.getInstance()); 960 typefaceIndex = MONOSPACE; 961 } else if ((mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION)) 962 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { 963 typefaceIndex = MONOSPACE; 964 } 965 966 setTypefaceByIndex(typefaceIndex, styleIndex); 967 968 if (shadowcolor != 0) { 969 setShadowLayer(r, dx, dy, shadowcolor); 970 } 971 972 if (maxlength >= 0) { 973 setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) }); 974 } else { 975 setFilters(NO_FILTERS); 976 } 977 978 setText(text, bufferType); 979 if (hint != null) setHint(hint); 980 981 /* 982 * Views are not normally focusable unless specified to be. 983 * However, TextViews that have input or movement methods *are* 984 * focusable by default. 985 */ 986 a = context.obtainStyledAttributes(attrs, 987 com.android.internal.R.styleable.View, 988 defStyle, 0); 989 990 boolean focusable = mMovement != null || mInput != null; 991 boolean clickable = focusable; 992 boolean longClickable = focusable; 993 994 n = a.getIndexCount(); 995 for (int i = 0; i < n; i++) { 996 int attr = a.getIndex(i); 997 998 switch (attr) { 999 case com.android.internal.R.styleable.View_focusable: 1000 focusable = a.getBoolean(attr, focusable); 1001 break; 1002 1003 case com.android.internal.R.styleable.View_clickable: 1004 clickable = a.getBoolean(attr, clickable); 1005 break; 1006 1007 case com.android.internal.R.styleable.View_longClickable: 1008 longClickable = a.getBoolean(attr, longClickable); 1009 break; 1010 } 1011 } 1012 a.recycle(); 1013 1014 setFocusable(focusable); 1015 setClickable(clickable); 1016 setLongClickable(longClickable); 1017 1018 prepareCursorControllers(); 1019 1020 final ViewConfiguration viewConfiguration = ViewConfiguration.get(context); 1021 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 1022 mSquaredTouchSlopDistance = touchSlop * touchSlop; 1023 } 1024 1025 private void setTypefaceByIndex(int typefaceIndex, int styleIndex) { 1026 Typeface tf = null; 1027 switch (typefaceIndex) { 1028 case SANS: 1029 tf = Typeface.SANS_SERIF; 1030 break; 1031 1032 case SERIF: 1033 tf = Typeface.SERIF; 1034 break; 1035 1036 case MONOSPACE: 1037 tf = Typeface.MONOSPACE; 1038 break; 1039 } 1040 1041 setTypeface(tf, styleIndex); 1042 } 1043 1044 @Override 1045 public void setEnabled(boolean enabled) { 1046 if (enabled == isEnabled()) { 1047 return; 1048 } 1049 1050 if (!enabled) { 1051 // Hide the soft input if the currently active TextView is disabled 1052 InputMethodManager imm = InputMethodManager.peekInstance(); 1053 if (imm != null && imm.isActive(this)) { 1054 imm.hideSoftInputFromWindow(getWindowToken(), 0); 1055 } 1056 } 1057 super.setEnabled(enabled); 1058 } 1059 1060 /** 1061 * Sets the typeface and style in which the text should be displayed, 1062 * and turns on the fake bold and italic bits in the Paint if the 1063 * Typeface that you provided does not have all the bits in the 1064 * style that you specified. 1065 * 1066 * @attr ref android.R.styleable#TextView_typeface 1067 * @attr ref android.R.styleable#TextView_textStyle 1068 */ 1069 public void setTypeface(Typeface tf, int style) { 1070 if (style > 0) { 1071 if (tf == null) { 1072 tf = Typeface.defaultFromStyle(style); 1073 } else { 1074 tf = Typeface.create(tf, style); 1075 } 1076 1077 setTypeface(tf); 1078 // now compute what (if any) algorithmic styling is needed 1079 int typefaceStyle = tf != null ? tf.getStyle() : 0; 1080 int need = style & ~typefaceStyle; 1081 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); 1082 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); 1083 } else { 1084 mTextPaint.setFakeBoldText(false); 1085 mTextPaint.setTextSkewX(0); 1086 setTypeface(tf); 1087 } 1088 } 1089 1090 /** 1091 * Subclasses override this to specify that they have a KeyListener 1092 * by default even if not specifically called for in the XML options. 1093 */ 1094 protected boolean getDefaultEditable() { 1095 return false; 1096 } 1097 1098 /** 1099 * Subclasses override this to specify a default movement method. 1100 */ 1101 protected MovementMethod getDefaultMovementMethod() { 1102 return null; 1103 } 1104 1105 /** 1106 * Return the text the TextView is displaying. If setText() was called with 1107 * an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast 1108 * the return value from this method to Spannable or Editable, respectively. 1109 * 1110 * Note: The content of the return value should not be modified. If you want 1111 * a modifiable one, you should make your own copy first. 1112 */ 1113 @ViewDebug.CapturedViewProperty 1114 public CharSequence getText() { 1115 return mText; 1116 } 1117 1118 /** 1119 * Returns the length, in characters, of the text managed by this TextView 1120 */ 1121 public int length() { 1122 return mText.length(); 1123 } 1124 1125 /** 1126 * Return the text the TextView is displaying as an Editable object. If 1127 * the text is not editable, null is returned. 1128 * 1129 * @see #getText 1130 */ 1131 public Editable getEditableText() { 1132 return (mText instanceof Editable) ? (Editable)mText : null; 1133 } 1134 1135 /** 1136 * @return the height of one standard line in pixels. Note that markup 1137 * within the text can cause individual lines to be taller or shorter 1138 * than this height, and the layout may contain additional first- 1139 * or last-line padding. 1140 */ 1141 public int getLineHeight() { 1142 return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd); 1143 } 1144 1145 /** 1146 * @return the Layout that is currently being used to display the text. 1147 * This can be null if the text or width has recently changes. 1148 */ 1149 public final Layout getLayout() { 1150 return mLayout; 1151 } 1152 1153 /** 1154 * @return the current key listener for this TextView. 1155 * This will frequently be null for non-EditText TextViews. 1156 */ 1157 public final KeyListener getKeyListener() { 1158 return mInput; 1159 } 1160 1161 /** 1162 * Sets the key listener to be used with this TextView. This can be null 1163 * to disallow user input. Note that this method has significant and 1164 * subtle interactions with soft keyboards and other input method: 1165 * see {@link KeyListener#getInputType() KeyListener.getContentType()} 1166 * for important details. Calling this method will replace the current 1167 * content type of the text view with the content type returned by the 1168 * key listener. 1169 * <p> 1170 * Be warned that if you want a TextView with a key listener or movement 1171 * method not to be focusable, or if you want a TextView without a 1172 * key listener or movement method to be focusable, you must call 1173 * {@link #setFocusable} again after calling this to get the focusability 1174 * back the way you want it. 1175 * 1176 * @attr ref android.R.styleable#TextView_numeric 1177 * @attr ref android.R.styleable#TextView_digits 1178 * @attr ref android.R.styleable#TextView_phoneNumber 1179 * @attr ref android.R.styleable#TextView_inputMethod 1180 * @attr ref android.R.styleable#TextView_capitalize 1181 * @attr ref android.R.styleable#TextView_autoText 1182 */ 1183 public void setKeyListener(KeyListener input) { 1184 setKeyListenerOnly(input); 1185 fixFocusableAndClickableSettings(); 1186 1187 if (input != null) { 1188 try { 1189 mInputType = mInput.getInputType(); 1190 } catch (IncompatibleClassChangeError e) { 1191 mInputType = EditorInfo.TYPE_CLASS_TEXT; 1192 } 1193 // Change inputType, without affecting transformation. 1194 // No need to applySingleLine since mSingleLine is unchanged. 1195 setInputTypeSingleLine(mSingleLine); 1196 } else { 1197 mInputType = EditorInfo.TYPE_NULL; 1198 } 1199 1200 InputMethodManager imm = InputMethodManager.peekInstance(); 1201 if (imm != null) imm.restartInput(this); 1202 } 1203 1204 private void setKeyListenerOnly(KeyListener input) { 1205 mInput = input; 1206 if (mInput != null && !(mText instanceof Editable)) 1207 setText(mText); 1208 1209 setFilters((Editable) mText, mFilters); 1210 } 1211 1212 /** 1213 * @return the movement method being used for this TextView. 1214 * This will frequently be null for non-EditText TextViews. 1215 */ 1216 public final MovementMethod getMovementMethod() { 1217 return mMovement; 1218 } 1219 1220 /** 1221 * Sets the movement method (arrow key handler) to be used for 1222 * this TextView. This can be null to disallow using the arrow keys 1223 * to move the cursor or scroll the view. 1224 * <p> 1225 * Be warned that if you want a TextView with a key listener or movement 1226 * method not to be focusable, or if you want a TextView without a 1227 * key listener or movement method to be focusable, you must call 1228 * {@link #setFocusable} again after calling this to get the focusability 1229 * back the way you want it. 1230 */ 1231 public final void setMovementMethod(MovementMethod movement) { 1232 mMovement = movement; 1233 1234 if (mMovement != null && !(mText instanceof Spannable)) 1235 setText(mText); 1236 1237 fixFocusableAndClickableSettings(); 1238 1239 // SelectionModifierCursorController depends on textCanBeSelected, which depends on mMovement 1240 prepareCursorControllers(); 1241 } 1242 1243 private void fixFocusableAndClickableSettings() { 1244 if ((mMovement != null) || mInput != null) { 1245 setFocusable(true); 1246 setClickable(true); 1247 setLongClickable(true); 1248 } else { 1249 setFocusable(false); 1250 setClickable(false); 1251 setLongClickable(false); 1252 } 1253 } 1254 1255 /** 1256 * @return the current transformation method for this TextView. 1257 * This will frequently be null except for single-line and password 1258 * fields. 1259 */ 1260 public final TransformationMethod getTransformationMethod() { 1261 return mTransformation; 1262 } 1263 1264 /** 1265 * Sets the transformation that is applied to the text that this 1266 * TextView is displaying. 1267 * 1268 * @attr ref android.R.styleable#TextView_password 1269 * @attr ref android.R.styleable#TextView_singleLine 1270 */ 1271 public final void setTransformationMethod(TransformationMethod method) { 1272 if (method == mTransformation) { 1273 // Avoid the setText() below if the transformation is 1274 // the same. 1275 return; 1276 } 1277 if (mTransformation != null) { 1278 if (mText instanceof Spannable) { 1279 ((Spannable) mText).removeSpan(mTransformation); 1280 } 1281 } 1282 1283 mTransformation = method; 1284 1285 setText(mText); 1286 } 1287 1288 /** 1289 * Returns the top padding of the view, plus space for the top 1290 * Drawable if any. 1291 */ 1292 public int getCompoundPaddingTop() { 1293 final Drawables dr = mDrawables; 1294 if (dr == null || dr.mDrawableTop == null) { 1295 return mPaddingTop; 1296 } else { 1297 return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop; 1298 } 1299 } 1300 1301 /** 1302 * Returns the bottom padding of the view, plus space for the bottom 1303 * Drawable if any. 1304 */ 1305 public int getCompoundPaddingBottom() { 1306 final Drawables dr = mDrawables; 1307 if (dr == null || dr.mDrawableBottom == null) { 1308 return mPaddingBottom; 1309 } else { 1310 return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom; 1311 } 1312 } 1313 1314 /** 1315 * Returns the left padding of the view, plus space for the left 1316 * Drawable if any. 1317 */ 1318 public int getCompoundPaddingLeft() { 1319 final Drawables dr = mDrawables; 1320 if (dr == null || dr.mDrawableLeft == null) { 1321 return mPaddingLeft; 1322 } else { 1323 return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft; 1324 } 1325 } 1326 1327 /** 1328 * Returns the right padding of the view, plus space for the right 1329 * Drawable if any. 1330 */ 1331 public int getCompoundPaddingRight() { 1332 final Drawables dr = mDrawables; 1333 if (dr == null || dr.mDrawableRight == null) { 1334 return mPaddingRight; 1335 } else { 1336 return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight; 1337 } 1338 } 1339 1340 /** 1341 * Returns the extended top padding of the view, including both the 1342 * top Drawable if any and any extra space to keep more than maxLines 1343 * of text from showing. It is only valid to call this after measuring. 1344 */ 1345 public int getExtendedPaddingTop() { 1346 if (mMaxMode != LINES) { 1347 return getCompoundPaddingTop(); 1348 } 1349 1350 if (mLayout.getLineCount() <= mMaximum) { 1351 return getCompoundPaddingTop(); 1352 } 1353 1354 int top = getCompoundPaddingTop(); 1355 int bottom = getCompoundPaddingBottom(); 1356 int viewht = getHeight() - top - bottom; 1357 int layoutht = mLayout.getLineTop(mMaximum); 1358 1359 if (layoutht >= viewht) { 1360 return top; 1361 } 1362 1363 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1364 if (gravity == Gravity.TOP) { 1365 return top; 1366 } else if (gravity == Gravity.BOTTOM) { 1367 return top + viewht - layoutht; 1368 } else { // (gravity == Gravity.CENTER_VERTICAL) 1369 return top + (viewht - layoutht) / 2; 1370 } 1371 } 1372 1373 /** 1374 * Returns the extended bottom padding of the view, including both the 1375 * bottom Drawable if any and any extra space to keep more than maxLines 1376 * of text from showing. It is only valid to call this after measuring. 1377 */ 1378 public int getExtendedPaddingBottom() { 1379 if (mMaxMode != LINES) { 1380 return getCompoundPaddingBottom(); 1381 } 1382 1383 if (mLayout.getLineCount() <= mMaximum) { 1384 return getCompoundPaddingBottom(); 1385 } 1386 1387 int top = getCompoundPaddingTop(); 1388 int bottom = getCompoundPaddingBottom(); 1389 int viewht = getHeight() - top - bottom; 1390 int layoutht = mLayout.getLineTop(mMaximum); 1391 1392 if (layoutht >= viewht) { 1393 return bottom; 1394 } 1395 1396 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1397 if (gravity == Gravity.TOP) { 1398 return bottom + viewht - layoutht; 1399 } else if (gravity == Gravity.BOTTOM) { 1400 return bottom; 1401 } else { // (gravity == Gravity.CENTER_VERTICAL) 1402 return bottom + (viewht - layoutht) / 2; 1403 } 1404 } 1405 1406 /** 1407 * Returns the total left padding of the view, including the left 1408 * Drawable if any. 1409 */ 1410 public int getTotalPaddingLeft() { 1411 return getCompoundPaddingLeft(); 1412 } 1413 1414 /** 1415 * Returns the total right padding of the view, including the right 1416 * Drawable if any. 1417 */ 1418 public int getTotalPaddingRight() { 1419 return getCompoundPaddingRight(); 1420 } 1421 1422 /** 1423 * Returns the total top padding of the view, including the top 1424 * Drawable if any, the extra space to keep more than maxLines 1425 * from showing, and the vertical offset for gravity, if any. 1426 */ 1427 public int getTotalPaddingTop() { 1428 return getExtendedPaddingTop() + getVerticalOffset(true); 1429 } 1430 1431 /** 1432 * Returns the total bottom padding of the view, including the bottom 1433 * Drawable if any, the extra space to keep more than maxLines 1434 * from showing, and the vertical offset for gravity, if any. 1435 */ 1436 public int getTotalPaddingBottom() { 1437 return getExtendedPaddingBottom() + getBottomVerticalOffset(true); 1438 } 1439 1440 /** 1441 * Sets the Drawables (if any) to appear to the left of, above, 1442 * to the right of, and below the text. Use null if you do not 1443 * want a Drawable there. The Drawables must already have had 1444 * {@link Drawable#setBounds} called. 1445 * 1446 * @attr ref android.R.styleable#TextView_drawableLeft 1447 * @attr ref android.R.styleable#TextView_drawableTop 1448 * @attr ref android.R.styleable#TextView_drawableRight 1449 * @attr ref android.R.styleable#TextView_drawableBottom 1450 */ 1451 public void setCompoundDrawables(Drawable left, Drawable top, 1452 Drawable right, Drawable bottom) { 1453 Drawables dr = mDrawables; 1454 1455 final boolean drawables = left != null || top != null 1456 || right != null || bottom != null; 1457 1458 if (!drawables) { 1459 // Clearing drawables... can we free the data structure? 1460 if (dr != null) { 1461 if (dr.mDrawablePadding == 0) { 1462 mDrawables = null; 1463 } else { 1464 // We need to retain the last set padding, so just clear 1465 // out all of the fields in the existing structure. 1466 if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null); 1467 dr.mDrawableLeft = null; 1468 if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null); 1469 dr.mDrawableTop = null; 1470 if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null); 1471 dr.mDrawableRight = null; 1472 if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null); 1473 dr.mDrawableBottom = null; 1474 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 1475 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 1476 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1477 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1478 } 1479 } 1480 } else { 1481 if (dr == null) { 1482 mDrawables = dr = new Drawables(); 1483 } 1484 1485 if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) { 1486 dr.mDrawableLeft.setCallback(null); 1487 } 1488 dr.mDrawableLeft = left; 1489 1490 if (dr.mDrawableTop != top && dr.mDrawableTop != null) { 1491 dr.mDrawableTop.setCallback(null); 1492 } 1493 dr.mDrawableTop = top; 1494 1495 if (dr.mDrawableRight != right && dr.mDrawableRight != null) { 1496 dr.mDrawableRight.setCallback(null); 1497 } 1498 dr.mDrawableRight = right; 1499 1500 if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { 1501 dr.mDrawableBottom.setCallback(null); 1502 } 1503 dr.mDrawableBottom = bottom; 1504 1505 final Rect compoundRect = dr.mCompoundRect; 1506 int[] state; 1507 1508 state = getDrawableState(); 1509 1510 if (left != null) { 1511 left.setState(state); 1512 left.copyBounds(compoundRect); 1513 left.setCallback(this); 1514 dr.mDrawableSizeLeft = compoundRect.width(); 1515 dr.mDrawableHeightLeft = compoundRect.height(); 1516 } else { 1517 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 1518 } 1519 1520 if (right != null) { 1521 right.setState(state); 1522 right.copyBounds(compoundRect); 1523 right.setCallback(this); 1524 dr.mDrawableSizeRight = compoundRect.width(); 1525 dr.mDrawableHeightRight = compoundRect.height(); 1526 } else { 1527 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 1528 } 1529 1530 if (top != null) { 1531 top.setState(state); 1532 top.copyBounds(compoundRect); 1533 top.setCallback(this); 1534 dr.mDrawableSizeTop = compoundRect.height(); 1535 dr.mDrawableWidthTop = compoundRect.width(); 1536 } else { 1537 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1538 } 1539 1540 if (bottom != null) { 1541 bottom.setState(state); 1542 bottom.copyBounds(compoundRect); 1543 bottom.setCallback(this); 1544 dr.mDrawableSizeBottom = compoundRect.height(); 1545 dr.mDrawableWidthBottom = compoundRect.width(); 1546 } else { 1547 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1548 } 1549 } 1550 1551 invalidate(); 1552 requestLayout(); 1553 } 1554 1555 /** 1556 * Sets the Drawables (if any) to appear to the left of, above, 1557 * to the right of, and below the text. Use 0 if you do not 1558 * want a Drawable there. The Drawables' bounds will be set to 1559 * their intrinsic bounds. 1560 * 1561 * @param left Resource identifier of the left Drawable. 1562 * @param top Resource identifier of the top Drawable. 1563 * @param right Resource identifier of the right Drawable. 1564 * @param bottom Resource identifier of the bottom Drawable. 1565 * 1566 * @attr ref android.R.styleable#TextView_drawableLeft 1567 * @attr ref android.R.styleable#TextView_drawableTop 1568 * @attr ref android.R.styleable#TextView_drawableRight 1569 * @attr ref android.R.styleable#TextView_drawableBottom 1570 */ 1571 public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) { 1572 final Resources resources = getContext().getResources(); 1573 setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null, 1574 top != 0 ? resources.getDrawable(top) : null, 1575 right != 0 ? resources.getDrawable(right) : null, 1576 bottom != 0 ? resources.getDrawable(bottom) : null); 1577 } 1578 1579 /** 1580 * Sets the Drawables (if any) to appear to the left of, above, 1581 * to the right of, and below the text. Use null if you do not 1582 * want a Drawable there. The Drawables' bounds will be set to 1583 * their intrinsic bounds. 1584 * 1585 * @attr ref android.R.styleable#TextView_drawableLeft 1586 * @attr ref android.R.styleable#TextView_drawableTop 1587 * @attr ref android.R.styleable#TextView_drawableRight 1588 * @attr ref android.R.styleable#TextView_drawableBottom 1589 */ 1590 public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, 1591 Drawable right, Drawable bottom) { 1592 1593 if (left != null) { 1594 left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight()); 1595 } 1596 if (right != null) { 1597 right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight()); 1598 } 1599 if (top != null) { 1600 top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); 1601 } 1602 if (bottom != null) { 1603 bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); 1604 } 1605 setCompoundDrawables(left, top, right, bottom); 1606 } 1607 1608 /** 1609 * Returns drawables for the left, top, right, and bottom borders. 1610 */ 1611 public Drawable[] getCompoundDrawables() { 1612 final Drawables dr = mDrawables; 1613 if (dr != null) { 1614 return new Drawable[] { 1615 dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom 1616 }; 1617 } else { 1618 return new Drawable[] { null, null, null, null }; 1619 } 1620 } 1621 1622 /** 1623 * Sets the size of the padding between the compound drawables and 1624 * the text. 1625 * 1626 * @attr ref android.R.styleable#TextView_drawablePadding 1627 */ 1628 public void setCompoundDrawablePadding(int pad) { 1629 Drawables dr = mDrawables; 1630 if (pad == 0) { 1631 if (dr != null) { 1632 dr.mDrawablePadding = pad; 1633 } 1634 } else { 1635 if (dr == null) { 1636 mDrawables = dr = new Drawables(); 1637 } 1638 dr.mDrawablePadding = pad; 1639 } 1640 1641 invalidate(); 1642 requestLayout(); 1643 } 1644 1645 /** 1646 * Returns the padding between the compound drawables and the text. 1647 */ 1648 public int getCompoundDrawablePadding() { 1649 final Drawables dr = mDrawables; 1650 return dr != null ? dr.mDrawablePadding : 0; 1651 } 1652 1653 @Override 1654 public void setPadding(int left, int top, int right, int bottom) { 1655 if (left != mPaddingLeft || 1656 right != mPaddingRight || 1657 top != mPaddingTop || 1658 bottom != mPaddingBottom) { 1659 nullLayouts(); 1660 } 1661 1662 // the super call will requestLayout() 1663 super.setPadding(left, top, right, bottom); 1664 invalidate(); 1665 } 1666 1667 /** 1668 * Gets the autolink mask of the text. See {@link 1669 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 1670 * possible values. 1671 * 1672 * @attr ref android.R.styleable#TextView_autoLink 1673 */ 1674 public final int getAutoLinkMask() { 1675 return mAutoLinkMask; 1676 } 1677 1678 /** 1679 * Sets the text color, size, style, hint color, and highlight color 1680 * from the specified TextAppearance resource. 1681 */ 1682 public void setTextAppearance(Context context, int resid) { 1683 TypedArray appearance = 1684 context.obtainStyledAttributes(resid, 1685 com.android.internal.R.styleable.TextAppearance); 1686 1687 int color; 1688 ColorStateList colors; 1689 int ts; 1690 1691 color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0); 1692 if (color != 0) { 1693 setHighlightColor(color); 1694 } 1695 1696 colors = appearance.getColorStateList(com.android.internal.R.styleable. 1697 TextAppearance_textColor); 1698 if (colors != null) { 1699 setTextColor(colors); 1700 } 1701 1702 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable. 1703 TextAppearance_textSize, 0); 1704 if (ts != 0) { 1705 setRawTextSize(ts); 1706 } 1707 1708 colors = appearance.getColorStateList(com.android.internal.R.styleable. 1709 TextAppearance_textColorHint); 1710 if (colors != null) { 1711 setHintTextColor(colors); 1712 } 1713 1714 colors = appearance.getColorStateList(com.android.internal.R.styleable. 1715 TextAppearance_textColorLink); 1716 if (colors != null) { 1717 setLinkTextColor(colors); 1718 } 1719 1720 int typefaceIndex, styleIndex; 1721 1722 typefaceIndex = appearance.getInt(com.android.internal.R.styleable. 1723 TextAppearance_typeface, -1); 1724 styleIndex = appearance.getInt(com.android.internal.R.styleable. 1725 TextAppearance_textStyle, -1); 1726 1727 setTypefaceByIndex(typefaceIndex, styleIndex); 1728 1729 appearance.recycle(); 1730 } 1731 1732 /** 1733 * @return the size (in pixels) of the default text size in this TextView. 1734 */ 1735 public float getTextSize() { 1736 return mTextPaint.getTextSize(); 1737 } 1738 1739 /** 1740 * Set the default text size to the given value, interpreted as "scaled 1741 * pixel" units. This size is adjusted based on the current density and 1742 * user font size preference. 1743 * 1744 * @param size The scaled pixel size. 1745 * 1746 * @attr ref android.R.styleable#TextView_textSize 1747 */ 1748 @android.view.RemotableViewMethod 1749 public void setTextSize(float size) { 1750 setTextSize(TypedValue.COMPLEX_UNIT_SP, size); 1751 } 1752 1753 /** 1754 * Set the default text size to a given unit and value. See {@link 1755 * TypedValue} for the possible dimension units. 1756 * 1757 * @param unit The desired dimension unit. 1758 * @param size The desired size in the given units. 1759 * 1760 * @attr ref android.R.styleable#TextView_textSize 1761 */ 1762 public void setTextSize(int unit, float size) { 1763 Context c = getContext(); 1764 Resources r; 1765 1766 if (c == null) 1767 r = Resources.getSystem(); 1768 else 1769 r = c.getResources(); 1770 1771 setRawTextSize(TypedValue.applyDimension( 1772 unit, size, r.getDisplayMetrics())); 1773 } 1774 1775 private void setRawTextSize(float size) { 1776 if (size != mTextPaint.getTextSize()) { 1777 mTextPaint.setTextSize(size); 1778 1779 if (mLayout != null) { 1780 nullLayouts(); 1781 requestLayout(); 1782 invalidate(); 1783 } 1784 } 1785 } 1786 1787 /** 1788 * @return the extent by which text is currently being stretched 1789 * horizontally. This will usually be 1. 1790 */ 1791 public float getTextScaleX() { 1792 return mTextPaint.getTextScaleX(); 1793 } 1794 1795 /** 1796 * Sets the extent by which text should be stretched horizontally. 1797 * 1798 * @attr ref android.R.styleable#TextView_textScaleX 1799 */ 1800 @android.view.RemotableViewMethod 1801 public void setTextScaleX(float size) { 1802 if (size != mTextPaint.getTextScaleX()) { 1803 mUserSetTextScaleX = true; 1804 mTextPaint.setTextScaleX(size); 1805 1806 if (mLayout != null) { 1807 nullLayouts(); 1808 requestLayout(); 1809 invalidate(); 1810 } 1811 } 1812 } 1813 1814 /** 1815 * Sets the typeface and style in which the text should be displayed. 1816 * Note that not all Typeface families actually have bold and italic 1817 * variants, so you may need to use 1818 * {@link #setTypeface(Typeface, int)} to get the appearance 1819 * that you actually want. 1820 * 1821 * @attr ref android.R.styleable#TextView_typeface 1822 * @attr ref android.R.styleable#TextView_textStyle 1823 */ 1824 public void setTypeface(Typeface tf) { 1825 if (mTextPaint.getTypeface() != tf) { 1826 mTextPaint.setTypeface(tf); 1827 1828 if (mLayout != null) { 1829 nullLayouts(); 1830 requestLayout(); 1831 invalidate(); 1832 } 1833 } 1834 } 1835 1836 /** 1837 * @return the current typeface and style in which the text is being 1838 * displayed. 1839 */ 1840 public Typeface getTypeface() { 1841 return mTextPaint.getTypeface(); 1842 } 1843 1844 /** 1845 * Sets the text color for all the states (normal, selected, 1846 * focused) to be this color. 1847 * 1848 * @attr ref android.R.styleable#TextView_textColor 1849 */ 1850 @android.view.RemotableViewMethod 1851 public void setTextColor(int color) { 1852 mTextColor = ColorStateList.valueOf(color); 1853 updateTextColors(); 1854 } 1855 1856 /** 1857 * Sets the text color. 1858 * 1859 * @attr ref android.R.styleable#TextView_textColor 1860 */ 1861 public void setTextColor(ColorStateList colors) { 1862 if (colors == null) { 1863 throw new NullPointerException(); 1864 } 1865 1866 mTextColor = colors; 1867 updateTextColors(); 1868 } 1869 1870 /** 1871 * Return the set of text colors. 1872 * 1873 * @return Returns the set of text colors. 1874 */ 1875 public final ColorStateList getTextColors() { 1876 return mTextColor; 1877 } 1878 1879 /** 1880 * <p>Return the current color selected for normal text.</p> 1881 * 1882 * @return Returns the current text color. 1883 */ 1884 public final int getCurrentTextColor() { 1885 return mCurTextColor; 1886 } 1887 1888 /** 1889 * Sets the color used to display the selection highlight. 1890 * 1891 * @attr ref android.R.styleable#TextView_textColorHighlight 1892 */ 1893 @android.view.RemotableViewMethod 1894 public void setHighlightColor(int color) { 1895 if (mHighlightColor != color) { 1896 mHighlightColor = color; 1897 invalidate(); 1898 } 1899 } 1900 1901 /** 1902 * Gives the text a shadow of the specified radius and color, the specified 1903 * distance from its normal position. 1904 * 1905 * @attr ref android.R.styleable#TextView_shadowColor 1906 * @attr ref android.R.styleable#TextView_shadowDx 1907 * @attr ref android.R.styleable#TextView_shadowDy 1908 * @attr ref android.R.styleable#TextView_shadowRadius 1909 */ 1910 public void setShadowLayer(float radius, float dx, float dy, int color) { 1911 mTextPaint.setShadowLayer(radius, dx, dy, color); 1912 1913 mShadowRadius = radius; 1914 mShadowDx = dx; 1915 mShadowDy = dy; 1916 1917 invalidate(); 1918 } 1919 1920 /** 1921 * @return the base paint used for the text. Please use this only to 1922 * consult the Paint's properties and not to change them. 1923 */ 1924 public TextPaint getPaint() { 1925 return mTextPaint; 1926 } 1927 1928 /** 1929 * Sets the autolink mask of the text. See {@link 1930 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 1931 * possible values. 1932 * 1933 * @attr ref android.R.styleable#TextView_autoLink 1934 */ 1935 @android.view.RemotableViewMethod 1936 public final void setAutoLinkMask(int mask) { 1937 mAutoLinkMask = mask; 1938 } 1939 1940 /** 1941 * Sets whether the movement method will automatically be set to 1942 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 1943 * set to nonzero and links are detected in {@link #setText}. 1944 * The default is true. 1945 * 1946 * @attr ref android.R.styleable#TextView_linksClickable 1947 */ 1948 @android.view.RemotableViewMethod 1949 public final void setLinksClickable(boolean whether) { 1950 mLinksClickable = whether; 1951 } 1952 1953 /** 1954 * Returns whether the movement method will automatically be set to 1955 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 1956 * set to nonzero and links are detected in {@link #setText}. 1957 * The default is true. 1958 * 1959 * @attr ref android.R.styleable#TextView_linksClickable 1960 */ 1961 public final boolean getLinksClickable() { 1962 return mLinksClickable; 1963 } 1964 1965 /** 1966 * Returns the list of URLSpans attached to the text 1967 * (by {@link Linkify} or otherwise) if any. You can call 1968 * {@link URLSpan#getURL} on them to find where they link to 1969 * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd} 1970 * to find the region of the text they are attached to. 1971 */ 1972 public URLSpan[] getUrls() { 1973 if (mText instanceof Spanned) { 1974 return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class); 1975 } else { 1976 return new URLSpan[0]; 1977 } 1978 } 1979 1980 /** 1981 * Sets the color of the hint text. 1982 * 1983 * @attr ref android.R.styleable#TextView_textColorHint 1984 */ 1985 @android.view.RemotableViewMethod 1986 public final void setHintTextColor(int color) { 1987 mHintTextColor = ColorStateList.valueOf(color); 1988 updateTextColors(); 1989 } 1990 1991 /** 1992 * Sets the color of the hint text. 1993 * 1994 * @attr ref android.R.styleable#TextView_textColorHint 1995 */ 1996 public final void setHintTextColor(ColorStateList colors) { 1997 mHintTextColor = colors; 1998 updateTextColors(); 1999 } 2000 2001 /** 2002 * <p>Return the color used to paint the hint text.</p> 2003 * 2004 * @return Returns the list of hint text colors. 2005 */ 2006 public final ColorStateList getHintTextColors() { 2007 return mHintTextColor; 2008 } 2009 2010 /** 2011 * <p>Return the current color selected to paint the hint text.</p> 2012 * 2013 * @return Returns the current hint text color. 2014 */ 2015 public final int getCurrentHintTextColor() { 2016 return mHintTextColor != null ? mCurHintTextColor : mCurTextColor; 2017 } 2018 2019 /** 2020 * Sets the color of links in the text. 2021 * 2022 * @attr ref android.R.styleable#TextView_textColorLink 2023 */ 2024 @android.view.RemotableViewMethod 2025 public final void setLinkTextColor(int color) { 2026 mLinkTextColor = ColorStateList.valueOf(color); 2027 updateTextColors(); 2028 } 2029 2030 /** 2031 * Sets the color of links in the text. 2032 * 2033 * @attr ref android.R.styleable#TextView_textColorLink 2034 */ 2035 public final void setLinkTextColor(ColorStateList colors) { 2036 mLinkTextColor = colors; 2037 updateTextColors(); 2038 } 2039 2040 /** 2041 * <p>Returns the color used to paint links in the text.</p> 2042 * 2043 * @return Returns the list of link text colors. 2044 */ 2045 public final ColorStateList getLinkTextColors() { 2046 return mLinkTextColor; 2047 } 2048 2049 /** 2050 * Sets the horizontal alignment of the text and the 2051 * vertical gravity that will be used when there is extra space 2052 * in the TextView beyond what is required for the text itself. 2053 * 2054 * @see android.view.Gravity 2055 * @attr ref android.R.styleable#TextView_gravity 2056 */ 2057 public void setGravity(int gravity) { 2058 if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) { 2059 gravity |= Gravity.LEFT; 2060 } 2061 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 2062 gravity |= Gravity.TOP; 2063 } 2064 2065 boolean newLayout = false; 2066 2067 if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) != 2068 (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK)) { 2069 newLayout = true; 2070 } 2071 2072 if (gravity != mGravity) { 2073 invalidate(); 2074 } 2075 2076 mGravity = gravity; 2077 2078 if (mLayout != null && newLayout) { 2079 // XXX this is heavy-handed because no actual content changes. 2080 int want = mLayout.getWidth(); 2081 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 2082 2083 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 2084 mRight - mLeft - getCompoundPaddingLeft() - 2085 getCompoundPaddingRight(), true); 2086 } 2087 } 2088 2089 /** 2090 * Returns the horizontal and vertical alignment of this TextView. 2091 * 2092 * @see android.view.Gravity 2093 * @attr ref android.R.styleable#TextView_gravity 2094 */ 2095 public int getGravity() { 2096 return mGravity; 2097 } 2098 2099 /** 2100 * @return the flags on the Paint being used to display the text. 2101 * @see Paint#getFlags 2102 */ 2103 public int getPaintFlags() { 2104 return mTextPaint.getFlags(); 2105 } 2106 2107 /** 2108 * Sets flags on the Paint being used to display the text and 2109 * reflows the text if they are different from the old flags. 2110 * @see Paint#setFlags 2111 */ 2112 @android.view.RemotableViewMethod 2113 public void setPaintFlags(int flags) { 2114 if (mTextPaint.getFlags() != flags) { 2115 mTextPaint.setFlags(flags); 2116 2117 if (mLayout != null) { 2118 nullLayouts(); 2119 requestLayout(); 2120 invalidate(); 2121 } 2122 } 2123 } 2124 2125 /** 2126 * Sets whether the text should be allowed to be wider than the 2127 * View is. If false, it will be wrapped to the width of the View. 2128 * 2129 * @attr ref android.R.styleable#TextView_scrollHorizontally 2130 */ 2131 public void setHorizontallyScrolling(boolean whether) { 2132 mHorizontallyScrolling = whether; 2133 2134 if (mLayout != null) { 2135 nullLayouts(); 2136 requestLayout(); 2137 invalidate(); 2138 } 2139 } 2140 2141 /** 2142 * Makes the TextView at least this many lines tall. 2143 * 2144 * Setting this value overrides any other (minimum) height setting. A single line TextView will 2145 * set this value to 1. 2146 * 2147 * @attr ref android.R.styleable#TextView_minLines 2148 */ 2149 @android.view.RemotableViewMethod 2150 public void setMinLines(int minlines) { 2151 mMinimum = minlines; 2152 mMinMode = LINES; 2153 2154 requestLayout(); 2155 invalidate(); 2156 } 2157 2158 /** 2159 * Makes the TextView at least this many pixels tall. 2160 * 2161 * Setting this value overrides any other (minimum) number of lines setting. 2162 * 2163 * @attr ref android.R.styleable#TextView_minHeight 2164 */ 2165 @android.view.RemotableViewMethod 2166 public void setMinHeight(int minHeight) { 2167 mMinimum = minHeight; 2168 mMinMode = PIXELS; 2169 2170 requestLayout(); 2171 invalidate(); 2172 } 2173 2174 /** 2175 * Makes the TextView at most this many lines tall. 2176 * 2177 * Setting this value overrides any other (maximum) height setting. 2178 * 2179 * @attr ref android.R.styleable#TextView_maxLines 2180 */ 2181 @android.view.RemotableViewMethod 2182 public void setMaxLines(int maxlines) { 2183 mMaximum = maxlines; 2184 mMaxMode = LINES; 2185 2186 requestLayout(); 2187 invalidate(); 2188 } 2189 2190 /** 2191 * Makes the TextView at most this many pixels tall. This option is mutually exclusive with the 2192 * {@link #setMaxLines(int)} method. 2193 * 2194 * Setting this value overrides any other (maximum) number of lines setting. 2195 * 2196 * @attr ref android.R.styleable#TextView_maxHeight 2197 */ 2198 @android.view.RemotableViewMethod 2199 public void setMaxHeight(int maxHeight) { 2200 mMaximum = maxHeight; 2201 mMaxMode = PIXELS; 2202 2203 requestLayout(); 2204 invalidate(); 2205 } 2206 2207 /** 2208 * Makes the TextView exactly this many lines tall. 2209 * 2210 * Note that setting this value overrides any other (minimum / maximum) number of lines or 2211 * height setting. A single line TextView will set this value to 1. 2212 * 2213 * @attr ref android.R.styleable#TextView_lines 2214 */ 2215 @android.view.RemotableViewMethod 2216 public void setLines(int lines) { 2217 mMaximum = mMinimum = lines; 2218 mMaxMode = mMinMode = LINES; 2219 2220 requestLayout(); 2221 invalidate(); 2222 } 2223 2224 /** 2225 * Makes the TextView exactly this many pixels tall. 2226 * You could do the same thing by specifying this number in the 2227 * LayoutParams. 2228 * 2229 * Note that setting this value overrides any other (minimum / maximum) number of lines or 2230 * height setting. 2231 * 2232 * @attr ref android.R.styleable#TextView_height 2233 */ 2234 @android.view.RemotableViewMethod 2235 public void setHeight(int pixels) { 2236 mMaximum = mMinimum = pixels; 2237 mMaxMode = mMinMode = PIXELS; 2238 2239 requestLayout(); 2240 invalidate(); 2241 } 2242 2243 /** 2244 * Makes the TextView at least this many ems wide 2245 * 2246 * @attr ref android.R.styleable#TextView_minEms 2247 */ 2248 @android.view.RemotableViewMethod 2249 public void setMinEms(int minems) { 2250 mMinWidth = minems; 2251 mMinWidthMode = EMS; 2252 2253 requestLayout(); 2254 invalidate(); 2255 } 2256 2257 /** 2258 * Makes the TextView at least this many pixels wide 2259 * 2260 * @attr ref android.R.styleable#TextView_minWidth 2261 */ 2262 @android.view.RemotableViewMethod 2263 public void setMinWidth(int minpixels) { 2264 mMinWidth = minpixels; 2265 mMinWidthMode = PIXELS; 2266 2267 requestLayout(); 2268 invalidate(); 2269 } 2270 2271 /** 2272 * Makes the TextView at most this many ems wide 2273 * 2274 * @attr ref android.R.styleable#TextView_maxEms 2275 */ 2276 @android.view.RemotableViewMethod 2277 public void setMaxEms(int maxems) { 2278 mMaxWidth = maxems; 2279 mMaxWidthMode = EMS; 2280 2281 requestLayout(); 2282 invalidate(); 2283 } 2284 2285 /** 2286 * Makes the TextView at most this many pixels wide 2287 * 2288 * @attr ref android.R.styleable#TextView_maxWidth 2289 */ 2290 @android.view.RemotableViewMethod 2291 public void setMaxWidth(int maxpixels) { 2292 mMaxWidth = maxpixels; 2293 mMaxWidthMode = PIXELS; 2294 2295 requestLayout(); 2296 invalidate(); 2297 } 2298 2299 /** 2300 * Makes the TextView exactly this many ems wide 2301 * 2302 * @attr ref android.R.styleable#TextView_ems 2303 */ 2304 @android.view.RemotableViewMethod 2305 public void setEms(int ems) { 2306 mMaxWidth = mMinWidth = ems; 2307 mMaxWidthMode = mMinWidthMode = EMS; 2308 2309 requestLayout(); 2310 invalidate(); 2311 } 2312 2313 /** 2314 * Makes the TextView exactly this many pixels wide. 2315 * You could do the same thing by specifying this number in the 2316 * LayoutParams. 2317 * 2318 * @attr ref android.R.styleable#TextView_width 2319 */ 2320 @android.view.RemotableViewMethod 2321 public void setWidth(int pixels) { 2322 mMaxWidth = mMinWidth = pixels; 2323 mMaxWidthMode = mMinWidthMode = PIXELS; 2324 2325 requestLayout(); 2326 invalidate(); 2327 } 2328 2329 2330 /** 2331 * Sets line spacing for this TextView. Each line will have its height 2332 * multiplied by <code>mult</code> and have <code>add</code> added to it. 2333 * 2334 * @attr ref android.R.styleable#TextView_lineSpacingExtra 2335 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 2336 */ 2337 public void setLineSpacing(float add, float mult) { 2338 mSpacingMult = mult; 2339 mSpacingAdd = add; 2340 2341 if (mLayout != null) { 2342 nullLayouts(); 2343 requestLayout(); 2344 invalidate(); 2345 } 2346 } 2347 2348 /** 2349 * Convenience method: Append the specified text to the TextView's 2350 * display buffer, upgrading it to BufferType.EDITABLE if it was 2351 * not already editable. 2352 */ 2353 public final void append(CharSequence text) { 2354 append(text, 0, text.length()); 2355 } 2356 2357 /** 2358 * Convenience method: Append the specified text slice to the TextView's 2359 * display buffer, upgrading it to BufferType.EDITABLE if it was 2360 * not already editable. 2361 */ 2362 public void append(CharSequence text, int start, int end) { 2363 if (!(mText instanceof Editable)) { 2364 setText(mText, BufferType.EDITABLE); 2365 } 2366 2367 ((Editable) mText).append(text, start, end); 2368 } 2369 2370 private void updateTextColors() { 2371 boolean inval = false; 2372 int color = mTextColor.getColorForState(getDrawableState(), 0); 2373 if (color != mCurTextColor) { 2374 mCurTextColor = color; 2375 inval = true; 2376 } 2377 if (mLinkTextColor != null) { 2378 color = mLinkTextColor.getColorForState(getDrawableState(), 0); 2379 if (color != mTextPaint.linkColor) { 2380 mTextPaint.linkColor = color; 2381 inval = true; 2382 } 2383 } 2384 if (mHintTextColor != null) { 2385 color = mHintTextColor.getColorForState(getDrawableState(), 0); 2386 if (color != mCurHintTextColor && mText.length() == 0) { 2387 mCurHintTextColor = color; 2388 inval = true; 2389 } 2390 } 2391 if (inval) { 2392 invalidate(); 2393 } 2394 } 2395 2396 @Override 2397 protected void drawableStateChanged() { 2398 super.drawableStateChanged(); 2399 if (mTextColor != null && mTextColor.isStateful() 2400 || (mHintTextColor != null && mHintTextColor.isStateful()) 2401 || (mLinkTextColor != null && mLinkTextColor.isStateful())) { 2402 updateTextColors(); 2403 } 2404 2405 final Drawables dr = mDrawables; 2406 if (dr != null) { 2407 int[] state = getDrawableState(); 2408 if (dr.mDrawableTop != null && dr.mDrawableTop.isStateful()) { 2409 dr.mDrawableTop.setState(state); 2410 } 2411 if (dr.mDrawableBottom != null && dr.mDrawableBottom.isStateful()) { 2412 dr.mDrawableBottom.setState(state); 2413 } 2414 if (dr.mDrawableLeft != null && dr.mDrawableLeft.isStateful()) { 2415 dr.mDrawableLeft.setState(state); 2416 } 2417 if (dr.mDrawableRight != null && dr.mDrawableRight.isStateful()) { 2418 dr.mDrawableRight.setState(state); 2419 } 2420 } 2421 } 2422 2423 /** 2424 * User interface state that is stored by TextView for implementing 2425 * {@link View#onSaveInstanceState}. 2426 */ 2427 public static class SavedState extends BaseSavedState { 2428 int selStart; 2429 int selEnd; 2430 CharSequence text; 2431 boolean frozenWithFocus; 2432 CharSequence error; 2433 2434 SavedState(Parcelable superState) { 2435 super(superState); 2436 } 2437 2438 @Override 2439 public void writeToParcel(Parcel out, int flags) { 2440 super.writeToParcel(out, flags); 2441 out.writeInt(selStart); 2442 out.writeInt(selEnd); 2443 out.writeInt(frozenWithFocus ? 1 : 0); 2444 TextUtils.writeToParcel(text, out, flags); 2445 2446 if (error == null) { 2447 out.writeInt(0); 2448 } else { 2449 out.writeInt(1); 2450 TextUtils.writeToParcel(error, out, flags); 2451 } 2452 } 2453 2454 @Override 2455 public String toString() { 2456 String str = "TextView.SavedState{" 2457 + Integer.toHexString(System.identityHashCode(this)) 2458 + " start=" + selStart + " end=" + selEnd; 2459 if (text != null) { 2460 str += " text=" + text; 2461 } 2462 return str + "}"; 2463 } 2464 2465 @SuppressWarnings("hiding") 2466 public static final Parcelable.Creator<SavedState> CREATOR 2467 = new Parcelable.Creator<SavedState>() { 2468 public SavedState createFromParcel(Parcel in) { 2469 return new SavedState(in); 2470 } 2471 2472 public SavedState[] newArray(int size) { 2473 return new SavedState[size]; 2474 } 2475 }; 2476 2477 private SavedState(Parcel in) { 2478 super(in); 2479 selStart = in.readInt(); 2480 selEnd = in.readInt(); 2481 frozenWithFocus = (in.readInt() != 0); 2482 text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 2483 2484 if (in.readInt() != 0) { 2485 error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 2486 } 2487 } 2488 } 2489 2490 @Override 2491 public Parcelable onSaveInstanceState() { 2492 Parcelable superState = super.onSaveInstanceState(); 2493 2494 // Save state if we are forced to 2495 boolean save = mFreezesText; 2496 int start = 0; 2497 int end = 0; 2498 2499 if (mText != null) { 2500 start = getSelectionStart(); 2501 end = getSelectionEnd(); 2502 if (start >= 0 || end >= 0) { 2503 // Or save state if there is a selection 2504 save = true; 2505 } 2506 } 2507 2508 if (save) { 2509 SavedState ss = new SavedState(superState); 2510 // XXX Should also save the current scroll position! 2511 ss.selStart = start; 2512 ss.selEnd = end; 2513 2514 if (mText instanceof Spanned) { 2515 /* 2516 * Calling setText() strips off any ChangeWatchers; 2517 * strip them now to avoid leaking references. 2518 * But do it to a copy so that if there are any 2519 * further changes to the text of this view, it 2520 * won't get into an inconsistent state. 2521 */ 2522 2523 Spannable sp = new SpannableString(mText); 2524 2525 for (ChangeWatcher cw : 2526 sp.getSpans(0, sp.length(), ChangeWatcher.class)) { 2527 sp.removeSpan(cw); 2528 } 2529 2530 ss.text = sp; 2531 } else { 2532 ss.text = mText.toString(); 2533 } 2534 2535 if (isFocused() && start >= 0 && end >= 0) { 2536 ss.frozenWithFocus = true; 2537 } 2538 2539 ss.error = mError; 2540 2541 return ss; 2542 } 2543 2544 return superState; 2545 } 2546 2547 @Override 2548 public void onRestoreInstanceState(Parcelable state) { 2549 if (!(state instanceof SavedState)) { 2550 super.onRestoreInstanceState(state); 2551 return; 2552 } 2553 2554 SavedState ss = (SavedState)state; 2555 super.onRestoreInstanceState(ss.getSuperState()); 2556 2557 // XXX restore buffer type too, as well as lots of other stuff 2558 if (ss.text != null) { 2559 setText(ss.text); 2560 } 2561 2562 if (ss.selStart >= 0 && ss.selEnd >= 0) { 2563 if (mText instanceof Spannable) { 2564 int len = mText.length(); 2565 2566 if (ss.selStart > len || ss.selEnd > len) { 2567 String restored = ""; 2568 2569 if (ss.text != null) { 2570 restored = "(restored) "; 2571 } 2572 2573 Log.e(LOG_TAG, "Saved cursor position " + ss.selStart + 2574 "/" + ss.selEnd + " out of range for " + restored + 2575 "text " + mText); 2576 } else { 2577 Selection.setSelection((Spannable) mText, ss.selStart, 2578 ss.selEnd); 2579 2580 if (ss.frozenWithFocus) { 2581 mFrozenWithFocus = true; 2582 } 2583 } 2584 } 2585 } 2586 2587 if (ss.error != null) { 2588 final CharSequence error = ss.error; 2589 // Display the error later, after the first layout pass 2590 post(new Runnable() { 2591 public void run() { 2592 setError(error); 2593 } 2594 }); 2595 } 2596 } 2597 2598 /** 2599 * Control whether this text view saves its entire text contents when 2600 * freezing to an icicle, in addition to dynamic state such as cursor 2601 * position. By default this is false, not saving the text. Set to true 2602 * if the text in the text view is not being saved somewhere else in 2603 * persistent storage (such as in a content provider) so that if the 2604 * view is later thawed the user will not lose their data. 2605 * 2606 * @param freezesText Controls whether a frozen icicle should include the 2607 * entire text data: true to include it, false to not. 2608 * 2609 * @attr ref android.R.styleable#TextView_freezesText 2610 */ 2611 @android.view.RemotableViewMethod 2612 public void setFreezesText(boolean freezesText) { 2613 mFreezesText = freezesText; 2614 } 2615 2616 /** 2617 * Return whether this text view is including its entire text contents 2618 * in frozen icicles. 2619 * 2620 * @return Returns true if text is included, false if it isn't. 2621 * 2622 * @see #setFreezesText 2623 */ 2624 public boolean getFreezesText() { 2625 return mFreezesText; 2626 } 2627 2628 /////////////////////////////////////////////////////////////////////////// 2629 2630 /** 2631 * Sets the Factory used to create new Editables. 2632 */ 2633 public final void setEditableFactory(Editable.Factory factory) { 2634 mEditableFactory = factory; 2635 setText(mText); 2636 } 2637 2638 /** 2639 * Sets the Factory used to create new Spannables. 2640 */ 2641 public final void setSpannableFactory(Spannable.Factory factory) { 2642 mSpannableFactory = factory; 2643 setText(mText); 2644 } 2645 2646 /** 2647 * Sets the string value of the TextView. TextView <em>does not</em> accept 2648 * HTML-like formatting, which you can do with text strings in XML resource files. 2649 * To style your strings, attach android.text.style.* objects to a 2650 * {@link android.text.SpannableString SpannableString}, or see the 2651 * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources"> 2652 * Available Resource Types</a> documentation for an example of setting 2653 * formatted text in the XML resource file. 2654 * 2655 * @attr ref android.R.styleable#TextView_text 2656 */ 2657 @android.view.RemotableViewMethod 2658 public final void setText(CharSequence text) { 2659 setText(text, mBufferType); 2660 } 2661 2662 /** 2663 * Like {@link #setText(CharSequence)}, 2664 * except that the cursor position (if any) is retained in the new text. 2665 * 2666 * @param text The new text to place in the text view. 2667 * 2668 * @see #setText(CharSequence) 2669 */ 2670 @android.view.RemotableViewMethod 2671 public final void setTextKeepState(CharSequence text) { 2672 setTextKeepState(text, mBufferType); 2673 } 2674 2675 /** 2676 * Sets the text that this TextView is to display (see 2677 * {@link #setText(CharSequence)}) and also sets whether it is stored 2678 * in a styleable/spannable buffer and whether it is editable. 2679 * 2680 * @attr ref android.R.styleable#TextView_text 2681 * @attr ref android.R.styleable#TextView_bufferType 2682 */ 2683 public void setText(CharSequence text, BufferType type) { 2684 setText(text, type, true, 0); 2685 2686 if (mCharWrapper != null) { 2687 mCharWrapper.mChars = null; 2688 } 2689 } 2690 2691 private void setText(CharSequence text, BufferType type, 2692 boolean notifyBefore, int oldlen) { 2693 if (text == null) { 2694 text = ""; 2695 } 2696 2697 if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f); 2698 2699 if (text instanceof Spanned && 2700 ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) { 2701 setHorizontalFadingEdgeEnabled(true); 2702 setEllipsize(TextUtils.TruncateAt.MARQUEE); 2703 } 2704 2705 int n = mFilters.length; 2706 for (int i = 0; i < n; i++) { 2707 CharSequence out = mFilters[i].filter(text, 0, text.length(), 2708 EMPTY_SPANNED, 0, 0); 2709 if (out != null) { 2710 text = out; 2711 } 2712 } 2713 2714 if (notifyBefore) { 2715 if (mText != null) { 2716 oldlen = mText.length(); 2717 sendBeforeTextChanged(mText, 0, oldlen, text.length()); 2718 } else { 2719 sendBeforeTextChanged("", 0, 0, text.length()); 2720 } 2721 } 2722 2723 boolean needEditableForNotification = false; 2724 2725 if (mListeners != null && mListeners.size() != 0) { 2726 needEditableForNotification = true; 2727 } 2728 2729 if (type == BufferType.EDITABLE || mInput != null || 2730 needEditableForNotification) { 2731 Editable t = mEditableFactory.newEditable(text); 2732 text = t; 2733 setFilters(t, mFilters); 2734 InputMethodManager imm = InputMethodManager.peekInstance(); 2735 if (imm != null) imm.restartInput(this); 2736 } else if (type == BufferType.SPANNABLE || mMovement != null) { 2737 text = mSpannableFactory.newSpannable(text); 2738 } else if (!(text instanceof CharWrapper)) { 2739 text = TextUtils.stringOrSpannedString(text); 2740 } 2741 2742 if (mAutoLinkMask != 0) { 2743 Spannable s2; 2744 2745 if (type == BufferType.EDITABLE || text instanceof Spannable) { 2746 s2 = (Spannable) text; 2747 } else { 2748 s2 = mSpannableFactory.newSpannable(text); 2749 } 2750 2751 if (Linkify.addLinks(s2, mAutoLinkMask)) { 2752 text = s2; 2753 type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE; 2754 2755 /* 2756 * We must go ahead and set the text before changing the 2757 * movement method, because setMovementMethod() may call 2758 * setText() again to try to upgrade the buffer type. 2759 */ 2760 mText = text; 2761 2762 // Do not change the movement method for text that support text selection as it 2763 // would prevent an arbitrary cursor displacement. 2764 final boolean hasTextSelection = this instanceof EditText || mTextIsSelectable; 2765 if (mLinksClickable && !hasTextSelection) { 2766 setMovementMethod(LinkMovementMethod.getInstance()); 2767 } 2768 } 2769 } 2770 2771 mBufferType = type; 2772 mText = text; 2773 2774 if (mTransformation == null) 2775 mTransformed = text; 2776 else 2777 mTransformed = mTransformation.getTransformation(text, this); 2778 2779 final int textLength = text.length(); 2780 2781 if (text instanceof Spannable) { 2782 Spannable sp = (Spannable) text; 2783 2784 // Remove any ChangeWatchers that might have come 2785 // from other TextViews. 2786 final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class); 2787 final int count = watchers.length; 2788 for (int i = 0; i < count; i++) 2789 sp.removeSpan(watchers[i]); 2790 2791 if (mChangeWatcher == null) 2792 mChangeWatcher = new ChangeWatcher(); 2793 2794 sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE | 2795 (PRIORITY << Spanned.SPAN_PRIORITY_SHIFT)); 2796 2797 if (mInput != null) { 2798 sp.setSpan(mInput, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 2799 } 2800 2801 if (mTransformation != null) { 2802 sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 2803 2804 } 2805 2806 if (mMovement != null) { 2807 mMovement.initialize(this, (Spannable) text); 2808 2809 /* 2810 * Initializing the movement method will have set the 2811 * selection, so reset mSelectionMoved to keep that from 2812 * interfering with the normal on-focus selection-setting. 2813 */ 2814 mSelectionMoved = false; 2815 } 2816 } 2817 2818 if (mLayout != null) { 2819 checkForRelayout(); 2820 } 2821 2822 sendOnTextChanged(text, 0, oldlen, textLength); 2823 onTextChanged(text, 0, oldlen, textLength); 2824 2825 if (needEditableForNotification) { 2826 sendAfterTextChanged((Editable) text); 2827 } 2828 2829 // SelectionModifierCursorController depends on textCanBeSelected, which depends on text 2830 prepareCursorControllers(); 2831 } 2832 2833 /** 2834 * Sets the TextView to display the specified slice of the specified 2835 * char array. You must promise that you will not change the contents 2836 * of the array except for right before another call to setText(), 2837 * since the TextView has no way to know that the text 2838 * has changed and that it needs to invalidate and re-layout. 2839 */ 2840 public final void setText(char[] text, int start, int len) { 2841 int oldlen = 0; 2842 2843 if (start < 0 || len < 0 || start + len > text.length) { 2844 throw new IndexOutOfBoundsException(start + ", " + len); 2845 } 2846 2847 /* 2848 * We must do the before-notification here ourselves because if 2849 * the old text is a CharWrapper we destroy it before calling 2850 * into the normal path. 2851 */ 2852 if (mText != null) { 2853 oldlen = mText.length(); 2854 sendBeforeTextChanged(mText, 0, oldlen, len); 2855 } else { 2856 sendBeforeTextChanged("", 0, 0, len); 2857 } 2858 2859 if (mCharWrapper == null) { 2860 mCharWrapper = new CharWrapper(text, start, len); 2861 } else { 2862 mCharWrapper.set(text, start, len); 2863 } 2864 2865 setText(mCharWrapper, mBufferType, false, oldlen); 2866 } 2867 2868 private static class CharWrapper 2869 implements CharSequence, GetChars, GraphicsOperations { 2870 private char[] mChars; 2871 private int mStart, mLength; 2872 2873 public CharWrapper(char[] chars, int start, int len) { 2874 mChars = chars; 2875 mStart = start; 2876 mLength = len; 2877 } 2878 2879 /* package */ void set(char[] chars, int start, int len) { 2880 mChars = chars; 2881 mStart = start; 2882 mLength = len; 2883 } 2884 2885 public int length() { 2886 return mLength; 2887 } 2888 2889 public char charAt(int off) { 2890 return mChars[off + mStart]; 2891 } 2892 2893 @Override 2894 public String toString() { 2895 return new String(mChars, mStart, mLength); 2896 } 2897 2898 public CharSequence subSequence(int start, int end) { 2899 if (start < 0 || end < 0 || start > mLength || end > mLength) { 2900 throw new IndexOutOfBoundsException(start + ", " + end); 2901 } 2902 2903 return new String(mChars, start + mStart, end - start); 2904 } 2905 2906 public void getChars(int start, int end, char[] buf, int off) { 2907 if (start < 0 || end < 0 || start > mLength || end > mLength) { 2908 throw new IndexOutOfBoundsException(start + ", " + end); 2909 } 2910 2911 System.arraycopy(mChars, start + mStart, buf, off, end - start); 2912 } 2913 2914 public void drawText(Canvas c, int start, int end, 2915 float x, float y, Paint p) { 2916 c.drawText(mChars, start + mStart, end - start, x, y, p); 2917 } 2918 2919 public void drawTextRun(Canvas c, int start, int end, 2920 int contextStart, int contextEnd, float x, float y, int flags, Paint p) { 2921 int count = end - start; 2922 int contextCount = contextEnd - contextStart; 2923 c.drawTextRun(mChars, start + mStart, count, contextStart + mStart, 2924 contextCount, x, y, flags, p); 2925 } 2926 2927 public float measureText(int start, int end, Paint p) { 2928 return p.measureText(mChars, start + mStart, end - start); 2929 } 2930 2931 public int getTextWidths(int start, int end, float[] widths, Paint p) { 2932 return p.getTextWidths(mChars, start + mStart, end - start, widths); 2933 } 2934 2935 public float getTextRunAdvances(int start, int end, int contextStart, 2936 int contextEnd, int flags, float[] advances, int advancesIndex, 2937 Paint p) { 2938 int count = end - start; 2939 int contextCount = contextEnd - contextStart; 2940 return p.getTextRunAdvances(mChars, start + mStart, count, 2941 contextStart + mStart, contextCount, flags, advances, 2942 advancesIndex); 2943 } 2944 2945 public int getTextRunCursor(int contextStart, int contextEnd, int flags, 2946 int offset, int cursorOpt, Paint p) { 2947 int contextCount = contextEnd - contextStart; 2948 return p.getTextRunCursor(mChars, contextStart + mStart, 2949 contextCount, flags, offset + mStart, cursorOpt); 2950 } 2951 } 2952 2953 /** 2954 * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)}, 2955 * except that the cursor position (if any) is retained in the new text. 2956 * 2957 * @see #setText(CharSequence, android.widget.TextView.BufferType) 2958 */ 2959 public final void setTextKeepState(CharSequence text, BufferType type) { 2960 int start = getSelectionStart(); 2961 int end = getSelectionEnd(); 2962 int len = text.length(); 2963 2964 setText(text, type); 2965 2966 if (start >= 0 || end >= 0) { 2967 if (mText instanceof Spannable) { 2968 Selection.setSelection((Spannable) mText, 2969 Math.max(0, Math.min(start, len)), 2970 Math.max(0, Math.min(end, len))); 2971 } 2972 } 2973 } 2974 2975 @android.view.RemotableViewMethod 2976 public final void setText(int resid) { 2977 setText(getContext().getResources().getText(resid)); 2978 } 2979 2980 public final void setText(int resid, BufferType type) { 2981 setText(getContext().getResources().getText(resid), type); 2982 } 2983 2984 /** 2985 * Sets the text to be displayed when the text of the TextView is empty. 2986 * Null means to use the normal empty text. The hint does not currently 2987 * participate in determining the size of the view. 2988 * 2989 * @attr ref android.R.styleable#TextView_hint 2990 */ 2991 @android.view.RemotableViewMethod 2992 public final void setHint(CharSequence hint) { 2993 mHint = TextUtils.stringOrSpannedString(hint); 2994 2995 if (mLayout != null) { 2996 checkForRelayout(); 2997 } 2998 2999 if (mText.length() == 0) { 3000 invalidate(); 3001 } 3002 } 3003 3004 /** 3005 * Sets the text to be displayed when the text of the TextView is empty, 3006 * from a resource. 3007 * 3008 * @attr ref android.R.styleable#TextView_hint 3009 */ 3010 @android.view.RemotableViewMethod 3011 public final void setHint(int resid) { 3012 setHint(getContext().getResources().getText(resid)); 3013 } 3014 3015 /** 3016 * Returns the hint that is displayed when the text of the TextView 3017 * is empty. 3018 * 3019 * @attr ref android.R.styleable#TextView_hint 3020 */ 3021 @ViewDebug.CapturedViewProperty 3022 public CharSequence getHint() { 3023 return mHint; 3024 } 3025 3026 private boolean isMultilineInputType(int type) { 3027 return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == 3028 (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); 3029 } 3030 3031 /** 3032 * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This 3033 * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, 3034 * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} 3035 * then a soft keyboard will not be displayed for this text view. 3036 * 3037 * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be 3038 * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input 3039 * type. 3040 * 3041 * @see #getInputType() 3042 * @see #setRawInputType(int) 3043 * @see android.text.InputType 3044 * @attr ref android.R.styleable#TextView_inputType 3045 */ 3046 public void setInputType(int type) { 3047 final boolean wasPassword = isPasswordInputType(mInputType); 3048 final boolean wasVisiblePassword = isVisiblePasswordInputType(mInputType); 3049 setInputType(type, false); 3050 final boolean isPassword = isPasswordInputType(type); 3051 final boolean isVisiblePassword = isVisiblePasswordInputType(type); 3052 boolean forceUpdate = false; 3053 if (isPassword) { 3054 setTransformationMethod(PasswordTransformationMethod.getInstance()); 3055 setTypefaceByIndex(MONOSPACE, 0); 3056 } else if (isVisiblePassword) { 3057 if (mTransformation == PasswordTransformationMethod.getInstance()) { 3058 forceUpdate = true; 3059 } 3060 setTypefaceByIndex(MONOSPACE, 0); 3061 } else if (wasPassword || wasVisiblePassword) { 3062 // not in password mode, clean up typeface and transformation 3063 setTypefaceByIndex(-1, -1); 3064 if (mTransformation == PasswordTransformationMethod.getInstance()) { 3065 forceUpdate = true; 3066 } 3067 } 3068 3069 boolean singleLine = !isMultilineInputType(type); 3070 3071 // We need to update the single line mode if it has changed or we 3072 // were previously in password mode. 3073 if (mSingleLine != singleLine || forceUpdate) { 3074 // Change single line mode, but only change the transformation if 3075 // we are not in password mode. 3076 applySingleLine(singleLine, !isPassword, true); 3077 } 3078 3079 InputMethodManager imm = InputMethodManager.peekInstance(); 3080 if (imm != null) imm.restartInput(this); 3081 } 3082 3083 /** 3084 * It would be better to rely on the input type for everything. A password inputType should have 3085 * a password transformation. We should hence use isPasswordInputType instead of this method. 3086 * 3087 * We should: 3088 * - Call setInputType in setKeyListener instead of changing the input type directly (which 3089 * would install the correct transformation). 3090 * - Refuse the installation of a non-password transformation in setTransformation if the input 3091 * type is password. 3092 * 3093 * However, this is like this for legacy reasons and we cannot break existing apps. This method 3094 * is useful since it matches what the user can see (obfuscated text or not). 3095 * 3096 * @return true if the current transformation method is of the password type. 3097 */ 3098 private boolean hasPasswordTransformationMethod() { 3099 return mTransformation instanceof PasswordTransformationMethod; 3100 } 3101 3102 private boolean isPasswordInputType(int inputType) { 3103 final int variation = 3104 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 3105 return variation 3106 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD) 3107 || variation 3108 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD) 3109 || variation 3110 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 3111 } 3112 3113 private boolean isVisiblePasswordInputType(int inputType) { 3114 final int variation = 3115 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 3116 return variation 3117 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); 3118 } 3119 3120 /** 3121 * Directly change the content type integer of the text view, without 3122 * modifying any other state. 3123 * @see #setInputType(int) 3124 * @see android.text.InputType 3125 * @attr ref android.R.styleable#TextView_inputType 3126 */ 3127 public void setRawInputType(int type) { 3128 mInputType = type; 3129 } 3130 3131 private void setInputType(int type, boolean direct) { 3132 final int cls = type & EditorInfo.TYPE_MASK_CLASS; 3133 KeyListener input; 3134 if (cls == EditorInfo.TYPE_CLASS_TEXT) { 3135 boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0; 3136 TextKeyListener.Capitalize cap; 3137 if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) { 3138 cap = TextKeyListener.Capitalize.CHARACTERS; 3139 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) { 3140 cap = TextKeyListener.Capitalize.WORDS; 3141 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) { 3142 cap = TextKeyListener.Capitalize.SENTENCES; 3143 } else { 3144 cap = TextKeyListener.Capitalize.NONE; 3145 } 3146 input = TextKeyListener.getInstance(autotext, cap); 3147 } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) { 3148 input = DigitsKeyListener.getInstance( 3149 (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0, 3150 (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0); 3151 } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) { 3152 switch (type & EditorInfo.TYPE_MASK_VARIATION) { 3153 case EditorInfo.TYPE_DATETIME_VARIATION_DATE: 3154 input = DateKeyListener.getInstance(); 3155 break; 3156 case EditorInfo.TYPE_DATETIME_VARIATION_TIME: 3157 input = TimeKeyListener.getInstance(); 3158 break; 3159 default: 3160 input = DateTimeKeyListener.getInstance(); 3161 break; 3162 } 3163 } else if (cls == EditorInfo.TYPE_CLASS_PHONE) { 3164 input = DialerKeyListener.getInstance(); 3165 } else { 3166 input = TextKeyListener.getInstance(); 3167 } 3168 setRawInputType(type); 3169 if (direct) mInput = input; 3170 else { 3171 setKeyListenerOnly(input); 3172 } 3173 } 3174 3175 /** 3176 * Get the type of the content. 3177 * 3178 * @see #setInputType(int) 3179 * @see android.text.InputType 3180 */ 3181 public int getInputType() { 3182 return mInputType; 3183 } 3184 3185 /** 3186 * Change the editor type integer associated with the text view, which 3187 * will be reported to an IME with {@link EditorInfo#imeOptions} when it 3188 * has focus. 3189 * @see #getImeOptions 3190 * @see android.view.inputmethod.EditorInfo 3191 * @attr ref android.R.styleable#TextView_imeOptions 3192 */ 3193 public void setImeOptions(int imeOptions) { 3194 if (mInputContentType == null) { 3195 mInputContentType = new InputContentType(); 3196 } 3197 mInputContentType.imeOptions = imeOptions; 3198 } 3199 3200 /** 3201 * Get the type of the IME editor. 3202 * 3203 * @see #setImeOptions(int) 3204 * @see android.view.inputmethod.EditorInfo 3205 */ 3206 public int getImeOptions() { 3207 return mInputContentType != null 3208 ? mInputContentType.imeOptions : EditorInfo.IME_NULL; 3209 } 3210 3211 /** 3212 * Change the custom IME action associated with the text view, which 3213 * will be reported to an IME with {@link EditorInfo#actionLabel} 3214 * and {@link EditorInfo#actionId} when it has focus. 3215 * @see #getImeActionLabel 3216 * @see #getImeActionId 3217 * @see android.view.inputmethod.EditorInfo 3218 * @attr ref android.R.styleable#TextView_imeActionLabel 3219 * @attr ref android.R.styleable#TextView_imeActionId 3220 */ 3221 public void setImeActionLabel(CharSequence label, int actionId) { 3222 if (mInputContentType == null) { 3223 mInputContentType = new InputContentType(); 3224 } 3225 mInputContentType.imeActionLabel = label; 3226 mInputContentType.imeActionId = actionId; 3227 } 3228 3229 /** 3230 * Get the IME action label previous set with {@link #setImeActionLabel}. 3231 * 3232 * @see #setImeActionLabel 3233 * @see android.view.inputmethod.EditorInfo 3234 */ 3235 public CharSequence getImeActionLabel() { 3236 return mInputContentType != null 3237 ? mInputContentType.imeActionLabel : null; 3238 } 3239 3240 /** 3241 * Get the IME action ID previous set with {@link #setImeActionLabel}. 3242 * 3243 * @see #setImeActionLabel 3244 * @see android.view.inputmethod.EditorInfo 3245 */ 3246 public int getImeActionId() { 3247 return mInputContentType != null 3248 ? mInputContentType.imeActionId : 0; 3249 } 3250 3251 /** 3252 * Set a special listener to be called when an action is performed 3253 * on the text view. This will be called when the enter key is pressed, 3254 * or when an action supplied to the IME is selected by the user. Setting 3255 * this means that the normal hard key event will not insert a newline 3256 * into the text view, even if it is multi-line; holding down the ALT 3257 * modifier will, however, allow the user to insert a newline character. 3258 */ 3259 public void setOnEditorActionListener(OnEditorActionListener l) { 3260 if (mInputContentType == null) { 3261 mInputContentType = new InputContentType(); 3262 } 3263 mInputContentType.onEditorActionListener = l; 3264 } 3265 3266 /** 3267 * Called when an attached input method calls 3268 * {@link InputConnection#performEditorAction(int) 3269 * InputConnection.performEditorAction()} 3270 * for this text view. The default implementation will call your action 3271 * listener supplied to {@link #setOnEditorActionListener}, or perform 3272 * a standard operation for {@link EditorInfo#IME_ACTION_NEXT 3273 * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS 3274 * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE 3275 * EditorInfo.IME_ACTION_DONE}. 3276 * 3277 * <p>For backwards compatibility, if no IME options have been set and the 3278 * text view would not normally advance focus on enter, then 3279 * the NEXT and DONE actions received here will be turned into an enter 3280 * key down/up pair to go through the normal key handling. 3281 * 3282 * @param actionCode The code of the action being performed. 3283 * 3284 * @see #setOnEditorActionListener 3285 */ 3286 public void onEditorAction(int actionCode) { 3287 final InputContentType ict = mInputContentType; 3288 if (ict != null) { 3289 if (ict.onEditorActionListener != null) { 3290 if (ict.onEditorActionListener.onEditorAction(this, 3291 actionCode, null)) { 3292 return; 3293 } 3294 } 3295 3296 // This is the handling for some default action. 3297 // Note that for backwards compatibility we don't do this 3298 // default handling if explicit ime options have not been given, 3299 // instead turning this into the normal enter key codes that an 3300 // app may be expecting. 3301 if (actionCode == EditorInfo.IME_ACTION_NEXT) { 3302 View v = focusSearch(FOCUS_DOWN); 3303 if (v != null) { 3304 if (!v.requestFocus(FOCUS_DOWN)) { 3305 throw new IllegalStateException("focus search returned a view " + 3306 "that wasn't able to take focus!"); 3307 } 3308 } 3309 return; 3310 3311 } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) { 3312 View v = focusSearch(FOCUS_UP); 3313 if (v != null) { 3314 if (!v.requestFocus(FOCUS_UP)) { 3315 throw new IllegalStateException("focus search returned a view " + 3316 "that wasn't able to take focus!"); 3317 } 3318 } 3319 return; 3320 3321 } else if (actionCode == EditorInfo.IME_ACTION_DONE) { 3322 InputMethodManager imm = InputMethodManager.peekInstance(); 3323 if (imm != null && imm.isActive(this)) { 3324 imm.hideSoftInputFromWindow(getWindowToken(), 0); 3325 } 3326 return; 3327 } 3328 } 3329 3330 Handler h = getHandler(); 3331 if (h != null) { 3332 long eventTime = SystemClock.uptimeMillis(); 3333 h.sendMessage(h.obtainMessage(ViewRoot.DISPATCH_KEY_FROM_IME, 3334 new KeyEvent(eventTime, eventTime, 3335 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, 3336 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3337 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3338 | KeyEvent.FLAG_EDITOR_ACTION))); 3339 h.sendMessage(h.obtainMessage(ViewRoot.DISPATCH_KEY_FROM_IME, 3340 new KeyEvent(SystemClock.uptimeMillis(), eventTime, 3341 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 3342 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3343 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3344 | KeyEvent.FLAG_EDITOR_ACTION))); 3345 } 3346 } 3347 3348 /** 3349 * Set the private content type of the text, which is the 3350 * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} 3351 * field that will be filled in when creating an input connection. 3352 * 3353 * @see #getPrivateImeOptions() 3354 * @see EditorInfo#privateImeOptions 3355 * @attr ref android.R.styleable#TextView_privateImeOptions 3356 */ 3357 public void setPrivateImeOptions(String type) { 3358 if (mInputContentType == null) mInputContentType = new InputContentType(); 3359 mInputContentType.privateImeOptions = type; 3360 } 3361 3362 /** 3363 * Get the private type of the content. 3364 * 3365 * @see #setPrivateImeOptions(String) 3366 * @see EditorInfo#privateImeOptions 3367 */ 3368 public String getPrivateImeOptions() { 3369 return mInputContentType != null 3370 ? mInputContentType.privateImeOptions : null; 3371 } 3372 3373 /** 3374 * Set the extra input data of the text, which is the 3375 * {@link EditorInfo#extras TextBoxAttribute.extras} 3376 * Bundle that will be filled in when creating an input connection. The 3377 * given integer is the resource ID of an XML resource holding an 3378 * {@link android.R.styleable#InputExtras <input-extras>} XML tree. 3379 * 3380 * @see #getInputExtras(boolean) 3381 * @see EditorInfo#extras 3382 * @attr ref android.R.styleable#TextView_editorExtras 3383 */ 3384 public void setInputExtras(int xmlResId) 3385 throws XmlPullParserException, IOException { 3386 XmlResourceParser parser = getResources().getXml(xmlResId); 3387 if (mInputContentType == null) mInputContentType = new InputContentType(); 3388 mInputContentType.extras = new Bundle(); 3389 getResources().parseBundleExtras(parser, mInputContentType.extras); 3390 } 3391 3392 /** 3393 * Retrieve the input extras currently associated with the text view, which 3394 * can be viewed as well as modified. 3395 * 3396 * @param create If true, the extras will be created if they don't already 3397 * exist. Otherwise, null will be returned if none have been created. 3398 * @see #setInputExtras(int) 3399 * @see EditorInfo#extras 3400 * @attr ref android.R.styleable#TextView_editorExtras 3401 */ 3402 public Bundle getInputExtras(boolean create) { 3403 if (mInputContentType == null) { 3404 if (!create) return null; 3405 mInputContentType = new InputContentType(); 3406 } 3407 if (mInputContentType.extras == null) { 3408 if (!create) return null; 3409 mInputContentType.extras = new Bundle(); 3410 } 3411 return mInputContentType.extras; 3412 } 3413 3414 /** 3415 * Returns the error message that was set to be displayed with 3416 * {@link #setError}, or <code>null</code> if no error was set 3417 * or if it the error was cleared by the widget after user input. 3418 */ 3419 public CharSequence getError() { 3420 return mError; 3421 } 3422 3423 /** 3424 * Sets the right-hand compound drawable of the TextView to the "error" 3425 * icon and sets an error message that will be displayed in a popup when 3426 * the TextView has focus. The icon and error message will be reset to 3427 * null when any key events cause changes to the TextView's text. If the 3428 * <code>error</code> is <code>null</code>, the error message and icon 3429 * will be cleared. 3430 */ 3431 @android.view.RemotableViewMethod 3432 public void setError(CharSequence error) { 3433 if (error == null) { 3434 setError(null, null); 3435 } else { 3436 Drawable dr = getContext().getResources(). 3437 getDrawable(com.android.internal.R.drawable.indicator_input_error); 3438 3439 dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); 3440 setError(error, dr); 3441 } 3442 } 3443 3444 /** 3445 * Sets the right-hand compound drawable of the TextView to the specified 3446 * icon and sets an error message that will be displayed in a popup when 3447 * the TextView has focus. The icon and error message will be reset to 3448 * null when any key events cause changes to the TextView's text. The 3449 * drawable must already have had {@link Drawable#setBounds} set on it. 3450 * If the <code>error</code> is <code>null</code>, the error message will 3451 * be cleared (and you should provide a <code>null</code> icon as well). 3452 */ 3453 public void setError(CharSequence error, Drawable icon) { 3454 error = TextUtils.stringOrSpannedString(error); 3455 3456 mError = error; 3457 mErrorWasChanged = true; 3458 final Drawables dr = mDrawables; 3459 if (dr != null) { 3460 setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon, dr.mDrawableBottom); 3461 } else { 3462 setCompoundDrawables(null, null, icon, null); 3463 } 3464 3465 if (error == null) { 3466 if (mPopup != null) { 3467 if (mPopup.isShowing()) { 3468 mPopup.dismiss(); 3469 } 3470 3471 mPopup = null; 3472 } 3473 } else { 3474 if (isFocused()) { 3475 showError(); 3476 } 3477 } 3478 } 3479 3480 private void showError() { 3481 if (getWindowToken() == null) { 3482 mShowErrorAfterAttach = true; 3483 return; 3484 } 3485 3486 if (mPopup == null) { 3487 LayoutInflater inflater = LayoutInflater.from(getContext()); 3488 final TextView err = (TextView) inflater.inflate( 3489 com.android.internal.R.layout.textview_hint, null); 3490 3491 final float scale = getResources().getDisplayMetrics().density; 3492 mPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f)); 3493 mPopup.setFocusable(false); 3494 // The user is entering text, so the input method is needed. We 3495 // don't want the popup to be displayed on top of it. 3496 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 3497 } 3498 3499 TextView tv = (TextView) mPopup.getContentView(); 3500 chooseSize(mPopup, mError, tv); 3501 tv.setText(mError); 3502 3503 mPopup.showAsDropDown(this, getErrorX(), getErrorY()); 3504 mPopup.fixDirection(mPopup.isAboveAnchor()); 3505 } 3506 3507 private static class ErrorPopup extends PopupWindow { 3508 private boolean mAbove = false; 3509 private final TextView mView; 3510 private int mPopupInlineErrorBackgroundId = 0; 3511 private int mPopupInlineErrorAboveBackgroundId = 0; 3512 3513 ErrorPopup(TextView v, int width, int height) { 3514 super(v, width, height); 3515 mView = v; 3516 // Make sure the TextView has a background set as it will be used the first time it is 3517 // shown and positionned. Initialized with below background, which should have 3518 // dimensions identical to the above version for this to work (and is more likely). 3519 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3520 com.android.internal.R.styleable.Theme_errorMessageBackground); 3521 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 3522 } 3523 3524 void fixDirection(boolean above) { 3525 mAbove = above; 3526 3527 if (above) { 3528 mPopupInlineErrorAboveBackgroundId = 3529 getResourceId(mPopupInlineErrorAboveBackgroundId, 3530 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 3531 } else { 3532 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3533 com.android.internal.R.styleable.Theme_errorMessageBackground); 3534 } 3535 3536 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 3537 mPopupInlineErrorBackgroundId); 3538 } 3539 3540 private int getResourceId(int currentId, int index) { 3541 if (currentId == 0) { 3542 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 3543 R.styleable.Theme); 3544 currentId = styledAttributes.getResourceId(index, 0); 3545 styledAttributes.recycle(); 3546 } 3547 return currentId; 3548 } 3549 3550 @Override 3551 public void update(int x, int y, int w, int h, boolean force) { 3552 super.update(x, y, w, h, force); 3553 3554 boolean above = isAboveAnchor(); 3555 if (above != mAbove) { 3556 fixDirection(above); 3557 } 3558 } 3559 } 3560 3561 /** 3562 * Returns the Y offset to make the pointy top of the error point 3563 * at the middle of the error icon. 3564 */ 3565 private int getErrorX() { 3566 /* 3567 * The "25" is the distance between the point and the right edge 3568 * of the background 3569 */ 3570 final float scale = getResources().getDisplayMetrics().density; 3571 3572 final Drawables dr = mDrawables; 3573 return getWidth() - mPopup.getWidth() - getPaddingRight() - 3574 (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f); 3575 } 3576 3577 /** 3578 * Returns the Y offset to make the pointy top of the error point 3579 * at the bottom of the error icon. 3580 */ 3581 private int getErrorY() { 3582 /* 3583 * Compound, not extended, because the icon is not clipped 3584 * if the text height is smaller. 3585 */ 3586 final int compoundPaddingTop = getCompoundPaddingTop(); 3587 int vspace = mBottom - mTop - getCompoundPaddingBottom() - compoundPaddingTop; 3588 3589 final Drawables dr = mDrawables; 3590 int icontop = compoundPaddingTop + 3591 (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2; 3592 3593 /* 3594 * The "2" is the distance between the point and the top edge 3595 * of the background. 3596 */ 3597 final float scale = getResources().getDisplayMetrics().density; 3598 return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - getHeight() - 3599 (int) (2 * scale + 0.5f); 3600 } 3601 3602 private void hideError() { 3603 if (mPopup != null) { 3604 if (mPopup.isShowing()) { 3605 mPopup.dismiss(); 3606 } 3607 } 3608 3609 mShowErrorAfterAttach = false; 3610 } 3611 3612 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { 3613 int wid = tv.getPaddingLeft() + tv.getPaddingRight(); 3614 int ht = tv.getPaddingTop() + tv.getPaddingBottom(); 3615 3616 /* 3617 * Figure out how big the text would be if we laid it out to the 3618 * full width of this view minus the border. 3619 */ 3620 int cap = getWidth() - wid; 3621 if (cap < 0) { 3622 cap = 200; // We must not be measured yet -- setFrame() will fix it. 3623 } 3624 3625 Layout l = new StaticLayout(text, tv.getPaint(), cap, 3626 Layout.Alignment.ALIGN_NORMAL, 1, 0, true); 3627 float max = 0; 3628 for (int i = 0; i < l.getLineCount(); i++) { 3629 max = Math.max(max, l.getLineWidth(i)); 3630 } 3631 3632 /* 3633 * Now set the popup size to be big enough for the text plus the border. 3634 */ 3635 pop.setWidth(wid + (int) Math.ceil(max)); 3636 pop.setHeight(ht + l.getHeight()); 3637 } 3638 3639 3640 @Override 3641 protected boolean setFrame(int l, int t, int r, int b) { 3642 boolean result = super.setFrame(l, t, r, b); 3643 3644 if (mPopup != null) { 3645 TextView tv = (TextView) mPopup.getContentView(); 3646 chooseSize(mPopup, mError, tv); 3647 mPopup.update(this, getErrorX(), getErrorY(), 3648 mPopup.getWidth(), mPopup.getHeight()); 3649 } 3650 3651 restartMarqueeIfNeeded(); 3652 3653 return result; 3654 } 3655 3656 private void restartMarqueeIfNeeded() { 3657 if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 3658 mRestartMarquee = false; 3659 startMarquee(); 3660 } 3661 } 3662 3663 /** 3664 * Sets the list of input filters that will be used if the buffer is 3665 * Editable. Has no effect otherwise. 3666 * 3667 * @attr ref android.R.styleable#TextView_maxLength 3668 */ 3669 public void setFilters(InputFilter[] filters) { 3670 if (filters == null) { 3671 throw new IllegalArgumentException(); 3672 } 3673 3674 mFilters = filters; 3675 3676 if (mText instanceof Editable) { 3677 setFilters((Editable) mText, filters); 3678 } 3679 } 3680 3681 /** 3682 * Sets the list of input filters on the specified Editable, 3683 * and includes mInput in the list if it is an InputFilter. 3684 */ 3685 private void setFilters(Editable e, InputFilter[] filters) { 3686 if (mInput instanceof InputFilter) { 3687 InputFilter[] nf = new InputFilter[filters.length + 1]; 3688 3689 System.arraycopy(filters, 0, nf, 0, filters.length); 3690 nf[filters.length] = (InputFilter) mInput; 3691 3692 e.setFilters(nf); 3693 } else { 3694 e.setFilters(filters); 3695 } 3696 } 3697 3698 /** 3699 * Returns the current list of input filters. 3700 */ 3701 public InputFilter[] getFilters() { 3702 return mFilters; 3703 } 3704 3705 ///////////////////////////////////////////////////////////////////////// 3706 3707 private int getVerticalOffset(boolean forceNormal) { 3708 int voffset = 0; 3709 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 3710 3711 Layout l = mLayout; 3712 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 3713 l = mHintLayout; 3714 } 3715 3716 if (gravity != Gravity.TOP) { 3717 int boxht; 3718 3719 if (l == mHintLayout) { 3720 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 3721 getCompoundPaddingBottom(); 3722 } else { 3723 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 3724 getExtendedPaddingBottom(); 3725 } 3726 int textht = l.getHeight(); 3727 3728 if (textht < boxht) { 3729 if (gravity == Gravity.BOTTOM) 3730 voffset = boxht - textht; 3731 else // (gravity == Gravity.CENTER_VERTICAL) 3732 voffset = (boxht - textht) >> 1; 3733 } 3734 } 3735 return voffset; 3736 } 3737 3738 private int getBottomVerticalOffset(boolean forceNormal) { 3739 int voffset = 0; 3740 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 3741 3742 Layout l = mLayout; 3743 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 3744 l = mHintLayout; 3745 } 3746 3747 if (gravity != Gravity.BOTTOM) { 3748 int boxht; 3749 3750 if (l == mHintLayout) { 3751 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 3752 getCompoundPaddingBottom(); 3753 } else { 3754 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 3755 getExtendedPaddingBottom(); 3756 } 3757 int textht = l.getHeight(); 3758 3759 if (textht < boxht) { 3760 if (gravity == Gravity.TOP) 3761 voffset = boxht - textht; 3762 else // (gravity == Gravity.CENTER_VERTICAL) 3763 voffset = (boxht - textht) >> 1; 3764 } 3765 } 3766 return voffset; 3767 } 3768 3769 private void invalidateCursorPath() { 3770 if (mHighlightPathBogus) { 3771 invalidateCursor(); 3772 } else { 3773 synchronized (sTempRect) { 3774 /* 3775 * The reason for this concern about the thickness of the 3776 * cursor and doing the floor/ceil on the coordinates is that 3777 * some EditTexts (notably textfields in the Browser) have 3778 * anti-aliased text where not all the characters are 3779 * necessarily at integer-multiple locations. This should 3780 * make sure the entire cursor gets invalidated instead of 3781 * sometimes missing half a pixel. 3782 */ 3783 3784 float thick = FloatMath.ceil(mTextPaint.getStrokeWidth()); 3785 if (thick < 1.0f) { 3786 thick = 1.0f; 3787 } 3788 3789 thick /= 2; 3790 3791 mHighlightPath.computeBounds(sTempRect, false); 3792 3793 int left = getCompoundPaddingLeft(); 3794 int top = getExtendedPaddingTop() + getVerticalOffset(true); 3795 3796 invalidate((int) FloatMath.floor(left + sTempRect.left - thick), 3797 (int) FloatMath.floor(top + sTempRect.top - thick), 3798 (int) FloatMath.ceil(left + sTempRect.right + thick), 3799 (int) FloatMath.ceil(top + sTempRect.bottom + thick)); 3800 } 3801 } 3802 } 3803 3804 private void invalidateCursor() { 3805 int where = getSelectionEnd(); 3806 3807 invalidateCursor(where, where, where); 3808 } 3809 3810 private void invalidateCursor(int a, int b, int c) { 3811 if (mLayout == null) { 3812 invalidate(); 3813 } else { 3814 if (a >= 0 || b >= 0 || c >= 0) { 3815 int first = Math.min(Math.min(a, b), c); 3816 int last = Math.max(Math.max(a, b), c); 3817 3818 int line = mLayout.getLineForOffset(first); 3819 int top = mLayout.getLineTop(line); 3820 3821 // This is ridiculous, but the descent from the line above 3822 // can hang down into the line we really want to redraw, 3823 // so we have to invalidate part of the line above to make 3824 // sure everything that needs to be redrawn really is. 3825 // (But not the whole line above, because that would cause 3826 // the same problem with the descenders on the line above it!) 3827 if (line > 0) { 3828 top -= mLayout.getLineDescent(line - 1); 3829 } 3830 3831 int line2; 3832 3833 if (first == last) 3834 line2 = line; 3835 else 3836 line2 = mLayout.getLineForOffset(last); 3837 3838 int bottom = mLayout.getLineTop(line2 + 1); 3839 int voffset = getVerticalOffset(true); 3840 3841 int left = getCompoundPaddingLeft() + mScrollX; 3842 invalidate(left, top + voffset + getExtendedPaddingTop(), 3843 left + getWidth() - getCompoundPaddingLeft() - 3844 getCompoundPaddingRight(), 3845 bottom + voffset + getExtendedPaddingTop()); 3846 } 3847 } 3848 } 3849 3850 private void registerForPreDraw() { 3851 final ViewTreeObserver observer = getViewTreeObserver(); 3852 if (observer == null) { 3853 return; 3854 } 3855 3856 if (mPreDrawState == PREDRAW_NOT_REGISTERED) { 3857 observer.addOnPreDrawListener(this); 3858 mPreDrawState = PREDRAW_PENDING; 3859 } else if (mPreDrawState == PREDRAW_DONE) { 3860 mPreDrawState = PREDRAW_PENDING; 3861 } 3862 3863 // else state is PREDRAW_PENDING, so keep waiting. 3864 } 3865 3866 /** 3867 * {@inheritDoc} 3868 */ 3869 public boolean onPreDraw() { 3870 if (mPreDrawState != PREDRAW_PENDING) { 3871 return true; 3872 } 3873 3874 if (mLayout == null) { 3875 assumeLayout(); 3876 } 3877 3878 boolean changed = false; 3879 3880 if (mMovement != null) { 3881 /* This code also provides auto-scrolling when a cursor is moved using a 3882 * CursorController (insertion point or selection limits). 3883 * For selection, ensure start or end is visible depending on controller's state. 3884 */ 3885 int curs = getSelectionEnd(); 3886 // Do not create the controller if it is not already created. 3887 if (mSelectionModifierCursorController != null && 3888 mSelectionModifierCursorController.isSelectionStartDragged()) { 3889 curs = getSelectionStart(); 3890 } 3891 3892 /* 3893 * TODO: This should really only keep the end in view if 3894 * it already was before the text changed. I'm not sure 3895 * of a good way to tell from here if it was. 3896 */ 3897 if (curs < 0 && 3898 (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 3899 curs = mText.length(); 3900 } 3901 3902 if (curs >= 0) { 3903 changed = bringPointIntoView(curs); 3904 } 3905 } else { 3906 changed = bringTextIntoView(); 3907 } 3908 3909 // This has to be checked here since: 3910 // - onFocusChanged cannot start it when focus is given to a view with selected text (after 3911 // a screen rotation) since layout is not yet initialized at that point. 3912 if (mCreatedWithASelection) { 3913 startSelectionActionMode(); 3914 mCreatedWithASelection = false; 3915 } 3916 3917 // Phone specific code (there is no ExtractEditText on tablets). 3918 // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can 3919 // not be set. Do the test here instead. 3920 if (this instanceof ExtractEditText && hasSelection()) { 3921 startSelectionActionMode(); 3922 } 3923 3924 mPreDrawState = PREDRAW_DONE; 3925 return !changed; 3926 } 3927 3928 @Override 3929 protected void onAttachedToWindow() { 3930 super.onAttachedToWindow(); 3931 3932 mTemporaryDetach = false; 3933 3934 if (mShowErrorAfterAttach) { 3935 showError(); 3936 mShowErrorAfterAttach = false; 3937 } 3938 3939 final ViewTreeObserver observer = getViewTreeObserver(); 3940 if (observer != null) { 3941 // No need to create the controller. 3942 // The get method will add the listener on controller creation. 3943 if (mInsertionPointCursorController != null) { 3944 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 3945 } 3946 if (mSelectionModifierCursorController != null) { 3947 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 3948 } 3949 } 3950 } 3951 3952 @Override 3953 protected void onDetachedFromWindow() { 3954 super.onDetachedFromWindow(); 3955 3956 final ViewTreeObserver observer = getViewTreeObserver(); 3957 if (observer != null) { 3958 if (mPreDrawState != PREDRAW_NOT_REGISTERED) { 3959 observer.removeOnPreDrawListener(this); 3960 mPreDrawState = PREDRAW_NOT_REGISTERED; 3961 } 3962 // No need to create the controller, as getXXController would. 3963 if (mInsertionPointCursorController != null) { 3964 observer.removeOnTouchModeChangeListener(mInsertionPointCursorController); 3965 } 3966 if (mSelectionModifierCursorController != null) { 3967 observer.removeOnTouchModeChangeListener(mSelectionModifierCursorController); 3968 } 3969 } 3970 3971 if (mError != null) { 3972 hideError(); 3973 } 3974 3975 if (mBlink != null) { 3976 mBlink.cancel(); 3977 } 3978 3979 if (mInsertionPointCursorController != null) { 3980 mInsertionPointCursorController.onDetached(); 3981 } 3982 3983 if (mSelectionModifierCursorController != null) { 3984 mSelectionModifierCursorController.onDetached(); 3985 } 3986 3987 hideControllers(); 3988 } 3989 3990 @Override 3991 protected boolean isPaddingOffsetRequired() { 3992 return mShadowRadius != 0 || mDrawables != null; 3993 } 3994 3995 @Override 3996 protected int getLeftPaddingOffset() { 3997 return getCompoundPaddingLeft() - mPaddingLeft + 3998 (int) Math.min(0, mShadowDx - mShadowRadius); 3999 } 4000 4001 @Override 4002 protected int getTopPaddingOffset() { 4003 return (int) Math.min(0, mShadowDy - mShadowRadius); 4004 } 4005 4006 @Override 4007 protected int getBottomPaddingOffset() { 4008 return (int) Math.max(0, mShadowDy + mShadowRadius); 4009 } 4010 4011 @Override 4012 protected int getRightPaddingOffset() { 4013 return -(getCompoundPaddingRight() - mPaddingRight) + 4014 (int) Math.max(0, mShadowDx + mShadowRadius); 4015 } 4016 4017 @Override 4018 protected boolean verifyDrawable(Drawable who) { 4019 final boolean verified = super.verifyDrawable(who); 4020 if (!verified && mDrawables != null) { 4021 return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || 4022 who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom; 4023 } 4024 return verified; 4025 } 4026 4027 @Override 4028 public void jumpDrawablesToCurrentState() { 4029 super.jumpDrawablesToCurrentState(); 4030 if (mDrawables != null) { 4031 if (mDrawables.mDrawableLeft != null) { 4032 mDrawables.mDrawableLeft.jumpToCurrentState(); 4033 } 4034 if (mDrawables.mDrawableTop != null) { 4035 mDrawables.mDrawableTop.jumpToCurrentState(); 4036 } 4037 if (mDrawables.mDrawableRight != null) { 4038 mDrawables.mDrawableRight.jumpToCurrentState(); 4039 } 4040 if (mDrawables.mDrawableBottom != null) { 4041 mDrawables.mDrawableBottom.jumpToCurrentState(); 4042 } 4043 } 4044 } 4045 4046 @Override 4047 public void invalidateDrawable(Drawable drawable) { 4048 if (verifyDrawable(drawable)) { 4049 final Rect dirty = drawable.getBounds(); 4050 int scrollX = mScrollX; 4051 int scrollY = mScrollY; 4052 4053 // IMPORTANT: The coordinates below are based on the coordinates computed 4054 // for each compound drawable in onDraw(). Make sure to update each section 4055 // accordingly. 4056 final TextView.Drawables drawables = mDrawables; 4057 if (drawables != null) { 4058 if (drawable == drawables.mDrawableLeft) { 4059 final int compoundPaddingTop = getCompoundPaddingTop(); 4060 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4061 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4062 4063 scrollX += mPaddingLeft; 4064 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 4065 } else if (drawable == drawables.mDrawableRight) { 4066 final int compoundPaddingTop = getCompoundPaddingTop(); 4067 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4068 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4069 4070 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 4071 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 4072 } else if (drawable == drawables.mDrawableTop) { 4073 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4074 final int compoundPaddingRight = getCompoundPaddingRight(); 4075 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4076 4077 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 4078 scrollY += mPaddingTop; 4079 } else if (drawable == drawables.mDrawableBottom) { 4080 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4081 final int compoundPaddingRight = getCompoundPaddingRight(); 4082 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4083 4084 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 4085 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 4086 } 4087 } 4088 4089 invalidate(dirty.left + scrollX, dirty.top + scrollY, 4090 dirty.right + scrollX, dirty.bottom + scrollY); 4091 } 4092 } 4093 4094 @Override 4095 protected boolean onSetAlpha(int alpha) { 4096 // Alpha is supported if and only if the drawing can be done in one pass. 4097 // TODO text with spans with a background color currently do not respect this alpha. 4098 if (getBackground() == null) { 4099 mCurrentAlpha = alpha; 4100 final Drawables dr = mDrawables; 4101 if (dr != null) { 4102 if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha); 4103 if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha); 4104 if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha); 4105 if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha); 4106 } 4107 return true; 4108 } 4109 4110 mCurrentAlpha = 255; 4111 return false; 4112 } 4113 4114 /** 4115 * When a TextView is used to display a useful piece of information to the user (such as a 4116 * contact's address), it should be made selectable, so that the user can select and copy this 4117 * content. 4118 * 4119 * Use {@link #setTextIsSelectable(boolean)} or the 4120 * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView 4121 * selectable (text is not selectable by default). 4122 * 4123 * Note that the content of an EditText is always selectable. 4124 * 4125 * @return True if the text displayed in this TextView can be selected by the user. 4126 * 4127 * @attr ref android.R.styleable#TextView_textIsSelectable 4128 */ 4129 public boolean isTextSelectable() { 4130 return mTextIsSelectable; 4131 } 4132 4133 /** 4134 * Sets whether or not (default) the content of this view is selectable by the user. 4135 * 4136 * Note that this methods affect the {@link #setFocusable(boolean)}, 4137 * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and 4138 * {@link #setLongClickable(boolean)} states and you may want to restore these if they were 4139 * customized. 4140 * 4141 * See {@link #isTextSelectable} for details. 4142 * 4143 * @param selectable Whether or not the content of this TextView should be selectable. 4144 */ 4145 public void setTextIsSelectable(boolean selectable) { 4146 if (mTextIsSelectable == selectable) return; 4147 4148 mTextIsSelectable = selectable; 4149 4150 setFocusableInTouchMode(selectable); 4151 setFocusable(selectable); 4152 setClickable(selectable); 4153 setLongClickable(selectable); 4154 4155 // mInputType is already EditorInfo.TYPE_NULL and mInput is null; 4156 4157 setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); 4158 setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL); 4159 4160 // Called by setText above, but safer in case of future code changes 4161 prepareCursorControllers(); 4162 } 4163 4164 @Override 4165 protected int[] onCreateDrawableState(int extraSpace) { 4166 final int[] drawableState; 4167 4168 if (mSingleLine) { 4169 drawableState = super.onCreateDrawableState(extraSpace); 4170 } else { 4171 drawableState = super.onCreateDrawableState(extraSpace + 1); 4172 mergeDrawableStates(drawableState, MULTILINE_STATE_SET); 4173 } 4174 4175 if (mTextIsSelectable) { 4176 // Disable pressed state, which was introduced when TextView was made clickable. 4177 // Prevents text color change. 4178 // setClickable(false) would have a similar effect, but it also disables focus changes 4179 // and long press actions, which are both needed by text selection. 4180 final int length = drawableState.length; 4181 for (int i = 0; i < length; i++) { 4182 if (drawableState[i] == R.attr.state_pressed) { 4183 final int[] nonPressedState = new int[length - 1]; 4184 System.arraycopy(drawableState, 0, nonPressedState, 0, i); 4185 System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); 4186 return nonPressedState; 4187 } 4188 } 4189 } 4190 4191 return drawableState; 4192 } 4193 4194 @Override 4195 protected void onDraw(Canvas canvas) { 4196 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return; 4197 4198 restartMarqueeIfNeeded(); 4199 4200 // Draw the background for this view 4201 super.onDraw(canvas); 4202 4203 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4204 final int compoundPaddingTop = getCompoundPaddingTop(); 4205 final int compoundPaddingRight = getCompoundPaddingRight(); 4206 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4207 final int scrollX = mScrollX; 4208 final int scrollY = mScrollY; 4209 final int right = mRight; 4210 final int left = mLeft; 4211 final int bottom = mBottom; 4212 final int top = mTop; 4213 4214 final Drawables dr = mDrawables; 4215 if (dr != null) { 4216 /* 4217 * Compound, not extended, because the icon is not clipped 4218 * if the text height is smaller. 4219 */ 4220 4221 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 4222 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 4223 4224 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4225 // Make sure to update invalidateDrawable() when changing this code. 4226 if (dr.mDrawableLeft != null) { 4227 canvas.save(); 4228 canvas.translate(scrollX + mPaddingLeft, 4229 scrollY + compoundPaddingTop + 4230 (vspace - dr.mDrawableHeightLeft) / 2); 4231 dr.mDrawableLeft.draw(canvas); 4232 canvas.restore(); 4233 } 4234 4235 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4236 // Make sure to update invalidateDrawable() when changing this code. 4237 if (dr.mDrawableRight != null) { 4238 canvas.save(); 4239 canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight, 4240 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 4241 dr.mDrawableRight.draw(canvas); 4242 canvas.restore(); 4243 } 4244 4245 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4246 // Make sure to update invalidateDrawable() when changing this code. 4247 if (dr.mDrawableTop != null) { 4248 canvas.save(); 4249 canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, 4250 scrollY + mPaddingTop); 4251 dr.mDrawableTop.draw(canvas); 4252 canvas.restore(); 4253 } 4254 4255 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4256 // Make sure to update invalidateDrawable() when changing this code. 4257 if (dr.mDrawableBottom != null) { 4258 canvas.save(); 4259 canvas.translate(scrollX + compoundPaddingLeft + 4260 (hspace - dr.mDrawableWidthBottom) / 2, 4261 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 4262 dr.mDrawableBottom.draw(canvas); 4263 canvas.restore(); 4264 } 4265 } 4266 4267 if (mPreDrawState == PREDRAW_DONE) { 4268 final ViewTreeObserver observer = getViewTreeObserver(); 4269 if (observer != null) { 4270 observer.removeOnPreDrawListener(this); 4271 mPreDrawState = PREDRAW_NOT_REGISTERED; 4272 } 4273 } 4274 4275 int color = mCurTextColor; 4276 4277 if (mLayout == null) { 4278 assumeLayout(); 4279 } 4280 4281 Layout layout = mLayout; 4282 int cursorcolor = color; 4283 4284 if (mHint != null && mText.length() == 0) { 4285 if (mHintTextColor != null) { 4286 color = mCurHintTextColor; 4287 } 4288 4289 layout = mHintLayout; 4290 } 4291 4292 mTextPaint.setColor(color); 4293 if (mCurrentAlpha != 255) { 4294 // If set, the alpha will override the color's alpha. Multiply the alphas. 4295 mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255); 4296 } 4297 mTextPaint.drawableState = getDrawableState(); 4298 4299 canvas.save(); 4300 /* Would be faster if we didn't have to do this. Can we chop the 4301 (displayable) text so that we don't need to do this ever? 4302 */ 4303 4304 int extendedPaddingTop = getExtendedPaddingTop(); 4305 int extendedPaddingBottom = getExtendedPaddingBottom(); 4306 4307 float clipLeft = compoundPaddingLeft + scrollX; 4308 float clipTop = extendedPaddingTop + scrollY; 4309 float clipRight = right - left - compoundPaddingRight + scrollX; 4310 float clipBottom = bottom - top - extendedPaddingBottom + scrollY; 4311 4312 if (mShadowRadius != 0) { 4313 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 4314 clipRight += Math.max(0, mShadowDx + mShadowRadius); 4315 4316 clipTop += Math.min(0, mShadowDy - mShadowRadius); 4317 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 4318 } 4319 4320 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 4321 4322 int voffsetText = 0; 4323 int voffsetCursor = 0; 4324 4325 // translate in by our padding 4326 { 4327 /* shortcircuit calling getVerticaOffset() */ 4328 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4329 voffsetText = getVerticalOffset(false); 4330 voffsetCursor = getVerticalOffset(true); 4331 } 4332 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 4333 } 4334 4335 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 4336 if (!mSingleLine && getLineCount() == 1 && canMarquee() && 4337 (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 4338 canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft - 4339 getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f); 4340 } 4341 4342 if (mMarquee != null && mMarquee.isRunning()) { 4343 canvas.translate(-mMarquee.mScroll, 0.0f); 4344 } 4345 } 4346 4347 Path highlight = null; 4348 int selStart = -1, selEnd = -1; 4349 4350 // If there is no movement method, then there can be no selection. 4351 // Check that first and attempt to skip everything having to do with 4352 // the cursor. 4353 // XXX This is not strictly true -- a program could set the 4354 // selection manually if it really wanted to. 4355 if (mMovement != null && (isFocused() || isPressed())) { 4356 selStart = getSelectionStart(); 4357 selEnd = getSelectionEnd(); 4358 4359 if ((isCursorVisible() || mTextIsSelectable) && selStart >= 0 && isEnabled()) { 4360 if (mHighlightPath == null) 4361 mHighlightPath = new Path(); 4362 4363 if (selStart == selEnd) { 4364 if (!mTextIsSelectable && 4365 (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) { 4366 if (mHighlightPathBogus) { 4367 mHighlightPath.reset(); 4368 mLayout.getCursorPath(selStart, mHighlightPath, mText); 4369 mHighlightPathBogus = false; 4370 } 4371 4372 // XXX should pass to skin instead of drawing directly 4373 mHighlightPaint.setColor(cursorcolor); 4374 if (mCurrentAlpha != 255) { 4375 mHighlightPaint.setAlpha( 4376 (mCurrentAlpha * Color.alpha(cursorcolor)) / 255); 4377 } 4378 mHighlightPaint.setStyle(Paint.Style.STROKE); 4379 4380 highlight = mHighlightPath; 4381 } 4382 } else { 4383 if (mHighlightPathBogus) { 4384 mHighlightPath.reset(); 4385 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 4386 mHighlightPathBogus = false; 4387 } 4388 4389 // XXX should pass to skin instead of drawing directly 4390 mHighlightPaint.setColor(mHighlightColor); 4391 if (mCurrentAlpha != 255) { 4392 mHighlightPaint.setAlpha( 4393 (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255); 4394 } 4395 mHighlightPaint.setStyle(Paint.Style.FILL); 4396 4397 highlight = mHighlightPath; 4398 } 4399 } 4400 } 4401 4402 /* Comment out until we decide what to do about animations 4403 boolean isLinearTextOn = false; 4404 if (currentTransformation != null) { 4405 isLinearTextOn = mTextPaint.isLinearTextOn(); 4406 Matrix m = currentTransformation.getMatrix(); 4407 if (!m.isIdentity()) { 4408 // mTextPaint.setLinearTextOn(true); 4409 } 4410 } 4411 */ 4412 4413 final InputMethodState ims = mInputMethodState; 4414 final int cursorOffsetVertical = voffsetCursor - voffsetText; 4415 if (ims != null && ims.mBatchEditNesting == 0) { 4416 InputMethodManager imm = InputMethodManager.peekInstance(); 4417 if (imm != null) { 4418 if (imm.isActive(this)) { 4419 boolean reported = false; 4420 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4421 // We are in extract mode and the content has changed 4422 // in some way... just report complete new text to the 4423 // input method. 4424 reported = reportExtractedText(); 4425 } 4426 if (!reported && highlight != null) { 4427 int candStart = -1; 4428 int candEnd = -1; 4429 if (mText instanceof Spannable) { 4430 Spannable sp = (Spannable)mText; 4431 candStart = EditableInputConnection.getComposingSpanStart(sp); 4432 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 4433 } 4434 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 4435 } 4436 } 4437 4438 if (imm.isWatchingCursor(this) && highlight != null) { 4439 highlight.computeBounds(ims.mTmpRectF, true); 4440 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 4441 4442 canvas.getMatrix().mapPoints(ims.mTmpOffset); 4443 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 4444 4445 ims.mTmpRectF.offset(0, cursorOffsetVertical); 4446 4447 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 4448 (int)(ims.mTmpRectF.top + 0.5), 4449 (int)(ims.mTmpRectF.right + 0.5), 4450 (int)(ims.mTmpRectF.bottom + 0.5)); 4451 4452 imm.updateCursor(this, 4453 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 4454 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 4455 } 4456 } 4457 } 4458 4459 if (mCorrectionHighlighter != null) { 4460 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 4461 } 4462 4463 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 4464 4465 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 4466 canvas.translate((int) mMarquee.getGhostOffset(), 0.0f); 4467 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 4468 } 4469 4470 /* Comment out until we decide what to do about animations 4471 if (currentTransformation != null) { 4472 mTextPaint.setLinearTextOn(isLinearTextOn); 4473 } 4474 */ 4475 4476 canvas.restore(); 4477 4478 updateCursorControllerPositions(); 4479 } 4480 4481 /** 4482 * Update the positions of the CursorControllers. Needed by WebTextView, 4483 * which does not draw. 4484 * @hide 4485 */ 4486 protected void updateCursorControllerPositions() { 4487 // No need to create the controllers if they were not already 4488 if (mInsertionPointCursorController != null && 4489 mInsertionPointCursorController.isShowing()) { 4490 mInsertionPointCursorController.updatePosition(); 4491 } 4492 if (mSelectionModifierCursorController != null && 4493 mSelectionModifierCursorController.isShowing()) { 4494 mSelectionModifierCursorController.updatePosition(); 4495 } 4496 } 4497 4498 @Override 4499 public void getFocusedRect(Rect r) { 4500 if (mLayout == null) { 4501 super.getFocusedRect(r); 4502 return; 4503 } 4504 4505 int sel = getSelectionEnd(); 4506 if (sel < 0) { 4507 super.getFocusedRect(r); 4508 return; 4509 } 4510 4511 int line = mLayout.getLineForOffset(sel); 4512 r.top = mLayout.getLineTop(line); 4513 r.bottom = mLayout.getLineBottom(line); 4514 4515 r.left = (int) mLayout.getPrimaryHorizontal(sel); 4516 r.right = r.left + 1; 4517 4518 // Adjust for padding and gravity. 4519 int paddingLeft = getCompoundPaddingLeft(); 4520 int paddingTop = getExtendedPaddingTop(); 4521 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4522 paddingTop += getVerticalOffset(false); 4523 } 4524 r.offset(paddingLeft, paddingTop); 4525 } 4526 4527 /** 4528 * Return the number of lines of text, or 0 if the internal Layout has not 4529 * been built. 4530 */ 4531 public int getLineCount() { 4532 return mLayout != null ? mLayout.getLineCount() : 0; 4533 } 4534 4535 /** 4536 * Return the baseline for the specified line (0...getLineCount() - 1) 4537 * If bounds is not null, return the top, left, right, bottom extents 4538 * of the specified line in it. If the internal Layout has not been built, 4539 * return 0 and set bounds to (0, 0, 0, 0) 4540 * @param line which line to examine (0..getLineCount() - 1) 4541 * @param bounds Optional. If not null, it returns the extent of the line 4542 * @return the Y-coordinate of the baseline 4543 */ 4544 public int getLineBounds(int line, Rect bounds) { 4545 if (mLayout == null) { 4546 if (bounds != null) { 4547 bounds.set(0, 0, 0, 0); 4548 } 4549 return 0; 4550 } 4551 else { 4552 int baseline = mLayout.getLineBounds(line, bounds); 4553 4554 int voffset = getExtendedPaddingTop(); 4555 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4556 voffset += getVerticalOffset(true); 4557 } 4558 if (bounds != null) { 4559 bounds.offset(getCompoundPaddingLeft(), voffset); 4560 } 4561 return baseline + voffset; 4562 } 4563 } 4564 4565 @Override 4566 public int getBaseline() { 4567 if (mLayout == null) { 4568 return super.getBaseline(); 4569 } 4570 4571 int voffset = 0; 4572 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4573 voffset = getVerticalOffset(true); 4574 } 4575 4576 return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); 4577 } 4578 4579 @Override 4580 public boolean onKeyDown(int keyCode, KeyEvent event) { 4581 int which = doKeyDown(keyCode, event, null); 4582 if (which == 0) { 4583 // Go through default dispatching. 4584 return super.onKeyDown(keyCode, event); 4585 } 4586 4587 return true; 4588 } 4589 4590 @Override 4591 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4592 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 4593 4594 int which = doKeyDown(keyCode, down, event); 4595 if (which == 0) { 4596 // Go through default dispatching. 4597 return super.onKeyMultiple(keyCode, repeatCount, event); 4598 } 4599 if (which == -1) { 4600 // Consumed the whole thing. 4601 return true; 4602 } 4603 4604 repeatCount--; 4605 4606 // We are going to dispatch the remaining events to either the input 4607 // or movement method. To do this, we will just send a repeated stream 4608 // of down and up events until we have done the complete repeatCount. 4609 // It would be nice if those interfaces had an onKeyMultiple() method, 4610 // but adding that is a more complicated change. 4611 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 4612 if (which == 1) { 4613 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4614 while (--repeatCount > 0) { 4615 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 4616 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4617 } 4618 hideErrorIfUnchanged(); 4619 4620 } else if (which == 2) { 4621 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4622 while (--repeatCount > 0) { 4623 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 4624 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4625 } 4626 } 4627 4628 return true; 4629 } 4630 4631 /** 4632 * Returns true if pressing ENTER in this field advances focus instead 4633 * of inserting the character. This is true mostly in single-line fields, 4634 * but also in mail addresses and subjects which will display on multiple 4635 * lines but where it doesn't make sense to insert newlines. 4636 */ 4637 private boolean shouldAdvanceFocusOnEnter() { 4638 if (mInput == null) { 4639 return false; 4640 } 4641 4642 if (mSingleLine) { 4643 return true; 4644 } 4645 4646 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 4647 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 4648 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS 4649 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 4650 return true; 4651 } 4652 } 4653 4654 return false; 4655 } 4656 4657 /** 4658 * Returns true if pressing TAB in this field advances focus instead 4659 * of inserting the character. Insert tabs only in multi-line editors. 4660 */ 4661 private boolean shouldAdvanceFocusOnTab() { 4662 if (mInput != null && !mSingleLine) { 4663 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 4664 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 4665 if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE 4666 || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { 4667 return false; 4668 } 4669 } 4670 } 4671 return true; 4672 } 4673 4674 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 4675 if (!isEnabled()) { 4676 return 0; 4677 } 4678 4679 switch (keyCode) { 4680 case KeyEvent.KEYCODE_ENTER: 4681 mEnterKeyIsDown = true; 4682 if (event.hasNoModifiers()) { 4683 // When mInputContentType is set, we know that we are 4684 // running in a "modern" cupcake environment, so don't need 4685 // to worry about the application trying to capture 4686 // enter key events. 4687 if (mInputContentType != null) { 4688 // If there is an action listener, given them a 4689 // chance to consume the event. 4690 if (mInputContentType.onEditorActionListener != null && 4691 mInputContentType.onEditorActionListener.onEditorAction( 4692 this, EditorInfo.IME_NULL, event)) { 4693 mInputContentType.enterDown = true; 4694 // We are consuming the enter key for them. 4695 return -1; 4696 } 4697 } 4698 4699 // If our editor should move focus when enter is pressed, or 4700 // this is a generated event from an IME action button, then 4701 // don't let it be inserted into the text. 4702 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 4703 || shouldAdvanceFocusOnEnter()) { 4704 if (mOnClickListener != null) { 4705 return 0; 4706 } 4707 return -1; 4708 } 4709 } 4710 break; 4711 4712 case KeyEvent.KEYCODE_DPAD_CENTER: 4713 mDPadCenterIsDown = true; 4714 if (event.hasNoModifiers()) { 4715 if (shouldAdvanceFocusOnEnter()) { 4716 return 0; 4717 } 4718 } 4719 break; 4720 4721 case KeyEvent.KEYCODE_TAB: 4722 if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 4723 if (shouldAdvanceFocusOnTab()) { 4724 return 0; 4725 } 4726 } 4727 break; 4728 4729 // Has to be done on key down (and not on key up) to correctly be intercepted. 4730 case KeyEvent.KEYCODE_BACK: 4731 if (mSelectionActionMode != null) { 4732 stopSelectionActionMode(); 4733 return -1; 4734 } 4735 break; 4736 } 4737 4738 if (mInput != null) { 4739 resetErrorChangedFlag(); 4740 4741 boolean doDown = true; 4742 if (otherEvent != null) { 4743 try { 4744 beginBatchEdit(); 4745 final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent); 4746 hideErrorIfUnchanged(); 4747 doDown = false; 4748 if (handled) { 4749 return -1; 4750 } 4751 } catch (AbstractMethodError e) { 4752 // onKeyOther was added after 1.0, so if it isn't 4753 // implemented we need to try to dispatch as a regular down. 4754 } finally { 4755 endBatchEdit(); 4756 } 4757 } 4758 4759 if (doDown) { 4760 beginBatchEdit(); 4761 final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event); 4762 endBatchEdit(); 4763 hideErrorIfUnchanged(); 4764 if (handled) return 1; 4765 } 4766 } 4767 4768 // bug 650865: sometimes we get a key event before a layout. 4769 // don't try to move around if we don't know the layout. 4770 4771 if (mMovement != null && mLayout != null) { 4772 boolean doDown = true; 4773 if (otherEvent != null) { 4774 try { 4775 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 4776 otherEvent); 4777 doDown = false; 4778 if (handled) { 4779 return -1; 4780 } 4781 } catch (AbstractMethodError e) { 4782 // onKeyOther was added after 1.0, so if it isn't 4783 // implemented we need to try to dispatch as a regular down. 4784 } 4785 } 4786 if (doDown) { 4787 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 4788 return 2; 4789 } 4790 } 4791 4792 return 0; 4793 } 4794 4795 /** 4796 * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} 4797 * can be recorded. 4798 * @hide 4799 */ 4800 public void resetErrorChangedFlag() { 4801 /* 4802 * Keep track of what the error was before doing the input 4803 * so that if an input filter changed the error, we leave 4804 * that error showing. Otherwise, we take down whatever 4805 * error was showing when the user types something. 4806 */ 4807 mErrorWasChanged = false; 4808 } 4809 4810 /** 4811 * @hide 4812 */ 4813 public void hideErrorIfUnchanged() { 4814 if (mError != null && !mErrorWasChanged) { 4815 setError(null, null); 4816 } 4817 } 4818 4819 @Override 4820 public boolean onKeyUp(int keyCode, KeyEvent event) { 4821 if (!isEnabled()) { 4822 return super.onKeyUp(keyCode, event); 4823 } 4824 4825 switch (keyCode) { 4826 case KeyEvent.KEYCODE_DPAD_CENTER: 4827 mDPadCenterIsDown = false; 4828 if (event.hasNoModifiers()) { 4829 /* 4830 * If there is a click listener, just call through to 4831 * super, which will invoke it. 4832 * 4833 * If there isn't a click listener, try to show the soft 4834 * input method. (It will also 4835 * call performClick(), but that won't do anything in 4836 * this case.) 4837 */ 4838 if (mOnClickListener == null) { 4839 if (mMovement != null && mText instanceof Editable 4840 && mLayout != null && onCheckIsTextEditor()) { 4841 InputMethodManager imm = InputMethodManager.peekInstance(); 4842 if (imm != null) imm.showSoftInput(this, 0); 4843 } 4844 } 4845 } 4846 return super.onKeyUp(keyCode, event); 4847 4848 case KeyEvent.KEYCODE_ENTER: 4849 mEnterKeyIsDown = false; 4850 if (event.hasNoModifiers()) { 4851 if (mInputContentType != null 4852 && mInputContentType.onEditorActionListener != null 4853 && mInputContentType.enterDown) { 4854 mInputContentType.enterDown = false; 4855 if (mInputContentType.onEditorActionListener.onEditorAction( 4856 this, EditorInfo.IME_NULL, event)) { 4857 return true; 4858 } 4859 } 4860 4861 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 4862 || shouldAdvanceFocusOnEnter()) { 4863 /* 4864 * If there is a click listener, just call through to 4865 * super, which will invoke it. 4866 * 4867 * If there isn't a click listener, try to advance focus, 4868 * but still call through to super, which will reset the 4869 * pressed state and longpress state. (It will also 4870 * call performClick(), but that won't do anything in 4871 * this case.) 4872 */ 4873 if (mOnClickListener == null) { 4874 View v = focusSearch(FOCUS_DOWN); 4875 4876 if (v != null) { 4877 if (!v.requestFocus(FOCUS_DOWN)) { 4878 throw new IllegalStateException( 4879 "focus search returned a view " + 4880 "that wasn't able to take focus!"); 4881 } 4882 4883 /* 4884 * Return true because we handled the key; super 4885 * will return false because there was no click 4886 * listener. 4887 */ 4888 super.onKeyUp(keyCode, event); 4889 return true; 4890 } else if ((event.getFlags() 4891 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 4892 // No target for next focus, but make sure the IME 4893 // if this came from it. 4894 InputMethodManager imm = InputMethodManager.peekInstance(); 4895 if (imm != null && imm.isActive(this)) { 4896 imm.hideSoftInputFromWindow(getWindowToken(), 0); 4897 } 4898 } 4899 } 4900 } 4901 return super.onKeyUp(keyCode, event); 4902 } 4903 break; 4904 } 4905 4906 if (mInput != null) 4907 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 4908 return true; 4909 4910 if (mMovement != null && mLayout != null) 4911 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 4912 return true; 4913 4914 return super.onKeyUp(keyCode, event); 4915 } 4916 4917 @Override public boolean onCheckIsTextEditor() { 4918 return mInputType != EditorInfo.TYPE_NULL; 4919 } 4920 4921 @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4922 if (onCheckIsTextEditor() && isEnabled()) { 4923 if (mInputMethodState == null) { 4924 mInputMethodState = new InputMethodState(); 4925 } 4926 outAttrs.inputType = mInputType; 4927 if (mInputContentType != null) { 4928 outAttrs.imeOptions = mInputContentType.imeOptions; 4929 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 4930 outAttrs.actionLabel = mInputContentType.imeActionLabel; 4931 outAttrs.actionId = mInputContentType.imeActionId; 4932 outAttrs.extras = mInputContentType.extras; 4933 } else { 4934 outAttrs.imeOptions = EditorInfo.IME_NULL; 4935 } 4936 if (focusSearch(FOCUS_DOWN) != null) { 4937 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 4938 } 4939 if (focusSearch(FOCUS_UP) != null) { 4940 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 4941 } 4942 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 4943 == EditorInfo.IME_ACTION_UNSPECIFIED) { 4944 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 4945 // An action has not been set, but the enter key will move to 4946 // the next focus, so set the action to that. 4947 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 4948 } else { 4949 // An action has not been set, and there is no focus to move 4950 // to, so let's just supply a "done" action. 4951 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 4952 } 4953 if (!shouldAdvanceFocusOnEnter()) { 4954 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 4955 } 4956 } 4957 if (isMultilineInputType(outAttrs.inputType)) { 4958 // Multi-line text editors should always show an enter key. 4959 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 4960 } 4961 outAttrs.hintText = mHint; 4962 if (mText instanceof Editable) { 4963 InputConnection ic = new EditableInputConnection(this); 4964 outAttrs.initialSelStart = getSelectionStart(); 4965 outAttrs.initialSelEnd = getSelectionEnd(); 4966 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 4967 return ic; 4968 } 4969 } 4970 return null; 4971 } 4972 4973 /** 4974 * If this TextView contains editable content, extract a portion of it 4975 * based on the information in <var>request</var> in to <var>outText</var>. 4976 * @return Returns true if the text was successfully extracted, else false. 4977 */ 4978 public boolean extractText(ExtractedTextRequest request, 4979 ExtractedText outText) { 4980 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 4981 EXTRACT_UNKNOWN, outText); 4982 } 4983 4984 static final int EXTRACT_NOTHING = -2; 4985 static final int EXTRACT_UNKNOWN = -1; 4986 4987 boolean extractTextInternal(ExtractedTextRequest request, 4988 int partialStartOffset, int partialEndOffset, int delta, 4989 ExtractedText outText) { 4990 final CharSequence content = mText; 4991 if (content != null) { 4992 if (partialStartOffset != EXTRACT_NOTHING) { 4993 final int N = content.length(); 4994 if (partialStartOffset < 0) { 4995 outText.partialStartOffset = outText.partialEndOffset = -1; 4996 partialStartOffset = 0; 4997 partialEndOffset = N; 4998 } else { 4999 // Now use the delta to determine the actual amount of text 5000 // we need. 5001 partialEndOffset += delta; 5002 // Adjust offsets to ensure we contain full spans. 5003 if (content instanceof Spanned) { 5004 Spanned spanned = (Spanned)content; 5005 Object[] spans = spanned.getSpans(partialStartOffset, 5006 partialEndOffset, ParcelableSpan.class); 5007 int i = spans.length; 5008 while (i > 0) { 5009 i--; 5010 int j = spanned.getSpanStart(spans[i]); 5011 if (j < partialStartOffset) partialStartOffset = j; 5012 j = spanned.getSpanEnd(spans[i]); 5013 if (j > partialEndOffset) partialEndOffset = j; 5014 } 5015 } 5016 outText.partialStartOffset = partialStartOffset; 5017 outText.partialEndOffset = partialEndOffset - delta; 5018 5019 if (partialStartOffset > N) { 5020 partialStartOffset = N; 5021 } else if (partialStartOffset < 0) { 5022 partialStartOffset = 0; 5023 } 5024 if (partialEndOffset > N) { 5025 partialEndOffset = N; 5026 } else if (partialEndOffset < 0) { 5027 partialEndOffset = 0; 5028 } 5029 } 5030 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 5031 outText.text = content.subSequence(partialStartOffset, 5032 partialEndOffset); 5033 } else { 5034 outText.text = TextUtils.substring(content, partialStartOffset, 5035 partialEndOffset); 5036 } 5037 } else { 5038 outText.partialStartOffset = 0; 5039 outText.partialEndOffset = 0; 5040 outText.text = ""; 5041 } 5042 outText.flags = 0; 5043 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 5044 outText.flags |= ExtractedText.FLAG_SELECTING; 5045 } 5046 if (mSingleLine) { 5047 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 5048 } 5049 outText.startOffset = 0; 5050 outText.selectionStart = getSelectionStart(); 5051 outText.selectionEnd = getSelectionEnd(); 5052 return true; 5053 } 5054 return false; 5055 } 5056 5057 boolean reportExtractedText() { 5058 final InputMethodState ims = mInputMethodState; 5059 if (ims != null) { 5060 final boolean contentChanged = ims.mContentChanged; 5061 if (contentChanged || ims.mSelectionModeChanged) { 5062 ims.mContentChanged = false; 5063 ims.mSelectionModeChanged = false; 5064 final ExtractedTextRequest req = mInputMethodState.mExtracting; 5065 if (req != null) { 5066 InputMethodManager imm = InputMethodManager.peekInstance(); 5067 if (imm != null) { 5068 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 5069 + ims.mChangedStart + " end=" + ims.mChangedEnd 5070 + " delta=" + ims.mChangedDelta); 5071 if (ims.mChangedStart < 0 && !contentChanged) { 5072 ims.mChangedStart = EXTRACT_NOTHING; 5073 } 5074 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 5075 ims.mChangedDelta, ims.mTmpExtracted)) { 5076 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 5077 + ims.mTmpExtracted.partialStartOffset 5078 + " end=" + ims.mTmpExtracted.partialEndOffset 5079 + ": " + ims.mTmpExtracted.text); 5080 imm.updateExtractedText(this, req.token, 5081 mInputMethodState.mTmpExtracted); 5082 ims.mChangedStart = EXTRACT_UNKNOWN; 5083 ims.mChangedEnd = EXTRACT_UNKNOWN; 5084 ims.mChangedDelta = 0; 5085 ims.mContentChanged = false; 5086 return true; 5087 } 5088 } 5089 } 5090 } 5091 } 5092 return false; 5093 } 5094 5095 /** 5096 * This is used to remove all style-impacting spans from text before new 5097 * extracted text is being replaced into it, so that we don't have any 5098 * lingering spans applied during the replace. 5099 */ 5100 static void removeParcelableSpans(Spannable spannable, int start, int end) { 5101 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 5102 int i = spans.length; 5103 while (i > 0) { 5104 i--; 5105 spannable.removeSpan(spans[i]); 5106 } 5107 } 5108 5109 /** 5110 * Apply to this text view the given extracted text, as previously 5111 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 5112 */ 5113 public void setExtractedText(ExtractedText text) { 5114 Editable content = getEditableText(); 5115 if (text.text != null) { 5116 if (content == null) { 5117 setText(text.text, TextView.BufferType.EDITABLE); 5118 } else if (text.partialStartOffset < 0) { 5119 removeParcelableSpans(content, 0, content.length()); 5120 content.replace(0, content.length(), text.text); 5121 } else { 5122 final int N = content.length(); 5123 int start = text.partialStartOffset; 5124 if (start > N) start = N; 5125 int end = text.partialEndOffset; 5126 if (end > N) end = N; 5127 removeParcelableSpans(content, start, end); 5128 content.replace(start, end, text.text); 5129 } 5130 } 5131 5132 // Now set the selection position... make sure it is in range, to 5133 // avoid crashes. If this is a partial update, it is possible that 5134 // the underlying text may have changed, causing us problems here. 5135 // Also we just don't want to trust clients to do the right thing. 5136 Spannable sp = (Spannable)getText(); 5137 final int N = sp.length(); 5138 int start = text.selectionStart; 5139 if (start < 0) start = 0; 5140 else if (start > N) start = N; 5141 int end = text.selectionEnd; 5142 if (end < 0) end = 0; 5143 else if (end > N) end = N; 5144 Selection.setSelection(sp, start, end); 5145 5146 // Finally, update the selection mode. 5147 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 5148 MetaKeyKeyListener.startSelecting(this, sp); 5149 } else { 5150 MetaKeyKeyListener.stopSelecting(this, sp); 5151 } 5152 } 5153 5154 /** 5155 * @hide 5156 */ 5157 public void setExtracting(ExtractedTextRequest req) { 5158 if (mInputMethodState != null) { 5159 mInputMethodState.mExtracting = req; 5160 } 5161 // This stops a possible text selection mode. Maybe not intended. 5162 hideControllers(); 5163 } 5164 5165 /** 5166 * Called by the framework in response to a text completion from 5167 * the current input method, provided by it calling 5168 * {@link InputConnection#commitCompletion 5169 * InputConnection.commitCompletion()}. The default implementation does 5170 * nothing; text views that are supporting auto-completion should override 5171 * this to do their desired behavior. 5172 * 5173 * @param text The auto complete text the user has selected. 5174 */ 5175 public void onCommitCompletion(CompletionInfo text) { 5176 } 5177 5178 /** 5179 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 5180 * a dictionnary) from the current input method, provided by it calling 5181 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 5182 * implementation flashes the background of the corrected word to provide feedback to the user. 5183 * 5184 * @param info The auto correct info about the text that was corrected. 5185 */ 5186 public void onCommitCorrection(CorrectionInfo info) { 5187 if (mCorrectionHighlighter == null) { 5188 mCorrectionHighlighter = new CorrectionHighlighter(); 5189 } else { 5190 mCorrectionHighlighter.invalidate(false); 5191 } 5192 5193 mCorrectionHighlighter.highlight(info); 5194 } 5195 5196 private class CorrectionHighlighter { 5197 private final Path mPath = new Path(); 5198 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5199 private int mStart, mEnd; 5200 private long mFadingStartTime; 5201 private final static int FADE_OUT_DURATION = 400; 5202 5203 public CorrectionHighlighter() { 5204 mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale); 5205 mPaint.setStyle(Paint.Style.FILL); 5206 } 5207 5208 public void highlight(CorrectionInfo info) { 5209 mStart = info.getOffset(); 5210 mEnd = mStart + info.getNewText().length(); 5211 mFadingStartTime = SystemClock.uptimeMillis(); 5212 5213 if (mStart < 0 || mEnd < 0) { 5214 stopAnimation(); 5215 } 5216 } 5217 5218 public void draw(Canvas canvas, int cursorOffsetVertical) { 5219 if (updatePath() && updatePaint()) { 5220 if (cursorOffsetVertical != 0) { 5221 canvas.translate(0, cursorOffsetVertical); 5222 } 5223 5224 canvas.drawPath(mPath, mPaint); 5225 5226 if (cursorOffsetVertical != 0) { 5227 canvas.translate(0, -cursorOffsetVertical); 5228 } 5229 invalidate(true); 5230 } else { 5231 stopAnimation(); 5232 invalidate(false); 5233 } 5234 } 5235 5236 private boolean updatePaint() { 5237 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5238 if (duration > FADE_OUT_DURATION) return false; 5239 5240 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5241 final int highlightColorAlpha = Color.alpha(mHighlightColor); 5242 final int color = (mHighlightColor & 0x00FFFFFF) + 5243 ((int) (highlightColorAlpha * coef) << 24); 5244 mPaint.setColor(color); 5245 return true; 5246 } 5247 5248 private boolean updatePath() { 5249 final Layout layout = TextView.this.mLayout; 5250 if (layout == null) return false; 5251 5252 // Update in case text is edited while the animation is run 5253 final int length = mText.length(); 5254 int start = Math.min(length, mStart); 5255 int end = Math.min(length, mEnd); 5256 5257 mPath.reset(); 5258 TextView.this.mLayout.getSelectionPath(start, end, mPath); 5259 return true; 5260 } 5261 5262 private void invalidate(boolean delayed) { 5263 if (TextView.this.mLayout == null) return; 5264 5265 synchronized (sTempRect) { 5266 mPath.computeBounds(sTempRect, false); 5267 5268 int left = getCompoundPaddingLeft(); 5269 int top = getExtendedPaddingTop() + getVerticalOffset(true); 5270 5271 if (delayed) { 5272 TextView.this.postInvalidateDelayed(16, // 60 Hz update 5273 left + (int) sTempRect.left, top + (int) sTempRect.top, 5274 left + (int) sTempRect.right, top + (int) sTempRect.bottom); 5275 } else { 5276 TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top, 5277 (int) sTempRect.right, (int) sTempRect.bottom); 5278 } 5279 } 5280 } 5281 5282 private void stopAnimation() { 5283 TextView.this.mCorrectionHighlighter = null; 5284 } 5285 } 5286 5287 public void beginBatchEdit() { 5288 mInBatchEditControllers = true; 5289 final InputMethodState ims = mInputMethodState; 5290 if (ims != null) { 5291 int nesting = ++ims.mBatchEditNesting; 5292 if (nesting == 1) { 5293 ims.mCursorChanged = false; 5294 ims.mChangedDelta = 0; 5295 if (ims.mContentChanged) { 5296 // We already have a pending change from somewhere else, 5297 // so turn this into a full update. 5298 ims.mChangedStart = 0; 5299 ims.mChangedEnd = mText.length(); 5300 } else { 5301 ims.mChangedStart = EXTRACT_UNKNOWN; 5302 ims.mChangedEnd = EXTRACT_UNKNOWN; 5303 ims.mContentChanged = false; 5304 } 5305 onBeginBatchEdit(); 5306 } 5307 } 5308 } 5309 5310 public void endBatchEdit() { 5311 mInBatchEditControllers = false; 5312 final InputMethodState ims = mInputMethodState; 5313 if (ims != null) { 5314 int nesting = --ims.mBatchEditNesting; 5315 if (nesting == 0) { 5316 finishBatchEdit(ims); 5317 } 5318 } 5319 } 5320 5321 void ensureEndedBatchEdit() { 5322 final InputMethodState ims = mInputMethodState; 5323 if (ims != null && ims.mBatchEditNesting != 0) { 5324 ims.mBatchEditNesting = 0; 5325 finishBatchEdit(ims); 5326 } 5327 } 5328 5329 void finishBatchEdit(final InputMethodState ims) { 5330 onEndBatchEdit(); 5331 5332 if (ims.mContentChanged || ims.mSelectionModeChanged) { 5333 updateAfterEdit(); 5334 reportExtractedText(); 5335 } else if (ims.mCursorChanged) { 5336 // Cheezy way to get us to report the current cursor location. 5337 invalidateCursor(); 5338 } 5339 } 5340 5341 void updateAfterEdit() { 5342 invalidate(); 5343 int curs = getSelectionStart(); 5344 5345 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == 5346 Gravity.BOTTOM) { 5347 registerForPreDraw(); 5348 } 5349 5350 if (curs >= 0) { 5351 mHighlightPathBogus = true; 5352 5353 if (isFocused()) { 5354 mShowCursor = SystemClock.uptimeMillis(); 5355 makeBlink(); 5356 } 5357 } 5358 5359 checkForResize(); 5360 } 5361 5362 /** 5363 * Called by the framework in response to a request to begin a batch 5364 * of edit operations through a call to link {@link #beginBatchEdit()}. 5365 */ 5366 public void onBeginBatchEdit() { 5367 } 5368 5369 /** 5370 * Called by the framework in response to a request to end a batch 5371 * of edit operations through a call to link {@link #endBatchEdit}. 5372 */ 5373 public void onEndBatchEdit() { 5374 } 5375 5376 /** 5377 * Called by the framework in response to a private command from the 5378 * current method, provided by it calling 5379 * {@link InputConnection#performPrivateCommand 5380 * InputConnection.performPrivateCommand()}. 5381 * 5382 * @param action The action name of the command. 5383 * @param data Any additional data for the command. This may be null. 5384 * @return Return true if you handled the command, else false. 5385 */ 5386 public boolean onPrivateIMECommand(String action, Bundle data) { 5387 return false; 5388 } 5389 5390 private void nullLayouts() { 5391 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 5392 mSavedLayout = (BoringLayout) mLayout; 5393 } 5394 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 5395 mSavedHintLayout = (BoringLayout) mHintLayout; 5396 } 5397 5398 mLayout = mHintLayout = null; 5399 5400 // Since it depends on the value of mLayout 5401 prepareCursorControllers(); 5402 } 5403 5404 /** 5405 * Make a new Layout based on the already-measured size of the view, 5406 * on the assumption that it was measured correctly at some point. 5407 */ 5408 private void assumeLayout() { 5409 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5410 5411 if (width < 1) { 5412 width = 0; 5413 } 5414 5415 int physicalWidth = width; 5416 5417 if (mHorizontallyScrolling) { 5418 width = VERY_WIDE; 5419 } 5420 5421 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 5422 physicalWidth, false); 5423 } 5424 5425 /** 5426 * The width passed in is now the desired layout width, 5427 * not the full view width with padding. 5428 * {@hide} 5429 */ 5430 protected void makeNewLayout(int w, int hintWidth, 5431 BoringLayout.Metrics boring, 5432 BoringLayout.Metrics hintBoring, 5433 int ellipsisWidth, boolean bringIntoView) { 5434 stopMarquee(); 5435 5436 mHighlightPathBogus = true; 5437 5438 if (w < 0) { 5439 w = 0; 5440 } 5441 if (hintWidth < 0) { 5442 hintWidth = 0; 5443 } 5444 5445 Layout.Alignment alignment; 5446 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 5447 case Gravity.CENTER_HORIZONTAL: 5448 alignment = Layout.Alignment.ALIGN_CENTER; 5449 break; 5450 5451 case Gravity.RIGHT: 5452 // Note, Layout resolves ALIGN_OPPOSITE to left or 5453 // right based on the paragraph direction. 5454 alignment = Layout.Alignment.ALIGN_OPPOSITE; 5455 break; 5456 5457 default: 5458 alignment = Layout.Alignment.ALIGN_NORMAL; 5459 } 5460 5461 boolean shouldEllipsize = mEllipsize != null && mInput == null; 5462 5463 if (mText instanceof Spannable) { 5464 mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w, 5465 alignment, mSpacingMult, 5466 mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null, 5467 ellipsisWidth); 5468 } else { 5469 if (boring == UNKNOWN_BORING) { 5470 boring = BoringLayout.isBoring(mTransformed, mTextPaint, 5471 mBoring); 5472 if (boring != null) { 5473 mBoring = boring; 5474 } 5475 } 5476 5477 if (boring != null) { 5478 if (boring.width <= w && 5479 (mEllipsize == null || boring.width <= ellipsisWidth)) { 5480 if (mSavedLayout != null) { 5481 mLayout = mSavedLayout. 5482 replaceOrMake(mTransformed, mTextPaint, 5483 w, alignment, mSpacingMult, mSpacingAdd, 5484 boring, mIncludePad); 5485 } else { 5486 mLayout = BoringLayout.make(mTransformed, mTextPaint, 5487 w, alignment, mSpacingMult, mSpacingAdd, 5488 boring, mIncludePad); 5489 } 5490 5491 mSavedLayout = (BoringLayout) mLayout; 5492 } else if (shouldEllipsize && boring.width <= w) { 5493 if (mSavedLayout != null) { 5494 mLayout = mSavedLayout. 5495 replaceOrMake(mTransformed, mTextPaint, 5496 w, alignment, mSpacingMult, mSpacingAdd, 5497 boring, mIncludePad, mEllipsize, 5498 ellipsisWidth); 5499 } else { 5500 mLayout = BoringLayout.make(mTransformed, mTextPaint, 5501 w, alignment, mSpacingMult, mSpacingAdd, 5502 boring, mIncludePad, mEllipsize, 5503 ellipsisWidth); 5504 } 5505 } else if (shouldEllipsize) { 5506 mLayout = new StaticLayout(mTransformed, 5507 0, mTransformed.length(), 5508 mTextPaint, w, alignment, mSpacingMult, 5509 mSpacingAdd, mIncludePad, mEllipsize, 5510 ellipsisWidth); 5511 } else { 5512 mLayout = new StaticLayout(mTransformed, mTextPaint, 5513 w, alignment, mSpacingMult, mSpacingAdd, 5514 mIncludePad); 5515 } 5516 } else if (shouldEllipsize) { 5517 mLayout = new StaticLayout(mTransformed, 5518 0, mTransformed.length(), 5519 mTextPaint, w, alignment, mSpacingMult, 5520 mSpacingAdd, mIncludePad, mEllipsize, 5521 ellipsisWidth); 5522 } else { 5523 mLayout = new StaticLayout(mTransformed, mTextPaint, 5524 w, alignment, mSpacingMult, mSpacingAdd, 5525 mIncludePad); 5526 } 5527 } 5528 5529 shouldEllipsize = mEllipsize != null; 5530 mHintLayout = null; 5531 5532 if (mHint != null) { 5533 if (shouldEllipsize) hintWidth = w; 5534 5535 if (hintBoring == UNKNOWN_BORING) { 5536 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, 5537 mHintBoring); 5538 if (hintBoring != null) { 5539 mHintBoring = hintBoring; 5540 } 5541 } 5542 5543 if (hintBoring != null) { 5544 if (hintBoring.width <= hintWidth && 5545 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 5546 if (mSavedHintLayout != null) { 5547 mHintLayout = mSavedHintLayout. 5548 replaceOrMake(mHint, mTextPaint, 5549 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5550 hintBoring, mIncludePad); 5551 } else { 5552 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5553 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5554 hintBoring, mIncludePad); 5555 } 5556 5557 mSavedHintLayout = (BoringLayout) mHintLayout; 5558 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 5559 if (mSavedHintLayout != null) { 5560 mHintLayout = mSavedHintLayout. 5561 replaceOrMake(mHint, mTextPaint, 5562 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5563 hintBoring, mIncludePad, mEllipsize, 5564 ellipsisWidth); 5565 } else { 5566 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5567 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5568 hintBoring, mIncludePad, mEllipsize, 5569 ellipsisWidth); 5570 } 5571 } else if (shouldEllipsize) { 5572 mHintLayout = new StaticLayout(mHint, 5573 0, mHint.length(), 5574 mTextPaint, hintWidth, alignment, mSpacingMult, 5575 mSpacingAdd, mIncludePad, mEllipsize, 5576 ellipsisWidth); 5577 } else { 5578 mHintLayout = new StaticLayout(mHint, mTextPaint, 5579 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5580 mIncludePad); 5581 } 5582 } else if (shouldEllipsize) { 5583 mHintLayout = new StaticLayout(mHint, 5584 0, mHint.length(), 5585 mTextPaint, hintWidth, alignment, mSpacingMult, 5586 mSpacingAdd, mIncludePad, mEllipsize, 5587 ellipsisWidth); 5588 } else { 5589 mHintLayout = new StaticLayout(mHint, mTextPaint, 5590 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5591 mIncludePad); 5592 } 5593 } 5594 5595 if (bringIntoView) { 5596 registerForPreDraw(); 5597 } 5598 5599 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 5600 if (!compressText(ellipsisWidth)) { 5601 final int height = mLayoutParams.height; 5602 // If the size of the view does not depend on the size of the text, try to 5603 // start the marquee immediately 5604 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 5605 startMarquee(); 5606 } else { 5607 // Defer the start of the marquee until we know our width (see setFrame()) 5608 mRestartMarquee = true; 5609 } 5610 } 5611 } 5612 5613 // CursorControllers need a non-null mLayout 5614 prepareCursorControllers(); 5615 } 5616 5617 private boolean compressText(float width) { 5618 if (isHardwareAccelerated()) return false; 5619 5620 // Only compress the text if it hasn't been compressed by the previous pass 5621 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 5622 mTextPaint.getTextScaleX() == 1.0f) { 5623 final float textWidth = mLayout.getLineWidth(0); 5624 final float overflow = (textWidth + 1.0f - width) / width; 5625 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 5626 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 5627 post(new Runnable() { 5628 public void run() { 5629 requestLayout(); 5630 } 5631 }); 5632 return true; 5633 } 5634 } 5635 5636 return false; 5637 } 5638 5639 private static int desired(Layout layout) { 5640 int n = layout.getLineCount(); 5641 CharSequence text = layout.getText(); 5642 float max = 0; 5643 5644 // if any line was wrapped, we can't use it. 5645 // but it's ok for the last line not to have a newline 5646 5647 for (int i = 0; i < n - 1; i++) { 5648 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 5649 return -1; 5650 } 5651 5652 for (int i = 0; i < n; i++) { 5653 max = Math.max(max, layout.getLineWidth(i)); 5654 } 5655 5656 return (int) FloatMath.ceil(max); 5657 } 5658 5659 /** 5660 * Set whether the TextView includes extra top and bottom padding to make 5661 * room for accents that go above the normal ascent and descent. 5662 * The default is true. 5663 * 5664 * @attr ref android.R.styleable#TextView_includeFontPadding 5665 */ 5666 public void setIncludeFontPadding(boolean includepad) { 5667 mIncludePad = includepad; 5668 5669 if (mLayout != null) { 5670 nullLayouts(); 5671 requestLayout(); 5672 invalidate(); 5673 } 5674 } 5675 5676 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 5677 5678 @Override 5679 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5680 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5681 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5682 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5683 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5684 5685 int width; 5686 int height; 5687 5688 BoringLayout.Metrics boring = UNKNOWN_BORING; 5689 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 5690 5691 int des = -1; 5692 boolean fromexisting = false; 5693 5694 if (widthMode == MeasureSpec.EXACTLY) { 5695 // Parent has told us how big to be. So be it. 5696 width = widthSize; 5697 } else { 5698 if (mLayout != null && mEllipsize == null) { 5699 des = desired(mLayout); 5700 } 5701 5702 if (des < 0) { 5703 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring); 5704 if (boring != null) { 5705 mBoring = boring; 5706 } 5707 } else { 5708 fromexisting = true; 5709 } 5710 5711 if (boring == null || boring == UNKNOWN_BORING) { 5712 if (des < 0) { 5713 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 5714 } 5715 5716 width = des; 5717 } else { 5718 width = boring.width; 5719 } 5720 5721 final Drawables dr = mDrawables; 5722 if (dr != null) { 5723 width = Math.max(width, dr.mDrawableWidthTop); 5724 width = Math.max(width, dr.mDrawableWidthBottom); 5725 } 5726 5727 if (mHint != null) { 5728 int hintDes = -1; 5729 int hintWidth; 5730 5731 if (mHintLayout != null && mEllipsize == null) { 5732 hintDes = desired(mHintLayout); 5733 } 5734 5735 if (hintDes < 0) { 5736 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 5737 if (hintBoring != null) { 5738 mHintBoring = hintBoring; 5739 } 5740 } 5741 5742 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 5743 if (hintDes < 0) { 5744 hintDes = (int) FloatMath.ceil( 5745 Layout.getDesiredWidth(mHint, mTextPaint)); 5746 } 5747 5748 hintWidth = hintDes; 5749 } else { 5750 hintWidth = hintBoring.width; 5751 } 5752 5753 if (hintWidth > width) { 5754 width = hintWidth; 5755 } 5756 } 5757 5758 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 5759 5760 if (mMaxWidthMode == EMS) { 5761 width = Math.min(width, mMaxWidth * getLineHeight()); 5762 } else { 5763 width = Math.min(width, mMaxWidth); 5764 } 5765 5766 if (mMinWidthMode == EMS) { 5767 width = Math.max(width, mMinWidth * getLineHeight()); 5768 } else { 5769 width = Math.max(width, mMinWidth); 5770 } 5771 5772 // Check against our minimum width 5773 width = Math.max(width, getSuggestedMinimumWidth()); 5774 5775 if (widthMode == MeasureSpec.AT_MOST) { 5776 width = Math.min(widthSize, width); 5777 } 5778 } 5779 5780 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5781 int unpaddedWidth = want; 5782 5783 if (mHorizontallyScrolling) want = VERY_WIDE; 5784 5785 int hintWant = want; 5786 int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth(); 5787 5788 if (mLayout == null) { 5789 makeNewLayout(want, hintWant, boring, hintBoring, 5790 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5791 } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) || 5792 (mLayout.getEllipsizedWidth() != 5793 width - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 5794 if (mHint == null && mEllipsize == null && 5795 want > mLayout.getWidth() && 5796 (mLayout instanceof BoringLayout || 5797 (fromexisting && des >= 0 && des <= want))) { 5798 mLayout.increaseWidthTo(want); 5799 } else { 5800 makeNewLayout(want, hintWant, boring, hintBoring, 5801 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5802 } 5803 } else { 5804 // Width has not changed. 5805 } 5806 5807 if (heightMode == MeasureSpec.EXACTLY) { 5808 // Parent has told us how big to be. So be it. 5809 height = heightSize; 5810 mDesiredHeightAtMeasure = -1; 5811 } else { 5812 int desired = getDesiredHeight(); 5813 5814 height = desired; 5815 mDesiredHeightAtMeasure = desired; 5816 5817 if (heightMode == MeasureSpec.AT_MOST) { 5818 height = Math.min(desired, heightSize); 5819 } 5820 } 5821 5822 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 5823 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 5824 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 5825 } 5826 5827 /* 5828 * We didn't let makeNewLayout() register to bring the cursor into view, 5829 * so do it here if there is any possibility that it is needed. 5830 */ 5831 if (mMovement != null || 5832 mLayout.getWidth() > unpaddedWidth || 5833 mLayout.getHeight() > unpaddedHeight) { 5834 registerForPreDraw(); 5835 } else { 5836 scrollTo(0, 0); 5837 } 5838 5839 setMeasuredDimension(width, height); 5840 } 5841 5842 private int getDesiredHeight() { 5843 return Math.max( 5844 getDesiredHeight(mLayout, true), 5845 getDesiredHeight(mHintLayout, mEllipsize != null)); 5846 } 5847 5848 private int getDesiredHeight(Layout layout, boolean cap) { 5849 if (layout == null) { 5850 return 0; 5851 } 5852 5853 int linecount = layout.getLineCount(); 5854 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 5855 int desired = layout.getLineTop(linecount); 5856 5857 final Drawables dr = mDrawables; 5858 if (dr != null) { 5859 desired = Math.max(desired, dr.mDrawableHeightLeft); 5860 desired = Math.max(desired, dr.mDrawableHeightRight); 5861 } 5862 5863 desired += pad; 5864 5865 if (mMaxMode == LINES) { 5866 /* 5867 * Don't cap the hint to a certain number of lines. 5868 * (Do cap it, though, if we have a maximum pixel height.) 5869 */ 5870 if (cap) { 5871 if (linecount > mMaximum) { 5872 desired = layout.getLineTop(mMaximum) + 5873 layout.getBottomPadding(); 5874 5875 if (dr != null) { 5876 desired = Math.max(desired, dr.mDrawableHeightLeft); 5877 desired = Math.max(desired, dr.mDrawableHeightRight); 5878 } 5879 5880 desired += pad; 5881 linecount = mMaximum; 5882 } 5883 } 5884 } else { 5885 desired = Math.min(desired, mMaximum); 5886 } 5887 5888 if (mMinMode == LINES) { 5889 if (linecount < mMinimum) { 5890 desired += getLineHeight() * (mMinimum - linecount); 5891 } 5892 } else { 5893 desired = Math.max(desired, mMinimum); 5894 } 5895 5896 // Check against our minimum height 5897 desired = Math.max(desired, getSuggestedMinimumHeight()); 5898 5899 return desired; 5900 } 5901 5902 /** 5903 * Check whether a change to the existing text layout requires a 5904 * new view layout. 5905 */ 5906 private void checkForResize() { 5907 boolean sizeChanged = false; 5908 5909 if (mLayout != null) { 5910 // Check if our width changed 5911 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 5912 sizeChanged = true; 5913 invalidate(); 5914 } 5915 5916 // Check if our height changed 5917 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 5918 int desiredHeight = getDesiredHeight(); 5919 5920 if (desiredHeight != this.getHeight()) { 5921 sizeChanged = true; 5922 } 5923 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 5924 if (mDesiredHeightAtMeasure >= 0) { 5925 int desiredHeight = getDesiredHeight(); 5926 5927 if (desiredHeight != mDesiredHeightAtMeasure) { 5928 sizeChanged = true; 5929 } 5930 } 5931 } 5932 } 5933 5934 if (sizeChanged) { 5935 requestLayout(); 5936 // caller will have already invalidated 5937 } 5938 } 5939 5940 /** 5941 * Check whether entirely new text requires a new view layout 5942 * or merely a new text layout. 5943 */ 5944 private void checkForRelayout() { 5945 // If we have a fixed width, we can just swap in a new text layout 5946 // if the text height stays the same or if the view height is fixed. 5947 5948 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 5949 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 5950 (mHint == null || mHintLayout != null) && 5951 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 5952 // Static width, so try making a new text layout. 5953 5954 int oldht = mLayout.getHeight(); 5955 int want = mLayout.getWidth(); 5956 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 5957 5958 /* 5959 * No need to bring the text into view, since the size is not 5960 * changing (unless we do the requestLayout(), in which case it 5961 * will happen at measure). 5962 */ 5963 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 5964 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 5965 false); 5966 5967 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 5968 // In a fixed-height view, so use our new text layout. 5969 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 5970 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 5971 invalidate(); 5972 return; 5973 } 5974 5975 // Dynamic height, but height has stayed the same, 5976 // so use our new text layout. 5977 if (mLayout.getHeight() == oldht && 5978 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 5979 invalidate(); 5980 return; 5981 } 5982 } 5983 5984 // We lose: the height has changed and we have a dynamic height. 5985 // Request a new view layout using our new text layout. 5986 requestLayout(); 5987 invalidate(); 5988 } else { 5989 // Dynamic width, so we have no choice but to request a new 5990 // view layout with a new text layout. 5991 5992 nullLayouts(); 5993 requestLayout(); 5994 invalidate(); 5995 } 5996 } 5997 5998 /** 5999 * Returns true if anything changed. 6000 */ 6001 private boolean bringTextIntoView() { 6002 int line = 0; 6003 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6004 line = mLayout.getLineCount() - 1; 6005 } 6006 6007 Layout.Alignment a = mLayout.getParagraphAlignment(line); 6008 int dir = mLayout.getParagraphDirection(line); 6009 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6010 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6011 int ht = mLayout.getHeight(); 6012 6013 int scrollx, scrolly; 6014 6015 if (a == Layout.Alignment.ALIGN_CENTER) { 6016 /* 6017 * Keep centered if possible, or, if it is too wide to fit, 6018 * keep leading edge in view. 6019 */ 6020 6021 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6022 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6023 6024 if (right - left < hspace) { 6025 scrollx = (right + left) / 2 - hspace / 2; 6026 } else { 6027 if (dir < 0) { 6028 scrollx = right - hspace; 6029 } else { 6030 scrollx = left; 6031 } 6032 } 6033 } else if (a == Layout.Alignment.ALIGN_NORMAL) { 6034 /* 6035 * Keep leading edge in view. 6036 */ 6037 6038 if (dir < 0) { 6039 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6040 scrollx = right - hspace; 6041 } else { 6042 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6043 } 6044 } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ { 6045 /* 6046 * Keep trailing edge in view. 6047 */ 6048 6049 if (dir < 0) { 6050 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6051 } else { 6052 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6053 scrollx = right - hspace; 6054 } 6055 } 6056 6057 if (ht < vspace) { 6058 scrolly = 0; 6059 } else { 6060 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6061 scrolly = ht - vspace; 6062 } else { 6063 scrolly = 0; 6064 } 6065 } 6066 6067 if (scrollx != mScrollX || scrolly != mScrollY) { 6068 scrollTo(scrollx, scrolly); 6069 return true; 6070 } else { 6071 return false; 6072 } 6073 } 6074 6075 /** 6076 * Move the point, specified by the offset, into the view if it is needed. 6077 * This has to be called after layout. Returns true if anything changed. 6078 */ 6079 public boolean bringPointIntoView(int offset) { 6080 boolean changed = false; 6081 6082 int line = mLayout.getLineForOffset(offset); 6083 6084 // FIXME: Is it okay to truncate this, or should we round? 6085 final int x = (int)mLayout.getPrimaryHorizontal(offset); 6086 final int top = mLayout.getLineTop(line); 6087 final int bottom = mLayout.getLineTop(line + 1); 6088 6089 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6090 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6091 int ht = mLayout.getHeight(); 6092 6093 int grav; 6094 6095 switch (mLayout.getParagraphAlignment(line)) { 6096 case ALIGN_NORMAL: 6097 grav = 1; 6098 break; 6099 6100 case ALIGN_OPPOSITE: 6101 grav = -1; 6102 break; 6103 6104 default: 6105 grav = 0; 6106 } 6107 6108 grav *= mLayout.getParagraphDirection(line); 6109 6110 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6111 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6112 6113 int hslack = (bottom - top) / 2; 6114 int vslack = hslack; 6115 6116 if (vslack > vspace / 4) 6117 vslack = vspace / 4; 6118 if (hslack > hspace / 4) 6119 hslack = hspace / 4; 6120 6121 int hs = mScrollX; 6122 int vs = mScrollY; 6123 6124 if (top - vs < vslack) 6125 vs = top - vslack; 6126 if (bottom - vs > vspace - vslack) 6127 vs = bottom - (vspace - vslack); 6128 if (ht - vs < vspace) 6129 vs = ht - vspace; 6130 if (0 - vs > 0) 6131 vs = 0; 6132 6133 if (grav != 0) { 6134 if (x - hs < hslack) { 6135 hs = x - hslack; 6136 } 6137 if (x - hs > hspace - hslack) { 6138 hs = x - (hspace - hslack); 6139 } 6140 } 6141 6142 if (grav < 0) { 6143 if (left - hs > 0) 6144 hs = left; 6145 if (right - hs < hspace) 6146 hs = right - hspace; 6147 } else if (grav > 0) { 6148 if (right - hs < hspace) 6149 hs = right - hspace; 6150 if (left - hs > 0) 6151 hs = left; 6152 } else /* grav == 0 */ { 6153 if (right - left <= hspace) { 6154 /* 6155 * If the entire text fits, center it exactly. 6156 */ 6157 hs = left - (hspace - (right - left)) / 2; 6158 } else if (x > right - hslack) { 6159 /* 6160 * If we are near the right edge, keep the right edge 6161 * at the edge of the view. 6162 */ 6163 hs = right - hspace; 6164 } else if (x < left + hslack) { 6165 /* 6166 * If we are near the left edge, keep the left edge 6167 * at the edge of the view. 6168 */ 6169 hs = left; 6170 } else if (left > hs) { 6171 /* 6172 * Is there whitespace visible at the left? Fix it if so. 6173 */ 6174 hs = left; 6175 } else if (right < hs + hspace) { 6176 /* 6177 * Is there whitespace visible at the right? Fix it if so. 6178 */ 6179 hs = right - hspace; 6180 } else { 6181 /* 6182 * Otherwise, float as needed. 6183 */ 6184 if (x - hs < hslack) { 6185 hs = x - hslack; 6186 } 6187 if (x - hs > hspace - hslack) { 6188 hs = x - (hspace - hslack); 6189 } 6190 } 6191 } 6192 6193 if (hs != mScrollX || vs != mScrollY) { 6194 if (mScroller == null) { 6195 scrollTo(hs, vs); 6196 } else { 6197 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6198 int dx = hs - mScrollX; 6199 int dy = vs - mScrollY; 6200 6201 if (duration > ANIMATED_SCROLL_GAP) { 6202 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6203 awakenScrollBars(mScroller.getDuration()); 6204 invalidate(); 6205 } else { 6206 if (!mScroller.isFinished()) { 6207 mScroller.abortAnimation(); 6208 } 6209 6210 scrollBy(dx, dy); 6211 } 6212 6213 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6214 } 6215 6216 changed = true; 6217 } 6218 6219 if (isFocused()) { 6220 // This offsets because getInterestingRect() is in terms of 6221 // viewport coordinates, but requestRectangleOnScreen() 6222 // is in terms of content coordinates. 6223 6224 Rect r = new Rect(x, top, x + 1, bottom); 6225 getInterestingRect(r, line); 6226 r.offset(mScrollX, mScrollY); 6227 6228 if (requestRectangleOnScreen(r)) { 6229 changed = true; 6230 } 6231 } 6232 6233 return changed; 6234 } 6235 6236 /** 6237 * Move the cursor, if needed, so that it is at an offset that is visible 6238 * to the user. This will not move the cursor if it represents more than 6239 * one character (a selection range). This will only work if the 6240 * TextView contains spannable text; otherwise it will do nothing. 6241 * 6242 * @return True if the cursor was actually moved, false otherwise. 6243 */ 6244 public boolean moveCursorToVisibleOffset() { 6245 if (!(mText instanceof Spannable)) { 6246 return false; 6247 } 6248 int start = getSelectionStart(); 6249 int end = getSelectionEnd(); 6250 if (start != end) { 6251 return false; 6252 } 6253 6254 // First: make sure the line is visible on screen: 6255 6256 int line = mLayout.getLineForOffset(start); 6257 6258 final int top = mLayout.getLineTop(line); 6259 final int bottom = mLayout.getLineTop(line + 1); 6260 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6261 int vslack = (bottom - top) / 2; 6262 if (vslack > vspace / 4) 6263 vslack = vspace / 4; 6264 final int vs = mScrollY; 6265 6266 if (top < (vs+vslack)) { 6267 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 6268 } else if (bottom > (vspace+vs-vslack)) { 6269 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 6270 } 6271 6272 // Next: make sure the character is visible on screen: 6273 6274 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6275 final int hs = mScrollX; 6276 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 6277 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 6278 6279 // line might contain bidirectional text 6280 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 6281 final int highChar = leftChar > rightChar ? leftChar : rightChar; 6282 6283 int newStart = start; 6284 if (newStart < lowChar) { 6285 newStart = lowChar; 6286 } else if (newStart > highChar) { 6287 newStart = highChar; 6288 } 6289 6290 if (newStart != start) { 6291 Selection.setSelection((Spannable)mText, newStart); 6292 return true; 6293 } 6294 6295 return false; 6296 } 6297 6298 @Override 6299 public void computeScroll() { 6300 if (mScroller != null) { 6301 if (mScroller.computeScrollOffset()) { 6302 mScrollX = mScroller.getCurrX(); 6303 mScrollY = mScroller.getCurrY(); 6304 invalidateParentCaches(); 6305 postInvalidate(); // So we draw again 6306 } 6307 } 6308 } 6309 6310 private void getInterestingRect(Rect r, int line) { 6311 convertFromViewportToContentCoordinates(r); 6312 6313 // Rectangle can can be expanded on first and last line to take 6314 // padding into account. 6315 // TODO Take left/right padding into account too? 6316 if (line == 0) r.top -= getExtendedPaddingTop(); 6317 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 6318 } 6319 6320 private void convertFromViewportToContentCoordinates(Rect r) { 6321 final int horizontalOffset = viewportToContentHorizontalOffset(); 6322 r.left += horizontalOffset; 6323 r.right += horizontalOffset; 6324 6325 final int verticalOffset = viewportToContentVerticalOffset(); 6326 r.top += verticalOffset; 6327 r.bottom += verticalOffset; 6328 } 6329 6330 private int viewportToContentHorizontalOffset() { 6331 return getCompoundPaddingLeft() - mScrollX; 6332 } 6333 6334 private int viewportToContentVerticalOffset() { 6335 int offset = getExtendedPaddingTop() - mScrollY; 6336 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 6337 offset += getVerticalOffset(false); 6338 } 6339 return offset; 6340 } 6341 6342 @Override 6343 public void debug(int depth) { 6344 super.debug(depth); 6345 6346 String output = debugIndent(depth); 6347 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 6348 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 6349 + "} "; 6350 6351 if (mText != null) { 6352 6353 output += "mText=\"" + mText + "\" "; 6354 if (mLayout != null) { 6355 output += "mLayout width=" + mLayout.getWidth() 6356 + " height=" + mLayout.getHeight(); 6357 } 6358 } else { 6359 output += "mText=NULL"; 6360 } 6361 Log.d(VIEW_LOG_TAG, output); 6362 } 6363 6364 /** 6365 * Convenience for {@link Selection#getSelectionStart}. 6366 */ 6367 @ViewDebug.ExportedProperty(category = "text") 6368 public int getSelectionStart() { 6369 return Selection.getSelectionStart(getText()); 6370 } 6371 6372 /** 6373 * Convenience for {@link Selection#getSelectionEnd}. 6374 */ 6375 @ViewDebug.ExportedProperty(category = "text") 6376 public int getSelectionEnd() { 6377 return Selection.getSelectionEnd(getText()); 6378 } 6379 6380 /** 6381 * Return true iff there is a selection inside this text view. 6382 */ 6383 public boolean hasSelection() { 6384 final int selectionStart = getSelectionStart(); 6385 final int selectionEnd = getSelectionEnd(); 6386 6387 return selectionStart >= 0 && selectionStart != selectionEnd; 6388 } 6389 6390 /** 6391 * Sets the properties of this field (lines, horizontally scrolling, 6392 * transformation method) to be for a single-line input. 6393 * 6394 * @attr ref android.R.styleable#TextView_singleLine 6395 */ 6396 public void setSingleLine() { 6397 setSingleLine(true); 6398 } 6399 6400 /** 6401 * If true, sets the properties of this field (number of lines, horizontally scrolling, 6402 * transformation method) to be for a single-line input; if false, restores these to the default 6403 * conditions. 6404 * 6405 * Note that the default conditions are not necessarily those that were in effect prior this 6406 * method, and you may want to reset these properties to your custom values. 6407 * 6408 * @attr ref android.R.styleable#TextView_singleLine 6409 */ 6410 @android.view.RemotableViewMethod 6411 public void setSingleLine(boolean singleLine) { 6412 // Could be used, but may break backward compatibility. 6413 // if (mSingleLine == singleLine) return; 6414 setInputTypeSingleLine(singleLine); 6415 applySingleLine(singleLine, true, true); 6416 } 6417 6418 /** 6419 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 6420 * @param singleLine 6421 */ 6422 private void setInputTypeSingleLine(boolean singleLine) { 6423 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 6424 if (singleLine) { 6425 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 6426 } else { 6427 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 6428 } 6429 } 6430 } 6431 6432 private void applySingleLine(boolean singleLine, boolean applyTransformation, 6433 boolean changeMaxLines) { 6434 mSingleLine = singleLine; 6435 if (singleLine) { 6436 setLines(1); 6437 setHorizontallyScrolling(true); 6438 if (applyTransformation) { 6439 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 6440 } 6441 // TODO setState 6442 } else { 6443 if (changeMaxLines) { 6444 setMaxLines(Integer.MAX_VALUE); 6445 } 6446 setHorizontallyScrolling(false); 6447 if (applyTransformation) { 6448 setTransformationMethod(null); 6449 } 6450 // TODO setState 6451 } 6452 } 6453 6454 /** 6455 * Causes words in the text that are longer than the view is wide 6456 * to be ellipsized instead of broken in the middle. You may also 6457 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 6458 * to constrain the text to a single line. Use <code>null</code> 6459 * to turn off ellipsizing. 6460 * 6461 * @attr ref android.R.styleable#TextView_ellipsize 6462 */ 6463 public void setEllipsize(TextUtils.TruncateAt where) { 6464 mEllipsize = where; 6465 6466 if (mLayout != null) { 6467 nullLayouts(); 6468 requestLayout(); 6469 invalidate(); 6470 } 6471 } 6472 6473 /** 6474 * Sets how many times to repeat the marquee animation. Only applied if the 6475 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 6476 * 6477 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 6478 */ 6479 public void setMarqueeRepeatLimit(int marqueeLimit) { 6480 mMarqueeRepeatLimit = marqueeLimit; 6481 } 6482 6483 /** 6484 * Returns where, if anywhere, words that are longer than the view 6485 * is wide should be ellipsized. 6486 */ 6487 @ViewDebug.ExportedProperty 6488 public TextUtils.TruncateAt getEllipsize() { 6489 return mEllipsize; 6490 } 6491 6492 /** 6493 * Set the TextView so that when it takes focus, all the text is 6494 * selected. 6495 * 6496 * @attr ref android.R.styleable#TextView_selectAllOnFocus 6497 */ 6498 @android.view.RemotableViewMethod 6499 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 6500 mSelectAllOnFocus = selectAllOnFocus; 6501 6502 if (selectAllOnFocus && !(mText instanceof Spannable)) { 6503 setText(mText, BufferType.SPANNABLE); 6504 } 6505 } 6506 6507 /** 6508 * Set whether the cursor is visible. The default is true. 6509 * 6510 * @attr ref android.R.styleable#TextView_cursorVisible 6511 */ 6512 @android.view.RemotableViewMethod 6513 public void setCursorVisible(boolean visible) { 6514 mCursorVisible = visible; 6515 invalidate(); 6516 6517 makeBlink(); 6518 6519 // InsertionPointCursorController depends on mCursorVisible 6520 prepareCursorControllers(); 6521 } 6522 6523 private boolean isCursorVisible() { 6524 return mCursorVisible && isTextEditable(); 6525 } 6526 6527 private boolean canMarquee() { 6528 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 6529 return width > 0 && mLayout.getLineWidth(0) > width; 6530 } 6531 6532 private void startMarquee() { 6533 // Do not ellipsize EditText 6534 if (mInput != null) return; 6535 6536 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 6537 return; 6538 } 6539 6540 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 6541 getLineCount() == 1 && canMarquee()) { 6542 6543 if (mMarquee == null) mMarquee = new Marquee(this); 6544 mMarquee.start(mMarqueeRepeatLimit); 6545 } 6546 } 6547 6548 private void stopMarquee() { 6549 if (mMarquee != null && !mMarquee.isStopped()) { 6550 mMarquee.stop(); 6551 } 6552 } 6553 6554 private void startStopMarquee(boolean start) { 6555 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6556 if (start) { 6557 startMarquee(); 6558 } else { 6559 stopMarquee(); 6560 } 6561 } 6562 } 6563 6564 private static final class Marquee extends Handler { 6565 // TODO: Add an option to configure this 6566 private static final float MARQUEE_DELTA_MAX = 0.07f; 6567 private static final int MARQUEE_DELAY = 1200; 6568 private static final int MARQUEE_RESTART_DELAY = 1200; 6569 private static final int MARQUEE_RESOLUTION = 1000 / 30; 6570 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 6571 6572 private static final byte MARQUEE_STOPPED = 0x0; 6573 private static final byte MARQUEE_STARTING = 0x1; 6574 private static final byte MARQUEE_RUNNING = 0x2; 6575 6576 private static final int MESSAGE_START = 0x1; 6577 private static final int MESSAGE_TICK = 0x2; 6578 private static final int MESSAGE_RESTART = 0x3; 6579 6580 private final WeakReference<TextView> mView; 6581 6582 private byte mStatus = MARQUEE_STOPPED; 6583 private final float mScrollUnit; 6584 private float mMaxScroll; 6585 float mMaxFadeScroll; 6586 private float mGhostStart; 6587 private float mGhostOffset; 6588 private float mFadeStop; 6589 private int mRepeatLimit; 6590 6591 float mScroll; 6592 6593 Marquee(TextView v) { 6594 final float density = v.getContext().getResources().getDisplayMetrics().density; 6595 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 6596 mView = new WeakReference<TextView>(v); 6597 } 6598 6599 @Override 6600 public void handleMessage(Message msg) { 6601 switch (msg.what) { 6602 case MESSAGE_START: 6603 mStatus = MARQUEE_RUNNING; 6604 tick(); 6605 break; 6606 case MESSAGE_TICK: 6607 tick(); 6608 break; 6609 case MESSAGE_RESTART: 6610 if (mStatus == MARQUEE_RUNNING) { 6611 if (mRepeatLimit >= 0) { 6612 mRepeatLimit--; 6613 } 6614 start(mRepeatLimit); 6615 } 6616 break; 6617 } 6618 } 6619 6620 void tick() { 6621 if (mStatus != MARQUEE_RUNNING) { 6622 return; 6623 } 6624 6625 removeMessages(MESSAGE_TICK); 6626 6627 final TextView textView = mView.get(); 6628 if (textView != null && (textView.isFocused() || textView.isSelected())) { 6629 mScroll += mScrollUnit; 6630 if (mScroll > mMaxScroll) { 6631 mScroll = mMaxScroll; 6632 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 6633 } else { 6634 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 6635 } 6636 textView.invalidate(); 6637 } 6638 } 6639 6640 void stop() { 6641 mStatus = MARQUEE_STOPPED; 6642 removeMessages(MESSAGE_START); 6643 removeMessages(MESSAGE_RESTART); 6644 removeMessages(MESSAGE_TICK); 6645 resetScroll(); 6646 } 6647 6648 private void resetScroll() { 6649 mScroll = 0.0f; 6650 final TextView textView = mView.get(); 6651 if (textView != null) textView.invalidate(); 6652 } 6653 6654 void start(int repeatLimit) { 6655 if (repeatLimit == 0) { 6656 stop(); 6657 return; 6658 } 6659 mRepeatLimit = repeatLimit; 6660 final TextView textView = mView.get(); 6661 if (textView != null && textView.mLayout != null) { 6662 mStatus = MARQUEE_STARTING; 6663 mScroll = 0.0f; 6664 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 6665 textView.getCompoundPaddingRight(); 6666 final float lineWidth = textView.mLayout.getLineWidth(0); 6667 final float gap = textWidth / 3.0f; 6668 mGhostStart = lineWidth - textWidth + gap; 6669 mMaxScroll = mGhostStart + textWidth; 6670 mGhostOffset = lineWidth + gap; 6671 mFadeStop = lineWidth + textWidth / 6.0f; 6672 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 6673 6674 textView.invalidate(); 6675 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 6676 } 6677 } 6678 6679 float getGhostOffset() { 6680 return mGhostOffset; 6681 } 6682 6683 boolean shouldDrawLeftFade() { 6684 return mScroll <= mFadeStop; 6685 } 6686 6687 boolean shouldDrawGhost() { 6688 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 6689 } 6690 6691 boolean isRunning() { 6692 return mStatus == MARQUEE_RUNNING; 6693 } 6694 6695 boolean isStopped() { 6696 return mStatus == MARQUEE_STOPPED; 6697 } 6698 } 6699 6700 /** 6701 * This method is called when the text is changed, in case any 6702 * subclasses would like to know. 6703 * 6704 * @param text The text the TextView is displaying. 6705 * @param start The offset of the start of the range of the text 6706 * that was modified. 6707 * @param before The offset of the former end of the range of the 6708 * text that was modified. If text was simply inserted, 6709 * this will be the same as <code>start</code>. 6710 * If text was replaced with new text or deleted, the 6711 * length of the old text was <code>before-start</code>. 6712 * @param after The offset of the end of the range of the text 6713 * that was modified. If text was simply deleted, 6714 * this will be the same as <code>start</code>. 6715 * If text was replaced with new text or inserted, 6716 * the length of the new text is <code>after-start</code>. 6717 */ 6718 protected void onTextChanged(CharSequence text, 6719 int start, int before, int after) { 6720 } 6721 6722 /** 6723 * This method is called when the selection has changed, in case any 6724 * subclasses would like to know. 6725 * 6726 * @param selStart The new selection start location. 6727 * @param selEnd The new selection end location. 6728 */ 6729 protected void onSelectionChanged(int selStart, int selEnd) { 6730 } 6731 6732 /** 6733 * Adds a TextWatcher to the list of those whose methods are called 6734 * whenever this TextView's text changes. 6735 * <p> 6736 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 6737 * not called after {@link #setText} calls. Now, doing {@link #setText} 6738 * if there are any text changed listeners forces the buffer type to 6739 * Editable if it would not otherwise be and does call this method. 6740 */ 6741 public void addTextChangedListener(TextWatcher watcher) { 6742 if (mListeners == null) { 6743 mListeners = new ArrayList<TextWatcher>(); 6744 } 6745 6746 mListeners.add(watcher); 6747 } 6748 6749 /** 6750 * Removes the specified TextWatcher from the list of those whose 6751 * methods are called 6752 * whenever this TextView's text changes. 6753 */ 6754 public void removeTextChangedListener(TextWatcher watcher) { 6755 if (mListeners != null) { 6756 int i = mListeners.indexOf(watcher); 6757 6758 if (i >= 0) { 6759 mListeners.remove(i); 6760 } 6761 } 6762 } 6763 6764 private void sendBeforeTextChanged(CharSequence text, int start, int before, 6765 int after) { 6766 if (mListeners != null) { 6767 final ArrayList<TextWatcher> list = mListeners; 6768 final int count = list.size(); 6769 for (int i = 0; i < count; i++) { 6770 list.get(i).beforeTextChanged(text, start, before, after); 6771 } 6772 } 6773 } 6774 6775 /** 6776 * Not private so it can be called from an inner class without going 6777 * through a thunk. 6778 */ 6779 void sendOnTextChanged(CharSequence text, int start, int before, 6780 int after) { 6781 if (mListeners != null) { 6782 final ArrayList<TextWatcher> list = mListeners; 6783 final int count = list.size(); 6784 for (int i = 0; i < count; i++) { 6785 list.get(i).onTextChanged(text, start, before, after); 6786 } 6787 } 6788 } 6789 6790 /** 6791 * Not private so it can be called from an inner class without going 6792 * through a thunk. 6793 */ 6794 void sendAfterTextChanged(Editable text) { 6795 if (mListeners != null) { 6796 final ArrayList<TextWatcher> list = mListeners; 6797 final int count = list.size(); 6798 for (int i = 0; i < count; i++) { 6799 list.get(i).afterTextChanged(text); 6800 } 6801 } 6802 } 6803 6804 /** 6805 * Not private so it can be called from an inner class without going 6806 * through a thunk. 6807 */ 6808 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 6809 final InputMethodState ims = mInputMethodState; 6810 if (ims == null || ims.mBatchEditNesting == 0) { 6811 updateAfterEdit(); 6812 } 6813 if (ims != null) { 6814 ims.mContentChanged = true; 6815 if (ims.mChangedStart < 0) { 6816 ims.mChangedStart = start; 6817 ims.mChangedEnd = start+before; 6818 } else { 6819 ims.mChangedStart = Math.min(ims.mChangedStart, start); 6820 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 6821 } 6822 ims.mChangedDelta += after-before; 6823 } 6824 6825 sendOnTextChanged(buffer, start, before, after); 6826 onTextChanged(buffer, start, before, after); 6827 6828 // Hide the controllers if the amount of content changed 6829 if (before != after) { 6830 hideControllers(); 6831 } 6832 } 6833 6834 /** 6835 * Not private so it can be called from an inner class without going 6836 * through a thunk. 6837 */ 6838 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 6839 // XXX Make the start and end move together if this ends up 6840 // spending too much time invalidating. 6841 6842 boolean selChanged = false; 6843 int newSelStart=-1, newSelEnd=-1; 6844 6845 final InputMethodState ims = mInputMethodState; 6846 6847 if (what == Selection.SELECTION_END) { 6848 mHighlightPathBogus = true; 6849 selChanged = true; 6850 newSelEnd = newStart; 6851 6852 if (!isFocused()) { 6853 mSelectionMoved = true; 6854 } 6855 6856 if (oldStart >= 0 || newStart >= 0) { 6857 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 6858 registerForPreDraw(); 6859 6860 if (isFocused()) { 6861 mShowCursor = SystemClock.uptimeMillis(); 6862 makeBlink(); 6863 } 6864 } 6865 } 6866 6867 if (what == Selection.SELECTION_START) { 6868 mHighlightPathBogus = true; 6869 selChanged = true; 6870 newSelStart = newStart; 6871 6872 if (!isFocused()) { 6873 mSelectionMoved = true; 6874 } 6875 6876 if (oldStart >= 0 || newStart >= 0) { 6877 int end = Selection.getSelectionEnd(buf); 6878 invalidateCursor(end, oldStart, newStart); 6879 } 6880 } 6881 6882 if (selChanged) { 6883 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 6884 if (newSelStart < 0) { 6885 newSelStart = Selection.getSelectionStart(buf); 6886 } 6887 if (newSelEnd < 0) { 6888 newSelEnd = Selection.getSelectionEnd(buf); 6889 } 6890 onSelectionChanged(newSelStart, newSelEnd); 6891 } 6892 } 6893 6894 if (what instanceof UpdateAppearance || 6895 what instanceof ParagraphStyle) { 6896 if (ims == null || ims.mBatchEditNesting == 0) { 6897 invalidate(); 6898 mHighlightPathBogus = true; 6899 checkForResize(); 6900 } else { 6901 ims.mContentChanged = true; 6902 } 6903 } 6904 6905 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 6906 mHighlightPathBogus = true; 6907 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 6908 ims.mSelectionModeChanged = true; 6909 } 6910 6911 if (Selection.getSelectionStart(buf) >= 0) { 6912 if (ims == null || ims.mBatchEditNesting == 0) { 6913 invalidateCursor(); 6914 } else { 6915 ims.mCursorChanged = true; 6916 } 6917 } 6918 } 6919 6920 if (what instanceof ParcelableSpan) { 6921 // If this is a span that can be sent to a remote process, 6922 // the current extract editor would be interested in it. 6923 if (ims != null && ims.mExtracting != null) { 6924 if (ims.mBatchEditNesting != 0) { 6925 if (oldStart >= 0) { 6926 if (ims.mChangedStart > oldStart) { 6927 ims.mChangedStart = oldStart; 6928 } 6929 if (ims.mChangedStart > oldEnd) { 6930 ims.mChangedStart = oldEnd; 6931 } 6932 } 6933 if (newStart >= 0) { 6934 if (ims.mChangedStart > newStart) { 6935 ims.mChangedStart = newStart; 6936 } 6937 if (ims.mChangedStart > newEnd) { 6938 ims.mChangedStart = newEnd; 6939 } 6940 } 6941 } else { 6942 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 6943 + oldStart + "-" + oldEnd + "," 6944 + newStart + "-" + newEnd + what); 6945 ims.mContentChanged = true; 6946 } 6947 } 6948 } 6949 } 6950 6951 private class ChangeWatcher 6952 implements TextWatcher, SpanWatcher { 6953 6954 private CharSequence mBeforeText; 6955 6956 public void beforeTextChanged(CharSequence buffer, int start, 6957 int before, int after) { 6958 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 6959 + " before=" + before + " after=" + after + ": " + buffer); 6960 6961 if (AccessibilityManager.getInstance(mContext).isEnabled() 6962 && !isPasswordInputType(mInputType) 6963 && !hasPasswordTransformationMethod()) { 6964 mBeforeText = buffer.toString(); 6965 } 6966 6967 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 6968 } 6969 6970 public void onTextChanged(CharSequence buffer, int start, 6971 int before, int after) { 6972 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 6973 + " before=" + before + " after=" + after + ": " + buffer); 6974 TextView.this.handleTextChanged(buffer, start, before, after); 6975 6976 if (AccessibilityManager.getInstance(mContext).isEnabled() && 6977 (isFocused() || isSelected() && 6978 isShown())) { 6979 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 6980 mBeforeText = null; 6981 } 6982 } 6983 6984 public void afterTextChanged(Editable buffer) { 6985 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 6986 TextView.this.sendAfterTextChanged(buffer); 6987 6988 if (MetaKeyKeyListener.getMetaState(buffer, 6989 MetaKeyKeyListener.META_SELECTING) != 0) { 6990 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 6991 } 6992 } 6993 6994 public void onSpanChanged(Spannable buf, 6995 Object what, int s, int e, int st, int en) { 6996 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 6997 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 6998 TextView.this.spanChange(buf, what, s, st, e, en); 6999 } 7000 7001 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 7002 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 7003 + " what=" + what + ": " + buf); 7004 TextView.this.spanChange(buf, what, -1, s, -1, e); 7005 } 7006 7007 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 7008 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 7009 + " what=" + what + ": " + buf); 7010 TextView.this.spanChange(buf, what, s, -1, e, -1); 7011 } 7012 } 7013 7014 private void makeBlink() { 7015 if (!isCursorVisible()) { 7016 if (mBlink != null) { 7017 mBlink.removeCallbacks(mBlink); 7018 } 7019 7020 return; 7021 } 7022 7023 if (mBlink == null) 7024 mBlink = new Blink(this); 7025 7026 mBlink.removeCallbacks(mBlink); 7027 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 7028 } 7029 7030 /** 7031 * @hide 7032 */ 7033 @Override 7034 public void dispatchFinishTemporaryDetach() { 7035 mDispatchTemporaryDetach = true; 7036 super.dispatchFinishTemporaryDetach(); 7037 mDispatchTemporaryDetach = false; 7038 } 7039 7040 @Override 7041 public void onStartTemporaryDetach() { 7042 super.onStartTemporaryDetach(); 7043 // Only track when onStartTemporaryDetach() is called directly, 7044 // usually because this instance is an editable field in a list 7045 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 7046 } 7047 7048 @Override 7049 public void onFinishTemporaryDetach() { 7050 super.onFinishTemporaryDetach(); 7051 // Only track when onStartTemporaryDetach() is called directly, 7052 // usually because this instance is an editable field in a list 7053 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 7054 } 7055 7056 @Override 7057 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 7058 if (mTemporaryDetach) { 7059 // If we are temporarily in the detach state, then do nothing. 7060 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7061 return; 7062 } 7063 7064 mShowCursor = SystemClock.uptimeMillis(); 7065 7066 ensureEndedBatchEdit(); 7067 7068 if (focused) { 7069 int selStart = getSelectionStart(); 7070 int selEnd = getSelectionEnd(); 7071 7072 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 7073 // mode for these, unless there was a specific selection already started. 7074 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 7075 selEnd == mText.length(); 7076 mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted; 7077 7078 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 7079 // If a tap was used to give focus to that view, move cursor at tap position. 7080 // Has to be done before onTakeFocus, which can be overloaded. 7081 final int lastTapPosition = getLastTapPosition(); 7082 if (lastTapPosition >= 0) { 7083 Selection.setSelection((Spannable) mText, lastTapPosition); 7084 } 7085 7086 if (mMovement != null) { 7087 mMovement.onTakeFocus(this, (Spannable) mText, direction); 7088 } 7089 7090 // The DecorView does not have focus when the 'Done' ExtractEditText button is 7091 // pressed. Since it is the ViewRoot's mView, it requests focus before 7092 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 7093 // This special case ensure that we keep current selection in that case. 7094 // It would be better to know why the DecorView does not have focus at that time. 7095 if (((this instanceof ExtractEditText) || mSelectionMoved) && 7096 selStart >= 0 && selEnd >= 0) { 7097 /* 7098 * Someone intentionally set the selection, so let them 7099 * do whatever it is that they wanted to do instead of 7100 * the default on-focus behavior. We reset the selection 7101 * here instead of just skipping the onTakeFocus() call 7102 * because some movement methods do something other than 7103 * just setting the selection in theirs and we still 7104 * need to go through that path. 7105 */ 7106 Selection.setSelection((Spannable) mText, selStart, selEnd); 7107 } 7108 7109 if (mSelectAllOnFocus) { 7110 selectAll(); 7111 } 7112 7113 mTouchFocusSelected = true; 7114 } 7115 7116 mFrozenWithFocus = false; 7117 mSelectionMoved = false; 7118 7119 if (mText instanceof Spannable) { 7120 Spannable sp = (Spannable) mText; 7121 MetaKeyKeyListener.resetMetaState(sp); 7122 } 7123 7124 makeBlink(); 7125 7126 if (mError != null) { 7127 showError(); 7128 } 7129 } else { 7130 if (mError != null) { 7131 hideError(); 7132 } 7133 // Don't leave us in the middle of a batch edit. 7134 onEndBatchEdit(); 7135 7136 hideInsertionPointCursorController(); 7137 if (this instanceof ExtractEditText) { 7138 // terminateTextSelectionMode removes selection, which we want to keep when 7139 // ExtractEditText goes out of focus. 7140 final int selStart = getSelectionStart(); 7141 final int selEnd = getSelectionEnd(); 7142 terminateSelectionActionMode(); 7143 Selection.setSelection((Spannable) mText, selStart, selEnd); 7144 } else { 7145 terminateSelectionActionMode(); 7146 } 7147 7148 // No need to create the controller 7149 if (mSelectionModifierCursorController != null) { 7150 mSelectionModifierCursorController.resetTouchOffsets(); 7151 } 7152 } 7153 7154 startStopMarquee(focused); 7155 7156 if (mTransformation != null) { 7157 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 7158 } 7159 7160 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7161 7162 // Performed after super.onFocusChanged so that this TextView is registered and can ask for 7163 // the IME. Showing the IME while focus is moved using the D-Pad is a bad idea, however this 7164 // does not happen in that case (using the arrows on a bluetooth keyboard). 7165 if (focused && isTextEditable()) { 7166 final InputMethodManager imm = InputMethodManager.peekInstance(); 7167 if (imm != null) imm.showSoftInput(this, 0, null); 7168 } 7169 } 7170 7171 private int getLastTapPosition() { 7172 // No need to create the controller at that point, no last tap position saved 7173 if (mSelectionModifierCursorController != null) { 7174 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 7175 if (lastTapPosition >= 0) { 7176 // Safety check, should not be possible. 7177 if (lastTapPosition > mText.length()) { 7178 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 7179 + mText.length() + ")"); 7180 lastTapPosition = mText.length(); 7181 } 7182 return lastTapPosition; 7183 } 7184 } 7185 7186 return -1; 7187 } 7188 7189 @Override 7190 public void onWindowFocusChanged(boolean hasWindowFocus) { 7191 super.onWindowFocusChanged(hasWindowFocus); 7192 7193 if (hasWindowFocus) { 7194 if (mBlink != null) { 7195 mBlink.uncancel(); 7196 7197 if (isFocused()) { 7198 mShowCursor = SystemClock.uptimeMillis(); 7199 makeBlink(); 7200 } 7201 } 7202 } else { 7203 if (mBlink != null) { 7204 mBlink.cancel(); 7205 } 7206 // Don't leave us in the middle of a batch edit. 7207 onEndBatchEdit(); 7208 if (mInputContentType != null) { 7209 mInputContentType.enterDown = false; 7210 } 7211 hideControllers(); 7212 } 7213 7214 startStopMarquee(hasWindowFocus); 7215 } 7216 7217 @Override 7218 protected void onVisibilityChanged(View changedView, int visibility) { 7219 super.onVisibilityChanged(changedView, visibility); 7220 if (visibility != VISIBLE) { 7221 hideControllers(); 7222 } 7223 } 7224 7225 /** 7226 * Use {@link BaseInputConnection#removeComposingSpans 7227 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 7228 * state from this text view. 7229 */ 7230 public void clearComposingText() { 7231 if (mText instanceof Spannable) { 7232 BaseInputConnection.removeComposingSpans((Spannable)mText); 7233 } 7234 } 7235 7236 @Override 7237 public void setSelected(boolean selected) { 7238 boolean wasSelected = isSelected(); 7239 7240 super.setSelected(selected); 7241 7242 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7243 if (selected) { 7244 startMarquee(); 7245 } else { 7246 stopMarquee(); 7247 } 7248 } 7249 } 7250 7251 class CommitSelectionReceiver extends ResultReceiver { 7252 private final int mPrevStart, mPrevEnd; 7253 7254 public CommitSelectionReceiver(int prevStart, int prevEnd) { 7255 super(getHandler()); 7256 mPrevStart = prevStart; 7257 mPrevEnd = prevEnd; 7258 } 7259 7260 @Override 7261 protected void onReceiveResult(int resultCode, Bundle resultData) { 7262 // If this tap was actually used to show the IMM, leave cursor or selection unchanged 7263 // by restoring its previous position. 7264 if (resultCode == InputMethodManager.RESULT_SHOWN) { 7265 final int len = mText.length(); 7266 int start = Math.min(len, mPrevStart); 7267 int end = Math.min(len, mPrevEnd); 7268 Selection.setSelection((Spannable)mText, start, end); 7269 7270 boolean selectAllGotFocus = mSelectAllOnFocus && mTouchFocusSelected; 7271 if (hasSelection() && !selectAllGotFocus) { 7272 startSelectionActionMode(); 7273 } 7274 } 7275 } 7276 } 7277 7278 @Override 7279 public boolean onTouchEvent(MotionEvent event) { 7280 final int action = event.getActionMasked(); 7281 7282 if (hasInsertionController()) { 7283 getInsertionController().onTouchEvent(event); 7284 } 7285 if (hasSelectionController()) { 7286 getSelectionController().onTouchEvent(event); 7287 } 7288 7289 if (action == MotionEvent.ACTION_DOWN) { 7290 mLastDownPositionX = (int) event.getX(); 7291 mLastDownPositionY = (int) event.getY(); 7292 7293 // Reset this state; it will be re-set if super.onTouchEvent 7294 // causes focus to move to the view. 7295 mTouchFocusSelected = false; 7296 mIgnoreActionUpEvent = false; 7297 } 7298 7299 final boolean superResult = super.onTouchEvent(event); 7300 7301 /* 7302 * Don't handle the release after a long press, because it will 7303 * move the selection away from whatever the menu action was 7304 * trying to affect. 7305 */ 7306 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 7307 mDiscardNextActionUp = false; 7308 return superResult; 7309 } 7310 7311 final boolean touchIsFinished = action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && 7312 isFocused(); 7313 7314 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 7315 && mText instanceof Spannable && mLayout != null) { 7316 boolean handled = false; 7317 7318 // Save previous selection, in case this event is used to show the IME. 7319 int oldSelStart = getSelectionStart(); 7320 int oldSelEnd = getSelectionEnd(); 7321 7322 final int oldScrollX = mScrollX; 7323 final int oldScrollY = mScrollY; 7324 7325 if (mMovement != null) { 7326 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 7327 } 7328 7329 if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable && touchIsFinished) { 7330 // The LinkMovementMethod which should handle taps on links has not been installed 7331 // to support text selection. We reproduce its behavior here to open links. 7332 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 7333 getSelectionEnd(), ClickableSpan.class); 7334 7335 if (links.length != 0) { 7336 links[0].onClick(this); 7337 handled = true; 7338 } 7339 } 7340 7341 if (isTextEditable() || mTextIsSelectable) { 7342 if (mScrollX != oldScrollX || mScrollY != oldScrollY) { 7343 // Hide insertion anchor while scrolling. Leave selection. 7344 hideInsertionPointCursorController(); 7345 // No need to create the controller, since there is nothing to update. 7346 if (mSelectionModifierCursorController != null && 7347 mSelectionModifierCursorController.isShowing()) { 7348 mSelectionModifierCursorController.updatePosition(); 7349 } 7350 } 7351 7352 if (touchIsFinished) { 7353 CommitSelectionReceiver csr = null; 7354 if (getSelectionStart() != oldSelStart || getSelectionEnd() != oldSelEnd || 7355 didTouchFocusSelect()) { 7356 csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd); 7357 } 7358 7359 // Show the IME, except when selecting in read-only text. 7360 if (!mTextIsSelectable) { 7361 final InputMethodManager imm = InputMethodManager.peekInstance(); 7362 handled |= imm != null && imm.showSoftInput(this, 0, csr) && (csr != null); 7363 } 7364 7365 stopSelectionActionMode(); 7366 boolean selectAllGotFocus = mSelectAllOnFocus && mTouchFocusSelected; 7367 if (hasInsertionController() && !selectAllGotFocus && mText.length() > 0) { 7368 getInsertionController().show(); 7369 } 7370 } 7371 } 7372 7373 if (handled) { 7374 return true; 7375 } 7376 } 7377 7378 return superResult; 7379 } 7380 7381 private void prepareCursorControllers() { 7382 boolean windowSupportsHandles = false; 7383 7384 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 7385 if (params instanceof WindowManager.LayoutParams) { 7386 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 7387 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 7388 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 7389 } 7390 7391 mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null; 7392 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 7393 mLayout != null; 7394 7395 if (!mInsertionControllerEnabled) { 7396 hideInsertionPointCursorController(); 7397 if (mInsertionPointCursorController != null) { 7398 mInsertionPointCursorController.onDetached(); 7399 mInsertionPointCursorController = null; 7400 } 7401 } 7402 7403 if (!mSelectionControllerEnabled) { 7404 stopSelectionActionMode(); 7405 if (mSelectionModifierCursorController != null) { 7406 mSelectionModifierCursorController.onDetached(); 7407 mSelectionModifierCursorController = null; 7408 } 7409 } 7410 } 7411 7412 /** 7413 * @return True iff this TextView contains a text that can be edited, or if this is 7414 * a selectable TextView. 7415 */ 7416 private boolean isTextEditable() { 7417 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 7418 } 7419 7420 /** 7421 * Returns true, only while processing a touch gesture, if the initial 7422 * touch down event caused focus to move to the text view and as a result 7423 * its selection changed. Only valid while processing the touch gesture 7424 * of interest. 7425 */ 7426 public boolean didTouchFocusSelect() { 7427 return mTouchFocusSelected; 7428 } 7429 7430 @Override 7431 public void cancelLongPress() { 7432 super.cancelLongPress(); 7433 mIgnoreActionUpEvent = true; 7434 } 7435 7436 @Override 7437 public boolean onTrackballEvent(MotionEvent event) { 7438 if (mMovement != null && mText instanceof Spannable && 7439 mLayout != null) { 7440 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 7441 return true; 7442 } 7443 } 7444 7445 return super.onTrackballEvent(event); 7446 } 7447 7448 public void setScroller(Scroller s) { 7449 mScroller = s; 7450 } 7451 7452 private static class Blink extends Handler implements Runnable { 7453 private final WeakReference<TextView> mView; 7454 private boolean mCancelled; 7455 7456 public Blink(TextView v) { 7457 mView = new WeakReference<TextView>(v); 7458 } 7459 7460 public void run() { 7461 if (mCancelled) { 7462 return; 7463 } 7464 7465 removeCallbacks(Blink.this); 7466 7467 TextView tv = mView.get(); 7468 7469 if (tv != null && tv.isFocused()) { 7470 int st = tv.getSelectionStart(); 7471 int en = tv.getSelectionEnd(); 7472 7473 if (st == en && st >= 0 && en >= 0) { 7474 if (tv.mLayout != null) { 7475 tv.invalidateCursorPath(); 7476 } 7477 7478 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 7479 } 7480 } 7481 } 7482 7483 void cancel() { 7484 if (!mCancelled) { 7485 removeCallbacks(Blink.this); 7486 mCancelled = true; 7487 } 7488 } 7489 7490 void uncancel() { 7491 mCancelled = false; 7492 } 7493 } 7494 7495 @Override 7496 protected float getLeftFadingEdgeStrength() { 7497 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 7498 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7499 if (mMarquee != null && !mMarquee.isStopped()) { 7500 final Marquee marquee = mMarquee; 7501 if (marquee.shouldDrawLeftFade()) { 7502 return marquee.mScroll / getHorizontalFadingEdgeLength(); 7503 } else { 7504 return 0.0f; 7505 } 7506 } else if (getLineCount() == 1) { 7507 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 7508 case Gravity.LEFT: 7509 return 0.0f; 7510 case Gravity.RIGHT: 7511 return (mLayout.getLineRight(0) - (mRight - mLeft) - 7512 getCompoundPaddingLeft() - getCompoundPaddingRight() - 7513 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 7514 case Gravity.CENTER_HORIZONTAL: 7515 return 0.0f; 7516 } 7517 } 7518 } 7519 return super.getLeftFadingEdgeStrength(); 7520 } 7521 7522 @Override 7523 protected float getRightFadingEdgeStrength() { 7524 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 7525 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7526 if (mMarquee != null && !mMarquee.isStopped()) { 7527 final Marquee marquee = mMarquee; 7528 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 7529 } else if (getLineCount() == 1) { 7530 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 7531 case Gravity.LEFT: 7532 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 7533 getCompoundPaddingRight(); 7534 final float lineWidth = mLayout.getLineWidth(0); 7535 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 7536 case Gravity.RIGHT: 7537 return 0.0f; 7538 case Gravity.CENTER_HORIZONTAL: 7539 case Gravity.FILL_HORIZONTAL: 7540 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 7541 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 7542 getHorizontalFadingEdgeLength(); 7543 } 7544 } 7545 } 7546 return super.getRightFadingEdgeStrength(); 7547 } 7548 7549 @Override 7550 protected int computeHorizontalScrollRange() { 7551 if (mLayout != null) { 7552 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 7553 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 7554 } 7555 7556 return super.computeHorizontalScrollRange(); 7557 } 7558 7559 @Override 7560 protected int computeVerticalScrollRange() { 7561 if (mLayout != null) 7562 return mLayout.getHeight(); 7563 7564 return super.computeVerticalScrollRange(); 7565 } 7566 7567 @Override 7568 protected int computeVerticalScrollExtent() { 7569 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 7570 } 7571 7572 public enum BufferType { 7573 NORMAL, SPANNABLE, EDITABLE, 7574 } 7575 7576 /** 7577 * Returns the TextView_textColor attribute from the 7578 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 7579 * from the TextView_textAppearance attribute, if TextView_textColor 7580 * was not set directly. 7581 */ 7582 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 7583 ColorStateList colors; 7584 colors = attrs.getColorStateList(com.android.internal.R.styleable. 7585 TextView_textColor); 7586 7587 if (colors == null) { 7588 int ap = attrs.getResourceId(com.android.internal.R.styleable. 7589 TextView_textAppearance, -1); 7590 if (ap != -1) { 7591 TypedArray appearance; 7592 appearance = context.obtainStyledAttributes(ap, 7593 com.android.internal.R.styleable.TextAppearance); 7594 colors = appearance.getColorStateList(com.android.internal.R.styleable. 7595 TextAppearance_textColor); 7596 appearance.recycle(); 7597 } 7598 } 7599 7600 return colors; 7601 } 7602 7603 /** 7604 * Returns the default color from the TextView_textColor attribute 7605 * from the AttributeSet, if set, or the default color from the 7606 * TextAppearance_textColor from the TextView_textAppearance attribute, 7607 * if TextView_textColor was not set directly. 7608 */ 7609 public static int getTextColor(Context context, 7610 TypedArray attrs, 7611 int def) { 7612 ColorStateList colors = getTextColors(context, attrs); 7613 7614 if (colors == null) { 7615 return def; 7616 } else { 7617 return colors.getDefaultColor(); 7618 } 7619 } 7620 7621 @Override 7622 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7623 final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; 7624 if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { 7625 switch (keyCode) { 7626 case KeyEvent.KEYCODE_A: 7627 if (canSelectText()) { 7628 return onTextContextMenuItem(ID_SELECT_ALL); 7629 } 7630 break; 7631 case KeyEvent.KEYCODE_X: 7632 if (canCut()) { 7633 return onTextContextMenuItem(ID_CUT); 7634 } 7635 break; 7636 case KeyEvent.KEYCODE_C: 7637 if (canCopy()) { 7638 return onTextContextMenuItem(ID_COPY); 7639 } 7640 break; 7641 case KeyEvent.KEYCODE_V: 7642 if (canPaste()) { 7643 return onTextContextMenuItem(ID_PASTE); 7644 } 7645 break; 7646 } 7647 } 7648 return super.onKeyShortcut(keyCode, event); 7649 } 7650 7651 /** 7652 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 7653 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 7654 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 7655 */ 7656 private boolean canSelectText() { 7657 return hasSelectionController() && mText.length() != 0; 7658 } 7659 7660 /** 7661 * Test based on the <i>intrinsic</i> charateristics of the TextView. 7662 * The text must be spannable and the movement method must allow for arbitary selection. 7663 * 7664 * See also {@link #canSelectText()}. 7665 */ 7666 private boolean textCanBeSelected() { 7667 // prepareCursorController() relies on this method. 7668 // If you change this condition, make sure prepareCursorController is called anywhere 7669 // the value of this condition might be changed. 7670 return mText instanceof Spannable && mMovement != null && mMovement.canSelectArbitrarily(); 7671 } 7672 7673 private boolean canCut() { 7674 if (hasPasswordTransformationMethod()) { 7675 return false; 7676 } 7677 7678 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 7679 return true; 7680 } 7681 7682 return false; 7683 } 7684 7685 private boolean canCopy() { 7686 if (hasPasswordTransformationMethod()) { 7687 return false; 7688 } 7689 7690 if (mText.length() > 0 && hasSelection()) { 7691 return true; 7692 } 7693 7694 return false; 7695 } 7696 7697 private boolean canPaste() { 7698 return (mText instanceof Editable && 7699 mInput != null && 7700 getSelectionStart() >= 0 && 7701 getSelectionEnd() >= 0 && 7702 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 7703 hasPrimaryClip()); 7704 } 7705 7706 private boolean isWordCharacter(int c, int type) { 7707 return (c == '\'' || c == '"' || 7708 type == Character.UPPERCASE_LETTER || 7709 type == Character.LOWERCASE_LETTER || 7710 type == Character.TITLECASE_LETTER || 7711 type == Character.MODIFIER_LETTER || 7712 type == Character.OTHER_LETTER || // Should handle asian characters 7713 type == Character.DECIMAL_DIGIT_NUMBER); 7714 } 7715 7716 /** 7717 * Returns the offsets delimiting the 'word' located at position offset. 7718 * 7719 * @param offset An offset in the text. 7720 * @return The offsets for the start and end of the word located at <code>offset</code>. 7721 * The two ints offsets are packed in a long using {@link #packRangeInLong(int, int)}. 7722 * Returns -1 if no valid word was found. 7723 */ 7724 private long getWordLimitsAt(int offset) { 7725 int klass = mInputType & InputType.TYPE_MASK_CLASS; 7726 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 7727 7728 // Text selection is not permitted in password fields 7729 if (hasPasswordTransformationMethod()) { 7730 return -1; 7731 } 7732 7733 final int len = mText.length(); 7734 7735 // Specific text fields: always select the entire text 7736 if (klass == InputType.TYPE_CLASS_NUMBER || 7737 klass == InputType.TYPE_CLASS_PHONE || 7738 klass == InputType.TYPE_CLASS_DATETIME || 7739 variation == InputType.TYPE_TEXT_VARIATION_URI || 7740 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 7741 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 7742 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 7743 return len > 0 ? packRangeInLong(0, len) : -1; 7744 } 7745 7746 int end = Math.min(offset, len); 7747 if (end < 0) { 7748 return -1; 7749 } 7750 7751 final int MAX_LENGTH = 48; 7752 int start = end; 7753 7754 for (; start > 0; start--) { 7755 final char c = mTransformed.charAt(start - 1); 7756 final int type = Character.getType(c); 7757 if (start == end && type == Character.OTHER_PUNCTUATION) { 7758 // Cases where the text ends with a '.' and we select from the end of the line 7759 // (right after the dot), or when we select from the space character in "aaa, bbb". 7760 continue; 7761 } 7762 if (type == Character.SURROGATE) { // Two Character codepoint 7763 end = start - 1; // Recheck as a pair when scanning forward 7764 continue; 7765 } 7766 if (!isWordCharacter(c, type)) break; 7767 if ((end - start) > MAX_LENGTH) return -1; 7768 } 7769 7770 for (; end < len; end++) { 7771 final int c = Character.codePointAt(mTransformed, end); 7772 final int type = Character.getType(c); 7773 if (!isWordCharacter(c, type)) break; 7774 if ((end - start) > MAX_LENGTH) return -1; 7775 if (c > 0xFFFF) { // Two Character codepoint 7776 end++; 7777 } 7778 } 7779 7780 if (start == end) { 7781 return -1; 7782 } 7783 7784 // Two ints packed in a long 7785 return packRangeInLong(start, end); 7786 } 7787 7788 private static long packRangeInLong(int start, int end) { 7789 return (((long) start) << 32) | end; 7790 } 7791 7792 private static int extractRangeStartFromLong(long range) { 7793 return (int) (range >>> 32); 7794 } 7795 7796 private static int extractRangeEndFromLong(long range) { 7797 return (int) (range & 0x00000000FFFFFFFFL); 7798 } 7799 7800 private void selectAll() { 7801 Selection.setSelection((Spannable) mText, 0, mText.length()); 7802 } 7803 7804 private void selectCurrentWord() { 7805 if (!canSelectText()) { 7806 return; 7807 } 7808 7809 if (hasPasswordTransformationMethod()) { 7810 // Always select all on a password field. 7811 // Cut/copy menu entries are not available for passwords, but being able to select all 7812 // is however useful to delete or paste to replace the entire content. 7813 selectAll(); 7814 return; 7815 } 7816 7817 long lastTouchOffsets = getLastTouchOffsets(); 7818 final int minOffset = extractRangeStartFromLong(lastTouchOffsets); 7819 final int maxOffset = extractRangeEndFromLong(lastTouchOffsets); 7820 7821 int selectionStart, selectionEnd; 7822 7823 // If a URLSpan (web address, email, phone...) is found at that position, select it. 7824 URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class); 7825 if (urlSpans.length == 1) { 7826 URLSpan url = urlSpans[0]; 7827 selectionStart = ((Spanned) mText).getSpanStart(url); 7828 selectionEnd = ((Spanned) mText).getSpanEnd(url); 7829 } else { 7830 long wordLimits = getWordLimitsAt(minOffset); 7831 if (wordLimits >= 0) { 7832 selectionStart = extractRangeStartFromLong(wordLimits); 7833 } else { 7834 selectionStart = Math.max(minOffset - 5, 0); 7835 } 7836 7837 wordLimits = getWordLimitsAt(maxOffset); 7838 if (wordLimits >= 0) { 7839 selectionEnd = extractRangeEndFromLong(wordLimits); 7840 } else { 7841 selectionEnd = Math.min(maxOffset + 5, mText.length()); 7842 } 7843 } 7844 7845 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 7846 } 7847 7848 private long getLastTouchOffsets() { 7849 int minOffset, maxOffset; 7850 7851 if (mContextMenuTriggeredByKey) { 7852 minOffset = getSelectionStart(); 7853 maxOffset = getSelectionEnd(); 7854 } else { 7855 SelectionModifierCursorController selectionController = getSelectionController(); 7856 minOffset = selectionController.getMinTouchOffset(); 7857 maxOffset = selectionController.getMaxTouchOffset(); 7858 } 7859 7860 return packRangeInLong(minOffset, maxOffset); 7861 } 7862 7863 @Override 7864 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 7865 if (!isShown()) { 7866 return false; 7867 } 7868 7869 final boolean isPassword = hasPasswordTransformationMethod(); 7870 7871 if (!isPassword) { 7872 CharSequence text = getText(); 7873 if (TextUtils.isEmpty(text)) { 7874 text = getHint(); 7875 } 7876 if (!TextUtils.isEmpty(text)) { 7877 if (text.length() > AccessibilityEvent.MAX_TEXT_LENGTH) { 7878 text = text.subSequence(0, AccessibilityEvent.MAX_TEXT_LENGTH + 1); 7879 } 7880 event.getText().add(text); 7881 } 7882 } else { 7883 event.setPassword(isPassword); 7884 } 7885 return false; 7886 } 7887 7888 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 7889 int fromIndex, int removedCount, int addedCount) { 7890 AccessibilityEvent event = 7891 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 7892 event.setFromIndex(fromIndex); 7893 event.setRemovedCount(removedCount); 7894 event.setAddedCount(addedCount); 7895 event.setBeforeText(beforeText); 7896 sendAccessibilityEventUnchecked(event); 7897 } 7898 7899 @Override 7900 protected void onCreateContextMenu(ContextMenu menu) { 7901 super.onCreateContextMenu(menu); 7902 boolean added = false; 7903 mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown; 7904 // Problem with context menu on long press: the menu appears while the key in down and when 7905 // the key is released, the view does not receive the key_up event. 7906 // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up 7907 // events. We cannot simply clear these flags in onTextContextMenuItem since 7908 // it may not be called (if the user/ discards the context menu with the back key). 7909 // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is 7910 // available in onTextContextMenuItem. 7911 mDPadCenterIsDown = mEnterKeyIsDown = false; 7912 7913 MenuHandler handler = new MenuHandler(); 7914 7915 if (mText instanceof Spanned && hasSelectionController()) { 7916 long lastTouchOffset = getLastTouchOffsets(); 7917 final int selStart = extractRangeStartFromLong(lastTouchOffset); 7918 final int selEnd = extractRangeEndFromLong(lastTouchOffset); 7919 7920 URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class); 7921 if (urls.length > 0) { 7922 menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl). 7923 setOnMenuItemClickListener(handler); 7924 7925 added = true; 7926 } 7927 } 7928 7929 // The context menu is not empty, which will prevent the selection mode from starting. 7930 // Add a entry to start it in the context menu. 7931 // TODO Does not handle the case where a subclass does not call super.thisMethod or 7932 // populates the menu AFTER this call. 7933 if (menu.size() > 0) { 7934 menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode). 7935 setOnMenuItemClickListener(handler); 7936 added = true; 7937 } 7938 7939 if (added) { 7940 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 7941 } 7942 } 7943 7944 /** 7945 * Returns whether this text view is a current input method target. The 7946 * default implementation just checks with {@link InputMethodManager}. 7947 */ 7948 public boolean isInputMethodTarget() { 7949 InputMethodManager imm = InputMethodManager.peekInstance(); 7950 return imm != null && imm.isActive(this); 7951 } 7952 7953 // Selection context mode 7954 private static final int ID_SELECT_ALL = android.R.id.selectAll; 7955 private static final int ID_CUT = android.R.id.cut; 7956 private static final int ID_COPY = android.R.id.copy; 7957 private static final int ID_PASTE = android.R.id.paste; 7958 // Context menu entries 7959 private static final int ID_COPY_URL = android.R.id.copyUrl; 7960 private static final int ID_SELECTION_MODE = android.R.id.selectTextMode; 7961 7962 private class MenuHandler implements MenuItem.OnMenuItemClickListener { 7963 public boolean onMenuItemClick(MenuItem item) { 7964 return onTextContextMenuItem(item.getItemId()); 7965 } 7966 } 7967 7968 /** 7969 * Called when a context menu option for the text view is selected. Currently 7970 * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode}, 7971 * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut} 7972 * or {@link android.R.id#copy}. 7973 */ 7974 public boolean onTextContextMenuItem(int id) { 7975 int min = 0; 7976 int max = mText.length(); 7977 7978 if (isFocused()) { 7979 final int selStart = getSelectionStart(); 7980 final int selEnd = getSelectionEnd(); 7981 7982 min = Math.max(0, Math.min(selStart, selEnd)); 7983 max = Math.max(0, Math.max(selStart, selEnd)); 7984 } 7985 7986 switch (id) { 7987 case ID_COPY_URL: 7988 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class); 7989 if (urls.length >= 1) { 7990 ClipData clip = null; 7991 for (int i=0; i<urls.length; i++) { 7992 Uri uri = Uri.parse(urls[0].getURL()); 7993 if (clip == null) { 7994 clip = ClipData.newRawUri(null, uri); 7995 } else { 7996 clip.addItem(new ClipData.Item(uri)); 7997 } 7998 } 7999 if (clip != null) { 8000 setPrimaryClip(clip); 8001 } 8002 } 8003 stopSelectionActionMode(); 8004 return true; 8005 8006 case ID_SELECTION_MODE: 8007 if (mSelectionActionMode != null) { 8008 // Selection mode is already started, simply change selected part. 8009 updateSelectedRegion(); 8010 } else { 8011 startSelectionActionMode(); 8012 } 8013 return true; 8014 8015 case ID_SELECT_ALL: 8016 selectAll(); 8017 // Update controller positions after selection change. 8018 if (hasSelectionController()) { 8019 getSelectionController().show(); 8020 } 8021 return true; 8022 8023 case ID_PASTE: 8024 paste(min, max); 8025 return true; 8026 8027 case ID_CUT: 8028 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8029 ((Editable) mText).delete(min, max); 8030 stopSelectionActionMode(); 8031 return true; 8032 8033 case ID_COPY: 8034 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8035 stopSelectionActionMode(); 8036 return true; 8037 } 8038 return false; 8039 } 8040 8041 /** 8042 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 8043 * by [min, max] when replacing this region by paste. 8044 * Note that if there were two spaces (or more) at that position before, they are kept. We just 8045 * make sure we do not add an extra one from the paste content. 8046 */ 8047 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 8048 if (paste.length() > 0) { 8049 if (min > 0) { 8050 final char charBefore = mTransformed.charAt(min - 1); 8051 final char charAfter = paste.charAt(0); 8052 8053 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8054 // Two spaces at beginning of paste: remove one 8055 final int originalLength = mText.length(); 8056 ((Editable) mText).delete(min - 1, min); 8057 // Due to filters, there is no guarantee that exactly one character was 8058 // removed: count instead. 8059 final int delta = mText.length() - originalLength; 8060 min += delta; 8061 max += delta; 8062 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8063 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8064 // No space at beginning of paste: add one 8065 final int originalLength = mText.length(); 8066 ((Editable) mText).replace(min, min, " "); 8067 // Taking possible filters into account as above. 8068 final int delta = mText.length() - originalLength; 8069 min += delta; 8070 max += delta; 8071 } 8072 } 8073 8074 if (max < mText.length()) { 8075 final char charBefore = paste.charAt(paste.length() - 1); 8076 final char charAfter = mTransformed.charAt(max); 8077 8078 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8079 // Two spaces at end of paste: remove one 8080 ((Editable) mText).delete(max, max + 1); 8081 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8082 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8083 // No space at end of paste: add one 8084 ((Editable) mText).replace(max, max, " "); 8085 } 8086 } 8087 } 8088 8089 return packRangeInLong(min, max); 8090 } 8091 8092 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 8093 TextView shadowView = (TextView) inflate(mContext, 8094 com.android.internal.R.layout.text_drag_thumbnail, null); 8095 8096 if (shadowView == null) { 8097 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 8098 } 8099 8100 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 8101 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 8102 } 8103 shadowView.setText(text); 8104 shadowView.setTextColor(getTextColors()); 8105 8106 shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 8107 shadowView.setGravity(Gravity.CENTER); 8108 8109 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8110 ViewGroup.LayoutParams.WRAP_CONTENT)); 8111 8112 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8113 shadowView.measure(size, size); 8114 8115 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 8116 shadowView.invalidate(); 8117 return new DragShadowBuilder(shadowView); 8118 } 8119 8120 private static class DragLocalState { 8121 public TextView sourceTextView; 8122 public int start, end; 8123 8124 public DragLocalState(TextView sourceTextView, int start, int end) { 8125 this.sourceTextView = sourceTextView; 8126 this.start = start; 8127 this.end = end; 8128 } 8129 } 8130 8131 @Override 8132 public boolean performLongClick() { 8133 if (super.performLongClick()) { 8134 mDiscardNextActionUp = true; 8135 return true; 8136 } 8137 8138 // Long press in empty space moves cursor and shows the Paste affordance if available. 8139 if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 8140 mInsertionControllerEnabled) { 8141 final int offset = getOffset(mLastDownPositionX, mLastDownPositionY); 8142 stopSelectionActionMode(); 8143 Selection.setSelection((Spannable)mText, offset); 8144 getInsertionController().show(0); 8145 mDiscardNextActionUp = true; 8146 return true; 8147 } 8148 8149 if (mSelectionActionMode != null) { 8150 if (touchPositionIsInSelection()) { 8151 // Start a drag 8152 final int start = getSelectionStart(); 8153 final int end = getSelectionEnd(); 8154 CharSequence selectedText = mTransformed.subSequence(start, end); 8155 ClipData data = ClipData.newPlainText(null, selectedText); 8156 DragLocalState localState = new DragLocalState(this, start, end); 8157 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 8158 stopSelectionActionMode(); 8159 } else { 8160 updateSelectedRegion(); 8161 } 8162 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 8163 mDiscardNextActionUp = true; 8164 return true; 8165 } 8166 8167 // Start a new selection 8168 if (startSelectionActionMode()) { 8169 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 8170 mDiscardNextActionUp = true; 8171 return true; 8172 } 8173 8174 return false; 8175 } 8176 8177 /** 8178 * When selection mode is already started, this method simply updates the selected part of text 8179 * to the text under the finger. 8180 */ 8181 private void updateSelectedRegion() { 8182 // Start a new selection at current position, keep selectionAction mode on 8183 selectCurrentWord(); 8184 // Updates handles' positions 8185 getSelectionController().show(); 8186 } 8187 8188 private boolean touchPositionIsInSelection() { 8189 int selectionStart = getSelectionStart(); 8190 int selectionEnd = getSelectionEnd(); 8191 8192 if (selectionStart == selectionEnd) { 8193 return false; 8194 } 8195 8196 if (selectionStart > selectionEnd) { 8197 int tmp = selectionStart; 8198 selectionStart = selectionEnd; 8199 selectionEnd = tmp; 8200 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8201 } 8202 8203 SelectionModifierCursorController selectionController = getSelectionController(); 8204 int minOffset = selectionController.getMinTouchOffset(); 8205 int maxOffset = selectionController.getMaxTouchOffset(); 8206 8207 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 8208 } 8209 8210 /** 8211 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 8212 * selection is initiated in this View. 8213 * 8214 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 8215 * Paste actions, depending on what this View supports. 8216 * 8217 * A custom implementation can add new entries in the default menu in its 8218 * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions 8219 * can also be removed from the menu using {@link Menu#removeItem(int)} and passing 8220 * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or 8221 * {@link android.R.id#paste} ids as parameters. 8222 * 8223 * Returning false from {@link ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will 8224 * prevent the action mode from being started. 8225 * 8226 * Action click events should be handled by the custom implementation of 8227 * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 8228 * 8229 * Note that text selection mode is not started when a TextView receives focus and the 8230 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 8231 * that case, to allow for quick replacement. 8232 */ 8233 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 8234 mCustomSelectionActionModeCallback = actionModeCallback; 8235 } 8236 8237 /** 8238 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 8239 * 8240 * @return The current custom selection callback. 8241 */ 8242 public ActionMode.Callback getCustomSelectionActionModeCallback() { 8243 return mCustomSelectionActionModeCallback; 8244 } 8245 8246 /** 8247 * 8248 * @return true if the selection mode was actually started. 8249 */ 8250 private boolean startSelectionActionMode() { 8251 if (mSelectionActionMode != null) { 8252 // Selection action mode is already started 8253 return false; 8254 } 8255 8256 if (!canSelectText() || !requestFocus()) { 8257 Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled."); 8258 return false; 8259 } 8260 8261 if (!hasSelection()) { 8262 // If selection mode is started after a device rotation, there is already a selection. 8263 selectCurrentWord(); 8264 } 8265 8266 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 8267 mSelectionActionMode = startActionMode(actionModeCallback); 8268 final boolean selectionStarted = mSelectionActionMode != null; 8269 8270 if (selectionStarted && !mTextIsSelectable) { 8271 // Show the IME to be able to replace text, except when selecting non editable text. 8272 final InputMethodManager imm = InputMethodManager.peekInstance(); 8273 if (imm != null) imm.showSoftInput(this, 0, null); 8274 } 8275 8276 return selectionStarted; 8277 } 8278 8279 /** 8280 * Same as {@link #stopSelectionActionMode()}, except that there is no cursor controller 8281 * fade out animation. Needed since the drawable and their alpha values are shared by all 8282 * TextViews. Switching from one TextView to another would fade the cursor controllers in the 8283 * new one otherwise. 8284 */ 8285 private void terminateSelectionActionMode() { 8286 stopSelectionActionMode(); 8287 8288 // No need to create the controller, nothing to cancel in that case. 8289 if (mSelectionModifierCursorController != null) { 8290 mSelectionModifierCursorController.cancelFadeOutAnimation(); 8291 } 8292 } 8293 8294 private void stopSelectionActionMode() { 8295 if (mSelectionActionMode != null) { 8296 // This will hide the mSelectionModifierCursorController 8297 mSelectionActionMode.finish(); 8298 } 8299 } 8300 8301 /** 8302 * Paste clipboard content between min and max positions. 8303 */ 8304 private void paste(int min, int max) { 8305 ClipboardManager clipboard = 8306 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 8307 ClipData clip = clipboard.getPrimaryClip(); 8308 if (clip != null) { 8309 boolean didfirst = false; 8310 for (int i=0; i<clip.getItemCount(); i++) { 8311 CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); 8312 if (paste != null) { 8313 if (!didfirst) { 8314 long minMax = prepareSpacesAroundPaste(min, max, paste); 8315 min = extractRangeStartFromLong(minMax); 8316 max = extractRangeEndFromLong(minMax); 8317 Selection.setSelection((Spannable) mText, max); 8318 ((Editable) mText).replace(min, max, paste); 8319 } else { 8320 ((Editable) mText).insert(getSelectionEnd(), "\n"); 8321 ((Editable) mText).insert(getSelectionEnd(), paste); 8322 } 8323 } 8324 } 8325 stopSelectionActionMode(); 8326 sLastCutOrCopyTime = 0; 8327 } 8328 } 8329 8330 private void setPrimaryClip(ClipData clip) { 8331 ClipboardManager clipboard = (ClipboardManager) getContext(). 8332 getSystemService(Context.CLIPBOARD_SERVICE); 8333 clipboard.setPrimaryClip(clip); 8334 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 8335 } 8336 8337 /** 8338 * An ActionMode Callback class that is used to provide actions while in text selection mode. 8339 * 8340 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 8341 * on which of these this TextView supports. 8342 */ 8343 private class SelectionActionModeCallback implements ActionMode.Callback { 8344 8345 @Override 8346 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 8347 TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme); 8348 8349 mode.setTitle(mContext.getString(com.android.internal.R.string.textSelectionCABTitle)); 8350 mode.setSubtitle(null); 8351 8352 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 8353 setAlphabeticShortcut('a'). 8354 setShowAsAction( 8355 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8356 8357 if (canCut()) { 8358 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 8359 setIcon(styledAttributes.getResourceId( 8360 R.styleable.Theme_actionModeCutDrawable, 0)). 8361 setAlphabeticShortcut('x'). 8362 setShowAsAction( 8363 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8364 } 8365 8366 if (canCopy()) { 8367 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 8368 setIcon(styledAttributes.getResourceId( 8369 R.styleable.Theme_actionModeCopyDrawable, 0)). 8370 setAlphabeticShortcut('c'). 8371 setShowAsAction( 8372 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8373 } 8374 8375 if (canPaste()) { 8376 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 8377 setIcon(styledAttributes.getResourceId( 8378 R.styleable.Theme_actionModePasteDrawable, 0)). 8379 setAlphabeticShortcut('v'). 8380 setShowAsAction( 8381 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8382 } 8383 8384 styledAttributes.recycle(); 8385 8386 if (mCustomSelectionActionModeCallback != null) { 8387 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 8388 // The custom mode can choose to cancel the action mode 8389 return false; 8390 } 8391 } 8392 8393 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 8394 getSelectionController().show(); 8395 return true; 8396 } else { 8397 return false; 8398 } 8399 } 8400 8401 @Override 8402 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 8403 if (mCustomSelectionActionModeCallback != null) { 8404 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 8405 } 8406 return true; 8407 } 8408 8409 @Override 8410 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 8411 if (mCustomSelectionActionModeCallback != null && 8412 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 8413 return true; 8414 } 8415 return onTextContextMenuItem(item.getItemId()); 8416 } 8417 8418 @Override 8419 public void onDestroyActionMode(ActionMode mode) { 8420 if (mCustomSelectionActionModeCallback != null) { 8421 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 8422 } 8423 Selection.setSelection((Spannable) mText, getSelectionEnd()); 8424 8425 if (mSelectionModifierCursorController != null) { 8426 mSelectionModifierCursorController.hide(); 8427 } 8428 8429 mSelectionActionMode = null; 8430 } 8431 } 8432 8433 /** 8434 * A CursorController instance can be used to control a cursor in the text. 8435 * It is not used outside of {@link TextView}. 8436 * @hide 8437 */ 8438 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 8439 /** 8440 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 8441 * See also {@link #hide()}. 8442 */ 8443 public void show(); 8444 8445 /** 8446 * Hide the cursor controller from screen. 8447 * See also {@link #show()}. 8448 */ 8449 public void hide(); 8450 8451 /** 8452 * @return true if the CursorController is currently visible 8453 */ 8454 public boolean isShowing(); 8455 8456 /** 8457 * Update the controller's position. 8458 */ 8459 public void updatePosition(HandleView handle, int x, int y); 8460 8461 public void updateOffset(HandleView handle, int offset); 8462 8463 public void updatePosition(); 8464 8465 public int getCurrentOffset(HandleView handle); 8466 8467 /** 8468 * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller 8469 * a chance to become active and/or visible. 8470 * @param event The touch event 8471 */ 8472 public boolean onTouchEvent(MotionEvent event); 8473 8474 /** 8475 * Called when the view is detached from window. Perform house keeping task, such as 8476 * stopping Runnable thread that would otherwise keep a reference on the context, thus 8477 * preventing the activity to be recycled. 8478 */ 8479 public void onDetached(); 8480 } 8481 8482 private class PastePopupMenu implements OnClickListener { 8483 private final PopupWindow mContainer; 8484 private int mPositionX; 8485 private int mPositionY; 8486 private final View[] mPasteViews = new View[4]; 8487 private final int[] mPasteViewLayouts = new int[] { 8488 mTextEditPasteWindowLayout, mTextEditNoPasteWindowLayout, 8489 mTextEditSidePasteWindowLayout, mTextEditSideNoPasteWindowLayout }; 8490 8491 public PastePopupMenu() { 8492 mContainer = new PopupWindow(TextView.this.mContext, null, 8493 com.android.internal.R.attr.textSelectHandleWindowStyle); 8494 mContainer.setSplitTouchEnabled(true); 8495 mContainer.setClippingEnabled(false); 8496 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8497 8498 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 8499 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 8500 } 8501 8502 private int viewIndex(boolean onTop) { 8503 return (onTop ? 0 : 1<<1) + (canPaste() ? 0 : 1<<0); 8504 } 8505 8506 private void updateContent(boolean onTop) { 8507 final int viewIndex = viewIndex(onTop); 8508 View view = mPasteViews[viewIndex]; 8509 8510 if (view == null) { 8511 final int layout = mPasteViewLayouts[viewIndex]; 8512 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 8513 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 8514 if (inflater != null) { 8515 view = inflater.inflate(layout, null); 8516 } 8517 8518 if (view == null) { 8519 throw new IllegalArgumentException("Unable to inflate TextEdit paste window"); 8520 } 8521 8522 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8523 view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8524 ViewGroup.LayoutParams.WRAP_CONTENT)); 8525 view.measure(size, size); 8526 8527 view.setOnClickListener(this); 8528 8529 mPasteViews[viewIndex] = view; 8530 } 8531 8532 mContainer.setContentView(view); 8533 } 8534 8535 public void show() { 8536 updateContent(true); 8537 positionAtCursor(); 8538 } 8539 8540 public void hide() { 8541 mContainer.dismiss(); 8542 } 8543 8544 public boolean isShowing() { 8545 return mContainer.isShowing(); 8546 } 8547 8548 @Override 8549 public void onClick(View v) { 8550 if (canPaste()) { 8551 paste(getSelectionStart(), getSelectionEnd()); 8552 } 8553 hide(); 8554 } 8555 8556 void positionAtCursor() { 8557 View contentView = mContainer.getContentView(); 8558 int width = contentView.getMeasuredWidth(); 8559 int height = contentView.getMeasuredHeight(); 8560 final int offset = TextView.this.getSelectionStart(); 8561 final int line = mLayout.getLineForOffset(offset); 8562 final int lineTop = mLayout.getLineTop(line); 8563 float primaryHorizontal = mLayout.getPrimaryHorizontal(offset); 8564 8565 final Rect bounds = sCursorControllerTempRect; 8566 bounds.left = (int) (primaryHorizontal - width / 2.0f); 8567 bounds.top = lineTop - height; 8568 8569 bounds.right = bounds.left + width; 8570 bounds.bottom = bounds.top + height; 8571 8572 convertFromViewportToContentCoordinates(bounds); 8573 8574 mPositionX = bounds.left; 8575 mPositionY = bounds.top; 8576 8577 8578 final int[] coords = mTempCoords; 8579 TextView.this.getLocationInWindow(coords); 8580 coords[0] += mPositionX; 8581 coords[1] += mPositionY; 8582 8583 final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels; 8584 if (coords[1] < 0) { 8585 updateContent(false); 8586 // Update dimensions from new view 8587 contentView = mContainer.getContentView(); 8588 width = contentView.getMeasuredWidth(); 8589 height = contentView.getMeasuredHeight(); 8590 8591 // Vertical clipping, move under edited line and to the side of insertion cursor 8592 // TODO bottom clipping in case there is no system bar 8593 coords[1] += height; 8594 final int lineBottom = mLayout.getLineBottom(line); 8595 final int lineHeight = lineBottom - lineTop; 8596 coords[1] += lineHeight; 8597 8598 // Move to right hand side of insertion cursor by default. TODO RTL text. 8599 final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes); 8600 final int handleHalfWidth = handle.getIntrinsicWidth() / 2; 8601 8602 if (primaryHorizontal + handleHalfWidth + width < screenWidth) { 8603 coords[0] += handleHalfWidth + width / 2; 8604 } else { 8605 coords[0] -= handleHalfWidth + width / 2; 8606 } 8607 } else { 8608 // Horizontal clipping 8609 coords[0] = Math.max(0, coords[0]); 8610 coords[0] = Math.min(screenWidth - width, coords[0]); 8611 } 8612 8613 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); 8614 } 8615 } 8616 8617 private class HandleView extends View { 8618 private Drawable mDrawable; 8619 private final PopupWindow mContainer; 8620 private int mPositionX; 8621 private int mPositionY; 8622 private final CursorController mController; 8623 private boolean mIsDragging; 8624 private float mTouchToWindowOffsetX; 8625 private float mTouchToWindowOffsetY; 8626 private float mHotspotX; 8627 private float mHotspotY; 8628 private int mHeight; 8629 private float mTouchOffsetY; 8630 private int mLastParentX; 8631 private int mLastParentY; 8632 private float mDownPositionX, mDownPositionY; 8633 private int mContainerPositionX, mContainerPositionY; 8634 private long mTouchTimer; 8635 private boolean mIsInsertionHandle = false; 8636 private PastePopupMenu mPastePopupWindow; 8637 8638 // Touch-up filter: number of previous positions remembered 8639 private static final int HISTORY_SIZE = 5; 8640 private static final int TOUCH_UP_FILTER_DELAY = 150; 8641 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 8642 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 8643 private int mPreviousOffsetIndex = 0; 8644 private int mNumberPreviousOffsets = 0; 8645 8646 public void startTouchUpFilter(int offset) { 8647 mNumberPreviousOffsets = 0; 8648 addPositionToTouchUpFilter(offset); 8649 } 8650 8651 public void addPositionToTouchUpFilter(int offset) { 8652 if (mNumberPreviousOffsets > 0 && 8653 mPreviousOffsets[mPreviousOffsetIndex] == offset) { 8654 // Make sure only actual changes of position are recorded. 8655 return; 8656 } 8657 8658 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 8659 mPreviousOffsets[mPreviousOffsetIndex] = offset; 8660 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 8661 mNumberPreviousOffsets++; 8662 } 8663 8664 public void filterOnTouchUp() { 8665 final long now = SystemClock.uptimeMillis(); 8666 int i = 0; 8667 int index = 0; 8668 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 8669 while (i < iMax) { 8670 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 8671 if ((now - mPreviousOffsetsTimes[index]) >= TOUCH_UP_FILTER_DELAY) break; 8672 i++; 8673 } 8674 8675 mController.updateOffset(this, mPreviousOffsets[index]); 8676 } 8677 8678 public static final int LEFT = 0; 8679 public static final int CENTER = 1; 8680 public static final int RIGHT = 2; 8681 8682 public HandleView(CursorController controller, int pos) { 8683 super(TextView.this.mContext); 8684 mController = controller; 8685 mContainer = new PopupWindow(TextView.this.mContext, null, 8686 com.android.internal.R.attr.textSelectHandleWindowStyle); 8687 mContainer.setSplitTouchEnabled(true); 8688 mContainer.setClippingEnabled(false); 8689 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8690 8691 setOrientation(pos); 8692 } 8693 8694 public void setOrientation(int pos) { 8695 int handleWidth; 8696 switch (pos) { 8697 case LEFT: { 8698 if (mSelectHandleLeft == null) { 8699 mSelectHandleLeft = mContext.getResources().getDrawable( 8700 mTextSelectHandleLeftRes); 8701 } 8702 mDrawable = mSelectHandleLeft; 8703 handleWidth = mDrawable.getIntrinsicWidth(); 8704 mHotspotX = (handleWidth * 3) / 4; 8705 break; 8706 } 8707 8708 case RIGHT: { 8709 if (mSelectHandleRight == null) { 8710 mSelectHandleRight = mContext.getResources().getDrawable( 8711 mTextSelectHandleRightRes); 8712 } 8713 mDrawable = mSelectHandleRight; 8714 handleWidth = mDrawable.getIntrinsicWidth(); 8715 mHotspotX = handleWidth / 4; 8716 break; 8717 } 8718 8719 case CENTER: 8720 default: { 8721 if (mSelectHandleCenter == null) { 8722 mSelectHandleCenter = mContext.getResources().getDrawable( 8723 mTextSelectHandleRes); 8724 } 8725 mDrawable = mSelectHandleCenter; 8726 handleWidth = mDrawable.getIntrinsicWidth(); 8727 mHotspotX = handleWidth / 2; 8728 mIsInsertionHandle = true; 8729 break; 8730 } 8731 } 8732 8733 final int handleHeight = mDrawable.getIntrinsicHeight(); 8734 8735 mTouchOffsetY = -handleHeight * 0.3f; 8736 mHotspotY = 0; 8737 mHeight = handleHeight; 8738 invalidate(); 8739 } 8740 8741 @Override 8742 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 8743 setMeasuredDimension(mDrawable.getIntrinsicWidth(), 8744 mDrawable.getIntrinsicHeight()); 8745 } 8746 8747 public void show() { 8748 if (!isPositionVisible()) { 8749 hide(); 8750 return; 8751 } 8752 mContainer.setContentView(this); 8753 final int[] coords = mTempCoords; 8754 TextView.this.getLocationInWindow(coords); 8755 mContainerPositionX = coords[0] + mPositionX; 8756 mContainerPositionY = coords[1] + mPositionY; 8757 mContainer.showAtLocation(TextView.this, 0, mContainerPositionX, mContainerPositionY); 8758 8759 // Hide paste view when handle is moved on screen. 8760 if (mPastePopupWindow != null) { 8761 mPastePopupWindow.hide(); 8762 } 8763 } 8764 8765 public void hide() { 8766 mIsDragging = false; 8767 mContainer.dismiss(); 8768 if (mPastePopupWindow != null) { 8769 mPastePopupWindow.hide(); 8770 } 8771 } 8772 8773 public boolean isShowing() { 8774 return mContainer.isShowing(); 8775 } 8776 8777 private boolean isPositionVisible() { 8778 // Always show a dragging handle. 8779 if (mIsDragging) { 8780 return true; 8781 } 8782 8783 if (isInBatchEditMode()) { 8784 return false; 8785 } 8786 8787 final int extendedPaddingTop = getExtendedPaddingTop(); 8788 final int extendedPaddingBottom = getExtendedPaddingBottom(); 8789 final int compoundPaddingLeft = getCompoundPaddingLeft(); 8790 final int compoundPaddingRight = getCompoundPaddingRight(); 8791 8792 final TextView hostView = TextView.this; 8793 final int left = 0; 8794 final int right = hostView.getWidth(); 8795 final int top = 0; 8796 final int bottom = hostView.getHeight(); 8797 8798 if (mTempRect == null) { 8799 mTempRect = new Rect(); 8800 } 8801 final Rect clip = mTempRect; 8802 clip.left = left + compoundPaddingLeft; 8803 clip.top = top + extendedPaddingTop; 8804 clip.right = right - compoundPaddingRight; 8805 clip.bottom = bottom - extendedPaddingBottom; 8806 8807 final ViewParent parent = hostView.getParent(); 8808 if (parent == null || !parent.getChildVisibleRect(hostView, clip, null)) { 8809 return false; 8810 } 8811 8812 final int[] coords = mTempCoords; 8813 hostView.getLocationInWindow(coords); 8814 final int posX = coords[0] + mPositionX + (int) mHotspotX; 8815 final int posY = coords[1] + mPositionY + (int) mHotspotY; 8816 8817 return posX >= clip.left && posX <= clip.right && 8818 posY >= clip.top && posY <= clip.bottom; 8819 } 8820 8821 private void moveTo(int x, int y) { 8822 mPositionX = x - TextView.this.mScrollX; 8823 mPositionY = y - TextView.this.mScrollY; 8824 if (isPositionVisible()) { 8825 int[] coords = null; 8826 if (mContainer.isShowing()) { 8827 coords = mTempCoords; 8828 TextView.this.getLocationInWindow(coords); 8829 final int containerPositionX = coords[0] + mPositionX; 8830 final int containerPositionY = coords[1] + mPositionY; 8831 8832 if (containerPositionX != mContainerPositionX || 8833 containerPositionY != mContainerPositionY) { 8834 mContainerPositionX = containerPositionX; 8835 mContainerPositionY = containerPositionY; 8836 8837 mContainer.update(mContainerPositionX, mContainerPositionY, 8838 mRight - mLeft, mBottom - mTop); 8839 8840 // Hide paste popup window as soon as a scroll occurs. 8841 if (mPastePopupWindow != null) { 8842 mPastePopupWindow.hide(); 8843 } 8844 } 8845 } else { 8846 show(); 8847 } 8848 8849 if (mIsDragging) { 8850 if (coords == null) { 8851 coords = mTempCoords; 8852 TextView.this.getLocationInWindow(coords); 8853 } 8854 if (coords[0] != mLastParentX || coords[1] != mLastParentY) { 8855 mTouchToWindowOffsetX += coords[0] - mLastParentX; 8856 mTouchToWindowOffsetY += coords[1] - mLastParentY; 8857 mLastParentX = coords[0]; 8858 mLastParentY = coords[1]; 8859 } 8860 // Hide paste popup window as soon as the handle is dragged. 8861 if (mPastePopupWindow != null) { 8862 mPastePopupWindow.hide(); 8863 } 8864 } 8865 } else { 8866 hide(); 8867 } 8868 } 8869 8870 @Override 8871 protected void onDraw(Canvas c) { 8872 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 8873 mDrawable.draw(c); 8874 } 8875 8876 @Override 8877 public boolean onTouchEvent(MotionEvent ev) { 8878 switch (ev.getActionMasked()) { 8879 case MotionEvent.ACTION_DOWN: { 8880 startTouchUpFilter(mController.getCurrentOffset(this)); 8881 mDownPositionX = ev.getRawX(); 8882 mDownPositionY = ev.getRawY(); 8883 mTouchToWindowOffsetX = mDownPositionX - mPositionX; 8884 mTouchToWindowOffsetY = mDownPositionY - mPositionY; 8885 final int[] coords = mTempCoords; 8886 TextView.this.getLocationInWindow(coords); 8887 mLastParentX = coords[0]; 8888 mLastParentY = coords[1]; 8889 mIsDragging = true; 8890 if (mIsInsertionHandle) { 8891 mTouchTimer = SystemClock.uptimeMillis(); 8892 } 8893 break; 8894 } 8895 8896 case MotionEvent.ACTION_MOVE: { 8897 final float rawX = ev.getRawX(); 8898 final float rawY = ev.getRawY(); 8899 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 8900 final float newPosY = rawY - mTouchToWindowOffsetY + mHotspotY + mTouchOffsetY; 8901 8902 mController.updatePosition(this, Math.round(newPosX), Math.round(newPosY)); 8903 break; 8904 } 8905 8906 case MotionEvent.ACTION_UP: 8907 if (mIsInsertionHandle) { 8908 long delay = SystemClock.uptimeMillis() - mTouchTimer; 8909 if (delay < ViewConfiguration.getTapTimeout()) { 8910 if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) { 8911 // Tapping on the handle dismisses the displayed paste view, 8912 mPastePopupWindow.hide(); 8913 } else { 8914 ((InsertionPointCursorController) mController).show(0); 8915 } 8916 } 8917 } 8918 filterOnTouchUp(); 8919 mIsDragging = false; 8920 break; 8921 8922 case MotionEvent.ACTION_CANCEL: 8923 mIsDragging = false; 8924 break; 8925 } 8926 return true; 8927 } 8928 8929 public boolean isDragging() { 8930 return mIsDragging; 8931 } 8932 8933 void positionAtCursor(final int offset, boolean bottom) { 8934 addPositionToTouchUpFilter(offset); 8935 final int width = mDrawable.getIntrinsicWidth(); 8936 final int height = mDrawable.getIntrinsicHeight(); 8937 final int line = mLayout.getLineForOffset(offset); 8938 final int lineTop = mLayout.getLineTop(line); 8939 final int lineBottom = mLayout.getLineBottom(line); 8940 8941 final Rect bounds = sCursorControllerTempRect; 8942 bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - mHotspotX) 8943 + TextView.this.mScrollX; 8944 bounds.top = (bottom ? lineBottom : lineTop - mHeight) + TextView.this.mScrollY; 8945 8946 bounds.right = bounds.left + width; 8947 bounds.bottom = bounds.top + height; 8948 8949 convertFromViewportToContentCoordinates(bounds); 8950 moveTo(bounds.left, bounds.top); 8951 } 8952 8953 void showPastePopupWindow() { 8954 if (mIsInsertionHandle) { 8955 if (mPastePopupWindow == null) { 8956 // Lazy initialisation: create when actually shown only. 8957 mPastePopupWindow = new PastePopupMenu(); 8958 } 8959 mPastePopupWindow.show(); 8960 } 8961 } 8962 } 8963 8964 private class InsertionPointCursorController implements CursorController { 8965 private static final int DELAY_BEFORE_FADE_OUT = 4100; 8966 private static final int DELAY_BEFORE_PASTE = 2000; 8967 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; 8968 8969 // The cursor controller image. Lazily created. 8970 private HandleView mHandle; 8971 private Runnable mHider; 8972 private Runnable mPastePopupShower; 8973 8974 public void show() { 8975 show(DELAY_BEFORE_PASTE); 8976 } 8977 8978 public void show(int delayBeforePaste) { 8979 updatePosition(); 8980 hideDelayed(); 8981 getHandle().show(); 8982 removePastePopupCallback(); 8983 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 8984 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 8985 delayBeforePaste = 0; 8986 } 8987 if (delayBeforePaste == 0 || canPaste()) { 8988 if (mPastePopupShower == null) { 8989 mPastePopupShower = new Runnable() { 8990 public void run() { 8991 getHandle().showPastePopupWindow(); 8992 } 8993 }; 8994 } 8995 postDelayed(mPastePopupShower, delayBeforePaste); 8996 } 8997 } 8998 8999 private void removePastePopupCallback() { 9000 if (mPastePopupShower != null) { 9001 removeCallbacks(mPastePopupShower); 9002 } 9003 } 9004 9005 private void removeHiderCallback() { 9006 if (mHider != null) { 9007 removeCallbacks(mHider); 9008 } 9009 } 9010 9011 public void hide() { 9012 if (mHandle != null) { 9013 mHandle.hide(); 9014 } 9015 removeHiderCallback(); 9016 removePastePopupCallback(); 9017 } 9018 9019 private void hideDelayed() { 9020 removeHiderCallback(); 9021 if (mHider == null) { 9022 mHider = new Runnable() { 9023 public void run() { 9024 hide(); 9025 } 9026 }; 9027 } 9028 postDelayed(mHider, DELAY_BEFORE_FADE_OUT); 9029 } 9030 9031 public boolean isShowing() { 9032 return mHandle != null && mHandle.isShowing(); 9033 } 9034 9035 public void updatePosition(HandleView handle, int x, int y) { 9036 final int previousOffset = getSelectionStart(); 9037 int offset = getHysteresisOffset(x, y, previousOffset); 9038 9039 if (offset != previousOffset) { 9040 updateOffset(handle, offset); 9041 removePastePopupCallback(); 9042 } 9043 hideDelayed(); 9044 } 9045 9046 public void updateOffset(HandleView handle, int offset) { 9047 Selection.setSelection((Spannable) mText, offset); 9048 updatePosition(); 9049 } 9050 9051 public void updatePosition() { 9052 final int offset = getSelectionStart(); 9053 9054 if (offset < 0) { 9055 // Should never happen, safety check. 9056 Log.w(LOG_TAG, "Update cursor controller position called with no cursor"); 9057 hide(); 9058 return; 9059 } 9060 9061 getHandle().positionAtCursor(offset, true); 9062 } 9063 9064 public int getCurrentOffset(HandleView handle) { 9065 return getSelectionStart(); 9066 } 9067 9068 public boolean onTouchEvent(MotionEvent ev) { 9069 return false; 9070 } 9071 9072 public void onTouchModeChanged(boolean isInTouchMode) { 9073 if (!isInTouchMode) { 9074 hide(); 9075 } 9076 } 9077 9078 private HandleView getHandle() { 9079 if (mHandle == null) { 9080 mHandle = new HandleView(this, HandleView.CENTER); 9081 } 9082 return mHandle; 9083 } 9084 9085 @Override 9086 public void onDetached() { 9087 removeHiderCallback(); 9088 removePastePopupCallback(); 9089 } 9090 } 9091 9092 private class SelectionModifierCursorController implements CursorController { 9093 // The cursor controller images, lazily created when shown. 9094 private HandleView mStartHandle, mEndHandle; 9095 // The offsets of that last touch down event. Remembered to start selection there. 9096 private int mMinTouchOffset, mMaxTouchOffset; 9097 // Whether selection anchors are active 9098 private boolean mIsShowing; 9099 9100 // Double tap detection 9101 private long mPreviousTapUpTime = 0; 9102 private int mPreviousTapPositionX; 9103 private int mPreviousTapPositionY; 9104 9105 SelectionModifierCursorController() { 9106 resetTouchOffsets(); 9107 } 9108 9109 public void show() { 9110 if (isInBatchEditMode()) { 9111 return; 9112 } 9113 9114 // Lazy object creation has to be done before updatePosition() is called. 9115 if (mStartHandle == null) mStartHandle = new HandleView(this, HandleView.LEFT); 9116 if (mEndHandle == null) mEndHandle = new HandleView(this, HandleView.RIGHT); 9117 9118 mIsShowing = true; 9119 updatePosition(); 9120 9121 mStartHandle.show(); 9122 mEndHandle.show(); 9123 9124 hideInsertionPointCursorController(); 9125 } 9126 9127 public void hide() { 9128 if (mStartHandle != null) mStartHandle.hide(); 9129 if (mEndHandle != null) mEndHandle.hide(); 9130 mIsShowing = false; 9131 } 9132 9133 public boolean isShowing() { 9134 return mIsShowing; 9135 } 9136 9137 public void cancelFadeOutAnimation() { 9138 hide(); 9139 } 9140 9141 public void updatePosition(HandleView handle, int x, int y) { 9142 int selectionStart = getSelectionStart(); 9143 int selectionEnd = getSelectionEnd(); 9144 9145 final int previousOffset = handle == mStartHandle ? selectionStart : selectionEnd; 9146 int offset = getHysteresisOffset(x, y, previousOffset); 9147 9148 // Handle the case where start and end are swapped, making sure start <= end 9149 if (handle == mStartHandle) { 9150 if (selectionStart == offset || offset > selectionEnd) { 9151 return; // no change, no need to redraw; 9152 } 9153 // If the user "closes" the selection entirely they were probably trying to 9154 // select a single character. Help them out. 9155 if (offset == selectionEnd) { 9156 offset = selectionEnd - 1; 9157 } 9158 selectionStart = offset; 9159 } else { 9160 if (selectionEnd == offset || offset < selectionStart) { 9161 return; // no change, no need to redraw; 9162 } 9163 // If the user "closes" the selection entirely they were probably trying to 9164 // select a single character. Help them out. 9165 if (offset == selectionStart) { 9166 offset = selectionStart + 1; 9167 } 9168 selectionEnd = offset; 9169 } 9170 9171 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 9172 updatePosition(); 9173 } 9174 9175 public void updateOffset(HandleView handle, int offset) { 9176 int start = getSelectionStart(); 9177 int end = getSelectionEnd(); 9178 9179 if (mStartHandle == handle) { 9180 start = offset; 9181 } else { 9182 end = offset; 9183 } 9184 9185 Selection.setSelection((Spannable) mText, start, end); 9186 updatePosition(); 9187 } 9188 9189 public void updatePosition() { 9190 if (!isShowing()) { 9191 return; 9192 } 9193 9194 final int selectionStart = getSelectionStart(); 9195 final int selectionEnd = getSelectionEnd(); 9196 9197 if ((selectionStart < 0) || (selectionEnd < 0)) { 9198 // Should never happen, safety check. 9199 Log.w(LOG_TAG, "Update selection controller position called with no cursor"); 9200 hide(); 9201 return; 9202 } 9203 9204 // The handles have been created since the controller isShowing(). 9205 mStartHandle.positionAtCursor(selectionStart, true); 9206 mEndHandle.positionAtCursor(selectionEnd, true); 9207 } 9208 9209 public int getCurrentOffset(HandleView handle) { 9210 return mStartHandle == handle ? getSelectionStart() : getSelectionEnd(); 9211 } 9212 9213 public boolean onTouchEvent(MotionEvent event) { 9214 // This is done even when the View does not have focus, so that long presses can start 9215 // selection and tap can move cursor from this tap position. 9216 if (isTextEditable() || mTextIsSelectable) { 9217 switch (event.getActionMasked()) { 9218 case MotionEvent.ACTION_DOWN: 9219 final int x = (int) event.getX(); 9220 final int y = (int) event.getY(); 9221 9222 // Remember finger down position, to be able to start selection from there 9223 mMinTouchOffset = mMaxTouchOffset = getOffset(x, y); 9224 9225 // Double tap detection 9226 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 9227 if (duration <= ViewConfiguration.getDoubleTapTimeout() && 9228 isPositionOnText(x, y)) { 9229 final int deltaX = x - mPreviousTapPositionX; 9230 final int deltaY = y - mPreviousTapPositionY; 9231 final int distanceSquared = deltaX * deltaX + deltaY * deltaY; 9232 if (distanceSquared < mSquaredTouchSlopDistance) { 9233 startSelectionActionMode(); 9234 mDiscardNextActionUp = true; 9235 } 9236 } 9237 9238 mPreviousTapPositionX = x; 9239 mPreviousTapPositionY = y; 9240 9241 break; 9242 9243 case MotionEvent.ACTION_POINTER_DOWN: 9244 case MotionEvent.ACTION_POINTER_UP: 9245 // Handle multi-point gestures. Keep min and max offset positions. 9246 // Only activated for devices that correctly handle multi-touch. 9247 if (mContext.getPackageManager().hasSystemFeature( 9248 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 9249 updateMinAndMaxOffsets(event); 9250 } 9251 break; 9252 9253 case MotionEvent.ACTION_UP: 9254 mPreviousTapUpTime = SystemClock.uptimeMillis(); 9255 break; 9256 } 9257 } 9258 return false; 9259 } 9260 9261 /** 9262 * @param event 9263 */ 9264 private void updateMinAndMaxOffsets(MotionEvent event) { 9265 int pointerCount = event.getPointerCount(); 9266 for (int index = 0; index < pointerCount; index++) { 9267 final int x = (int) event.getX(index); 9268 final int y = (int) event.getY(index); 9269 int offset = getOffset(x, y); 9270 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 9271 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 9272 } 9273 } 9274 9275 public int getMinTouchOffset() { 9276 return mMinTouchOffset; 9277 } 9278 9279 public int getMaxTouchOffset() { 9280 return mMaxTouchOffset; 9281 } 9282 9283 public void resetTouchOffsets() { 9284 mMinTouchOffset = mMaxTouchOffset = -1; 9285 } 9286 9287 /** 9288 * @return true iff this controller is currently used to move the selection start. 9289 */ 9290 public boolean isSelectionStartDragged() { 9291 return mStartHandle != null && mStartHandle.isDragging(); 9292 } 9293 9294 public void onTouchModeChanged(boolean isInTouchMode) { 9295 if (!isInTouchMode) { 9296 hide(); 9297 } 9298 } 9299 9300 @Override 9301 public void onDetached() {} 9302 } 9303 9304 private void hideInsertionPointCursorController() { 9305 // No need to create the controller to hide it. 9306 if (mInsertionPointCursorController != null) { 9307 mInsertionPointCursorController.hide(); 9308 } 9309 } 9310 9311 /** 9312 * Hides the insertion controller and stops text selection mode, hiding the selection controller 9313 */ 9314 private void hideControllers() { 9315 hideInsertionPointCursorController(); 9316 stopSelectionActionMode(); 9317 } 9318 9319 /** 9320 * Get the offset character closest to the specified absolute position. 9321 * 9322 * @param x The horizontal absolute position of a point on screen 9323 * @param y The vertical absolute position of a point on screen 9324 * @return the character offset for the character whose position is closest to the specified 9325 * position. Returns -1 if there is no layout. 9326 * 9327 * @hide 9328 */ 9329 public int getOffset(int x, int y) { 9330 if (getLayout() == null) return -1; 9331 final int line = getLineAtCoordinate(y); 9332 final int offset = getOffsetAtCoordinate(line, x); 9333 return offset; 9334 } 9335 9336 int getHysteresisOffset(int x, int y, int previousOffset) { 9337 final Layout layout = getLayout(); 9338 if (layout == null) return -1; 9339 9340 int line = getLineAtCoordinate(y); 9341 final int previousLine = layout.getLineForOffset(previousOffset); 9342 final int previousLineTop = layout.getLineTop(previousLine); 9343 final int previousLineBottom = layout.getLineBottom(previousLine); 9344 final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 8; 9345 9346 // If new line is just before or after previous line and y position is less than 9347 // hysteresisThreshold away from previous line, keep cursor on previous line. 9348 if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) || 9349 ((line == previousLine - 1) && ((previousLineTop - y) < hysteresisThreshold))) { 9350 line = previousLine; 9351 } 9352 9353 return getOffsetAtCoordinate(line, x); 9354 } 9355 9356 private int convertToLocalHorizontalCoordinate(int x) { 9357 x -= getTotalPaddingLeft(); 9358 // Clamp the position to inside of the view. 9359 x = Math.max(0, x); 9360 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 9361 x += getScrollX(); 9362 return x; 9363 } 9364 9365 private int getLineAtCoordinate(int y) { 9366 y -= getTotalPaddingTop(); 9367 // Clamp the position to inside of the view. 9368 y = Math.max(0, y); 9369 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 9370 y += getScrollY(); 9371 return getLayout().getLineForVertical(y); 9372 } 9373 9374 private int getOffsetAtCoordinate(int line, int x) { 9375 x = convertToLocalHorizontalCoordinate(x); 9376 return getLayout().getOffsetForHorizontal(line, x); 9377 } 9378 9379 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 9380 * in the view. Returns false when the position is in the empty space of left/right of text. 9381 */ 9382 private boolean isPositionOnText(int x, int y) { 9383 if (getLayout() == null) return false; 9384 9385 final int line = getLineAtCoordinate(y); 9386 x = convertToLocalHorizontalCoordinate(x); 9387 9388 if (x < getLayout().getLineLeft(line)) return false; 9389 if (x > getLayout().getLineRight(line)) return false; 9390 return true; 9391 } 9392 9393 @Override 9394 public boolean onDragEvent(DragEvent event) { 9395 switch (event.getAction()) { 9396 case DragEvent.ACTION_DRAG_STARTED: 9397 return hasInsertionController(); 9398 9399 case DragEvent.ACTION_DRAG_ENTERED: 9400 TextView.this.requestFocus(); 9401 return true; 9402 9403 case DragEvent.ACTION_DRAG_LOCATION: 9404 final int offset = getOffset((int) event.getX(), (int) event.getY()); 9405 Selection.setSelection((Spannable)mText, offset); 9406 return true; 9407 9408 case DragEvent.ACTION_DROP: 9409 onDrop(event); 9410 return true; 9411 9412 case DragEvent.ACTION_DRAG_ENDED: 9413 case DragEvent.ACTION_DRAG_EXITED: 9414 default: 9415 return true; 9416 } 9417 } 9418 9419 private void onDrop(DragEvent event) { 9420 StringBuilder content = new StringBuilder(""); 9421 ClipData clipData = event.getClipData(); 9422 final int itemCount = clipData.getItemCount(); 9423 for (int i=0; i < itemCount; i++) { 9424 Item item = clipData.getItemAt(i); 9425 content.append(item.coerceToText(TextView.this.mContext)); 9426 } 9427 9428 final int offset = getOffset((int) event.getX(), (int) event.getY()); 9429 9430 Object localState = event.getLocalState(); 9431 DragLocalState dragLocalState = null; 9432 if (localState instanceof DragLocalState) { 9433 dragLocalState = (DragLocalState) localState; 9434 } 9435 boolean dragDropIntoItself = dragLocalState != null && 9436 dragLocalState.sourceTextView == this; 9437 9438 if (dragDropIntoItself) { 9439 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 9440 // A drop inside the original selection discards the drop. 9441 return; 9442 } 9443 } 9444 9445 final int originalLength = mText.length(); 9446 long minMax = prepareSpacesAroundPaste(offset, offset, content); 9447 int min = extractRangeStartFromLong(minMax); 9448 int max = extractRangeEndFromLong(minMax); 9449 9450 Selection.setSelection((Spannable) mText, max); 9451 ((Editable) mText).replace(min, max, content); 9452 9453 if (dragDropIntoItself) { 9454 int dragSourceStart = dragLocalState.start; 9455 int dragSourceEnd = dragLocalState.end; 9456 if (max <= dragSourceStart) { 9457 // Inserting text before selection has shifted positions 9458 final int shift = mText.length() - originalLength; 9459 dragSourceStart += shift; 9460 dragSourceEnd += shift; 9461 } 9462 9463 // Delete original selection 9464 ((Editable) mText).delete(dragSourceStart, dragSourceEnd); 9465 9466 // Make sure we do not leave two adjacent spaces. 9467 if ((dragSourceStart == 0 || 9468 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 9469 (dragSourceStart == mText.length() || 9470 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 9471 final int pos = dragSourceStart == mText.length() ? 9472 dragSourceStart - 1 : dragSourceStart; 9473 ((Editable) mText).delete(pos, pos + 1); 9474 } 9475 } 9476 } 9477 9478 /** 9479 * @return True if this view supports insertion handles. 9480 */ 9481 boolean hasInsertionController() { 9482 return mInsertionControllerEnabled; 9483 } 9484 9485 /** 9486 * @return True if this view supports selection handles. 9487 */ 9488 boolean hasSelectionController() { 9489 return mSelectionControllerEnabled; 9490 } 9491 9492 InsertionPointCursorController getInsertionController() { 9493 if (!mInsertionControllerEnabled) { 9494 return null; 9495 } 9496 9497 if (mInsertionPointCursorController == null) { 9498 mInsertionPointCursorController = new InsertionPointCursorController(); 9499 9500 final ViewTreeObserver observer = getViewTreeObserver(); 9501 if (observer != null) { 9502 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 9503 } 9504 } 9505 9506 return mInsertionPointCursorController; 9507 } 9508 9509 SelectionModifierCursorController getSelectionController() { 9510 if (!mSelectionControllerEnabled) { 9511 return null; 9512 } 9513 9514 if (mSelectionModifierCursorController == null) { 9515 mSelectionModifierCursorController = new SelectionModifierCursorController(); 9516 9517 final ViewTreeObserver observer = getViewTreeObserver(); 9518 if (observer != null) { 9519 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 9520 } 9521 } 9522 9523 return mSelectionModifierCursorController; 9524 } 9525 9526 boolean isInBatchEditMode() { 9527 final InputMethodState ims = mInputMethodState; 9528 if (ims != null) { 9529 return ims.mBatchEditNesting > 0; 9530 } 9531 return mInBatchEditControllers; 9532 } 9533 9534 @ViewDebug.ExportedProperty(category = "text") 9535 private CharSequence mText; 9536 private CharSequence mTransformed; 9537 private BufferType mBufferType = BufferType.NORMAL; 9538 9539 private int mInputType = EditorInfo.TYPE_NULL; 9540 private CharSequence mHint; 9541 private Layout mHintLayout; 9542 9543 private KeyListener mInput; 9544 9545 private MovementMethod mMovement; 9546 private TransformationMethod mTransformation; 9547 private ChangeWatcher mChangeWatcher; 9548 9549 private ArrayList<TextWatcher> mListeners = null; 9550 9551 // display attributes 9552 private final TextPaint mTextPaint; 9553 private boolean mUserSetTextScaleX; 9554 private final Paint mHighlightPaint; 9555 private int mHighlightColor = 0xCC475925; 9556 /** 9557 * This is temporarily visible to fix bug 3085564 in webView. Do not rely on 9558 * this field being protected. Will be restored as private when lineHeight 9559 * feature request 3215097 is implemented 9560 * @hide 9561 */ 9562 protected Layout mLayout; 9563 9564 private long mShowCursor; 9565 private Blink mBlink; 9566 private boolean mCursorVisible = true; 9567 9568 // Cursor Controllers. 9569 private InsertionPointCursorController mInsertionPointCursorController; 9570 private SelectionModifierCursorController mSelectionModifierCursorController; 9571 private ActionMode mSelectionActionMode; 9572 private boolean mInsertionControllerEnabled; 9573 private boolean mSelectionControllerEnabled; 9574 private boolean mInBatchEditControllers; 9575 9576 // These are needed to desambiguate a long click. If the long click comes from ones of these, we 9577 // select from the current cursor position. Otherwise, select from long pressed position. 9578 private boolean mDPadCenterIsDown = false; 9579 private boolean mEnterKeyIsDown = false; 9580 private boolean mContextMenuTriggeredByKey = false; 9581 // Created once and shared by different CursorController helper methods. 9582 // Only one cursor controller is active at any time which prevent race conditions. 9583 private static Rect sCursorControllerTempRect = new Rect(); 9584 9585 private boolean mSelectAllOnFocus = false; 9586 9587 private int mGravity = Gravity.TOP | Gravity.LEFT; 9588 private boolean mHorizontallyScrolling; 9589 9590 private int mAutoLinkMask; 9591 private boolean mLinksClickable = true; 9592 9593 private float mSpacingMult = 1; 9594 private float mSpacingAdd = 0; 9595 private boolean mTextIsSelectable = false; 9596 9597 private static final int LINES = 1; 9598 private static final int EMS = LINES; 9599 private static final int PIXELS = 2; 9600 9601 private int mMaximum = Integer.MAX_VALUE; 9602 private int mMaxMode = LINES; 9603 private int mMinimum = 0; 9604 private int mMinMode = LINES; 9605 9606 private int mMaxWidth = Integer.MAX_VALUE; 9607 private int mMaxWidthMode = PIXELS; 9608 private int mMinWidth = 0; 9609 private int mMinWidthMode = PIXELS; 9610 9611 private boolean mSingleLine; 9612 private int mDesiredHeightAtMeasure = -1; 9613 private boolean mIncludePad = true; 9614 9615 // tmp primitives, so we don't alloc them on each draw 9616 private Path mHighlightPath; 9617 private boolean mHighlightPathBogus = true; 9618 private static final RectF sTempRect = new RectF(); 9619 9620 // XXX should be much larger 9621 private static final int VERY_WIDE = 16384; 9622 9623 private static final int BLINK = 500; 9624 9625 private static final int ANIMATED_SCROLL_GAP = 250; 9626 private long mLastScroll; 9627 private Scroller mScroller = null; 9628 9629 private BoringLayout.Metrics mBoring; 9630 private BoringLayout.Metrics mHintBoring; 9631 9632 private BoringLayout mSavedLayout, mSavedHintLayout; 9633 9634 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 9635 private InputFilter[] mFilters = NO_FILTERS; 9636 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 9637 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 9638 // System wide time for last cut or copy action. 9639 private static long sLastCutOrCopyTime; 9640 // Used to highlight a word when it is corrected by the IME 9641 private CorrectionHighlighter mCorrectionHighlighter; 9642 // New state used to change background based on whether this TextView is multiline. 9643 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 9644} 9645