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