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