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