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