TextView.java revision 904fcdad411817fcd12c3e8b9e708b0c27bd6007
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 static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH; 20import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX; 21import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY; 22import static android.view.inputmethod.CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION; 23 24import android.R; 25import android.annotation.CheckResult; 26import android.annotation.ColorInt; 27import android.annotation.DrawableRes; 28import android.annotation.FloatRange; 29import android.annotation.IntDef; 30import android.annotation.IntRange; 31import android.annotation.NonNull; 32import android.annotation.Nullable; 33import android.annotation.Px; 34import android.annotation.Size; 35import android.annotation.StringRes; 36import android.annotation.StyleRes; 37import android.annotation.XmlRes; 38import android.app.Activity; 39import android.app.assist.AssistStructure; 40import android.content.ClipData; 41import android.content.ClipDescription; 42import android.content.ClipboardManager; 43import android.content.Context; 44import android.content.Intent; 45import android.content.UndoManager; 46import android.content.res.ColorStateList; 47import android.content.res.CompatibilityInfo; 48import android.content.res.Configuration; 49import android.content.res.ResourceId; 50import android.content.res.Resources; 51import android.content.res.TypedArray; 52import android.content.res.XmlResourceParser; 53import android.graphics.BaseCanvas; 54import android.graphics.Canvas; 55import android.graphics.Insets; 56import android.graphics.Paint; 57import android.graphics.Paint.FontMetricsInt; 58import android.graphics.Path; 59import android.graphics.PorterDuff; 60import android.graphics.Rect; 61import android.graphics.RectF; 62import android.graphics.Typeface; 63import android.graphics.drawable.Drawable; 64import android.graphics.fonts.FontVariationAxis; 65import android.icu.text.DecimalFormatSymbols; 66import android.os.AsyncTask; 67import android.os.Build.VERSION_CODES; 68import android.os.Bundle; 69import android.os.LocaleList; 70import android.os.Parcel; 71import android.os.Parcelable; 72import android.os.ParcelableParcel; 73import android.os.SystemClock; 74import android.provider.Settings; 75import android.text.BoringLayout; 76import android.text.DynamicLayout; 77import android.text.Editable; 78import android.text.GetChars; 79import android.text.GraphicsOperations; 80import android.text.InputFilter; 81import android.text.InputType; 82import android.text.Layout; 83import android.text.ParcelableSpan; 84import android.text.PrecomputedText; 85import android.text.Selection; 86import android.text.SpanWatcher; 87import android.text.Spannable; 88import android.text.SpannableStringBuilder; 89import android.text.Spanned; 90import android.text.SpannedString; 91import android.text.StaticLayout; 92import android.text.TextDirectionHeuristic; 93import android.text.TextDirectionHeuristics; 94import android.text.TextPaint; 95import android.text.TextUtils; 96import android.text.TextUtils.TruncateAt; 97import android.text.TextWatcher; 98import android.text.method.AllCapsTransformationMethod; 99import android.text.method.ArrowKeyMovementMethod; 100import android.text.method.DateKeyListener; 101import android.text.method.DateTimeKeyListener; 102import android.text.method.DialerKeyListener; 103import android.text.method.DigitsKeyListener; 104import android.text.method.KeyListener; 105import android.text.method.LinkMovementMethod; 106import android.text.method.MetaKeyKeyListener; 107import android.text.method.MovementMethod; 108import android.text.method.PasswordTransformationMethod; 109import android.text.method.SingleLineTransformationMethod; 110import android.text.method.TextKeyListener; 111import android.text.method.TimeKeyListener; 112import android.text.method.TransformationMethod; 113import android.text.method.TransformationMethod2; 114import android.text.method.WordIterator; 115import android.text.style.CharacterStyle; 116import android.text.style.ClickableSpan; 117import android.text.style.ParagraphStyle; 118import android.text.style.SpellCheckSpan; 119import android.text.style.SuggestionSpan; 120import android.text.style.URLSpan; 121import android.text.style.UpdateAppearance; 122import android.text.util.Linkify; 123import android.util.AttributeSet; 124import android.util.DisplayMetrics; 125import android.util.IntArray; 126import android.util.Log; 127import android.util.SparseIntArray; 128import android.util.TypedValue; 129import android.view.AccessibilityIterators.TextSegmentIterator; 130import android.view.ActionMode; 131import android.view.Choreographer; 132import android.view.ContextMenu; 133import android.view.DragEvent; 134import android.view.Gravity; 135import android.view.HapticFeedbackConstants; 136import android.view.InputDevice; 137import android.view.KeyCharacterMap; 138import android.view.KeyEvent; 139import android.view.MotionEvent; 140import android.view.PointerIcon; 141import android.view.View; 142import android.view.ViewConfiguration; 143import android.view.ViewDebug; 144import android.view.ViewGroup.LayoutParams; 145import android.view.ViewHierarchyEncoder; 146import android.view.ViewParent; 147import android.view.ViewRootImpl; 148import android.view.ViewStructure; 149import android.view.ViewTreeObserver; 150import android.view.accessibility.AccessibilityEvent; 151import android.view.accessibility.AccessibilityManager; 152import android.view.accessibility.AccessibilityNodeInfo; 153import android.view.animation.AnimationUtils; 154import android.view.autofill.AutofillManager; 155import android.view.autofill.AutofillValue; 156import android.view.inputmethod.BaseInputConnection; 157import android.view.inputmethod.CompletionInfo; 158import android.view.inputmethod.CorrectionInfo; 159import android.view.inputmethod.CursorAnchorInfo; 160import android.view.inputmethod.EditorInfo; 161import android.view.inputmethod.ExtractedText; 162import android.view.inputmethod.ExtractedTextRequest; 163import android.view.inputmethod.InputConnection; 164import android.view.inputmethod.InputMethodManager; 165import android.view.textclassifier.TextClassificationManager; 166import android.view.textclassifier.TextClassifier; 167import android.view.textclassifier.TextLinks; 168import android.view.textservice.SpellCheckerSubtype; 169import android.view.textservice.TextServicesManager; 170import android.widget.RemoteViews.RemoteView; 171 172import com.android.internal.annotations.VisibleForTesting; 173import com.android.internal.logging.MetricsLogger; 174import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 175import com.android.internal.util.FastMath; 176import com.android.internal.util.Preconditions; 177import com.android.internal.widget.EditableInputConnection; 178 179import libcore.util.EmptyArray; 180 181import org.xmlpull.v1.XmlPullParserException; 182 183import java.io.IOException; 184import java.lang.annotation.Retention; 185import java.lang.annotation.RetentionPolicy; 186import java.lang.ref.WeakReference; 187import java.util.ArrayList; 188import java.util.Arrays; 189import java.util.Locale; 190 191/** 192 * A user interface element that displays text to the user. 193 * To provide user-editable text, see {@link EditText}. 194 * <p> 195 * The following code sample shows a typical use, with an XML layout 196 * and code to modify the contents of the text view: 197 * </p> 198 199 * <pre> 200 * <LinearLayout 201 xmlns:android="http://schemas.android.com/apk/res/android" 202 android:layout_width="match_parent" 203 android:layout_height="match_parent"> 204 * <TextView 205 * android:id="@+id/text_view_id" 206 * android:layout_height="wrap_content" 207 * android:layout_width="wrap_content" 208 * android:text="@string/hello" /> 209 * </LinearLayout> 210 * </pre> 211 * <p> 212 * This code sample demonstrates how to modify the contents of the text view 213 * defined in the previous XML layout: 214 * </p> 215 * <pre> 216 * public class MainActivity extends Activity { 217 * 218 * protected void onCreate(Bundle savedInstanceState) { 219 * super.onCreate(savedInstanceState); 220 * setContentView(R.layout.activity_main); 221 * final TextView helloTextView = (TextView) findViewById(R.id.text_view_id); 222 * helloTextView.setText(R.string.user_greeting); 223 * } 224 * } 225 * </pre> 226 * <p> 227 * To customize the appearance of TextView, see <a href="https://developer.android.com/guide/topics/ui/themes.html">Styles and Themes</a>. 228 * </p> 229 * <p> 230 * <b>XML attributes</b> 231 * <p> 232 * See {@link android.R.styleable#TextView TextView Attributes}, 233 * {@link android.R.styleable#View View Attributes} 234 * 235 * @attr ref android.R.styleable#TextView_text 236 * @attr ref android.R.styleable#TextView_bufferType 237 * @attr ref android.R.styleable#TextView_hint 238 * @attr ref android.R.styleable#TextView_textColor 239 * @attr ref android.R.styleable#TextView_textColorHighlight 240 * @attr ref android.R.styleable#TextView_textColorHint 241 * @attr ref android.R.styleable#TextView_textAppearance 242 * @attr ref android.R.styleable#TextView_textColorLink 243 * @attr ref android.R.styleable#TextView_textSize 244 * @attr ref android.R.styleable#TextView_textScaleX 245 * @attr ref android.R.styleable#TextView_fontFamily 246 * @attr ref android.R.styleable#TextView_typeface 247 * @attr ref android.R.styleable#TextView_textStyle 248 * @attr ref android.R.styleable#TextView_cursorVisible 249 * @attr ref android.R.styleable#TextView_maxLines 250 * @attr ref android.R.styleable#TextView_maxHeight 251 * @attr ref android.R.styleable#TextView_lines 252 * @attr ref android.R.styleable#TextView_height 253 * @attr ref android.R.styleable#TextView_minLines 254 * @attr ref android.R.styleable#TextView_minHeight 255 * @attr ref android.R.styleable#TextView_maxEms 256 * @attr ref android.R.styleable#TextView_maxWidth 257 * @attr ref android.R.styleable#TextView_ems 258 * @attr ref android.R.styleable#TextView_width 259 * @attr ref android.R.styleable#TextView_minEms 260 * @attr ref android.R.styleable#TextView_minWidth 261 * @attr ref android.R.styleable#TextView_gravity 262 * @attr ref android.R.styleable#TextView_scrollHorizontally 263 * @attr ref android.R.styleable#TextView_password 264 * @attr ref android.R.styleable#TextView_singleLine 265 * @attr ref android.R.styleable#TextView_selectAllOnFocus 266 * @attr ref android.R.styleable#TextView_includeFontPadding 267 * @attr ref android.R.styleable#TextView_maxLength 268 * @attr ref android.R.styleable#TextView_shadowColor 269 * @attr ref android.R.styleable#TextView_shadowDx 270 * @attr ref android.R.styleable#TextView_shadowDy 271 * @attr ref android.R.styleable#TextView_shadowRadius 272 * @attr ref android.R.styleable#TextView_autoLink 273 * @attr ref android.R.styleable#TextView_linksClickable 274 * @attr ref android.R.styleable#TextView_numeric 275 * @attr ref android.R.styleable#TextView_digits 276 * @attr ref android.R.styleable#TextView_phoneNumber 277 * @attr ref android.R.styleable#TextView_inputMethod 278 * @attr ref android.R.styleable#TextView_capitalize 279 * @attr ref android.R.styleable#TextView_autoText 280 * @attr ref android.R.styleable#TextView_editable 281 * @attr ref android.R.styleable#TextView_freezesText 282 * @attr ref android.R.styleable#TextView_ellipsize 283 * @attr ref android.R.styleable#TextView_drawableTop 284 * @attr ref android.R.styleable#TextView_drawableBottom 285 * @attr ref android.R.styleable#TextView_drawableRight 286 * @attr ref android.R.styleable#TextView_drawableLeft 287 * @attr ref android.R.styleable#TextView_drawableStart 288 * @attr ref android.R.styleable#TextView_drawableEnd 289 * @attr ref android.R.styleable#TextView_drawablePadding 290 * @attr ref android.R.styleable#TextView_drawableTint 291 * @attr ref android.R.styleable#TextView_drawableTintMode 292 * @attr ref android.R.styleable#TextView_lineSpacingExtra 293 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 294 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 295 * @attr ref android.R.styleable#TextView_inputType 296 * @attr ref android.R.styleable#TextView_imeOptions 297 * @attr ref android.R.styleable#TextView_privateImeOptions 298 * @attr ref android.R.styleable#TextView_imeActionLabel 299 * @attr ref android.R.styleable#TextView_imeActionId 300 * @attr ref android.R.styleable#TextView_editorExtras 301 * @attr ref android.R.styleable#TextView_elegantTextHeight 302 * @attr ref android.R.styleable#TextView_fallbackLineSpacing 303 * @attr ref android.R.styleable#TextView_letterSpacing 304 * @attr ref android.R.styleable#TextView_fontFeatureSettings 305 * @attr ref android.R.styleable#TextView_breakStrategy 306 * @attr ref android.R.styleable#TextView_hyphenationFrequency 307 * @attr ref android.R.styleable#TextView_autoSizeTextType 308 * @attr ref android.R.styleable#TextView_autoSizeMinTextSize 309 * @attr ref android.R.styleable#TextView_autoSizeMaxTextSize 310 * @attr ref android.R.styleable#TextView_autoSizeStepGranularity 311 * @attr ref android.R.styleable#TextView_autoSizePresetSizes 312 * @attr ref android.R.styleable#TextView_accessibilityHeading 313 */ 314@RemoteView 315public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { 316 static final String LOG_TAG = "TextView"; 317 static final boolean DEBUG_EXTRACT = false; 318 private static final float[] TEMP_POSITION = new float[2]; 319 320 // Enum for the "typeface" XML parameter. 321 // TODO: How can we get this from the XML instead of hardcoding it here? 322 /** @hide */ 323 @IntDef(value = {DEFAULT_TYPEFACE, SANS, SERIF, MONOSPACE}) 324 @Retention(RetentionPolicy.SOURCE) 325 public @interface XMLTypefaceAttr{} 326 private static final int DEFAULT_TYPEFACE = -1; 327 private static final int SANS = 1; 328 private static final int SERIF = 2; 329 private static final int MONOSPACE = 3; 330 331 // Enum for the "ellipsize" XML parameter. 332 private static final int ELLIPSIZE_NOT_SET = -1; 333 private static final int ELLIPSIZE_NONE = 0; 334 private static final int ELLIPSIZE_START = 1; 335 private static final int ELLIPSIZE_MIDDLE = 2; 336 private static final int ELLIPSIZE_END = 3; 337 private static final int ELLIPSIZE_MARQUEE = 4; 338 339 // Bitfield for the "numeric" XML parameter. 340 // TODO: How can we get this from the XML instead of hardcoding it here? 341 private static final int SIGNED = 2; 342 private static final int DECIMAL = 4; 343 344 /** 345 * Draw marquee text with fading edges as usual 346 */ 347 private static final int MARQUEE_FADE_NORMAL = 0; 348 349 /** 350 * Draw marquee text as ellipsize end while inactive instead of with the fade. 351 * (Useful for devices where the fade can be expensive if overdone) 352 */ 353 private static final int MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS = 1; 354 355 /** 356 * Draw marquee text with fading edges because it is currently active/animating. 357 */ 358 private static final int MARQUEE_FADE_SWITCH_SHOW_FADE = 2; 359 360 private static final int LINES = 1; 361 private static final int EMS = LINES; 362 private static final int PIXELS = 2; 363 364 private static final RectF TEMP_RECTF = new RectF(); 365 366 /** @hide */ 367 static final int VERY_WIDE = 1024 * 1024; // XXX should be much larger 368 private static final int ANIMATED_SCROLL_GAP = 250; 369 370 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 371 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 372 373 private static final int CHANGE_WATCHER_PRIORITY = 100; 374 375 // New state used to change background based on whether this TextView is multiline. 376 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 377 378 // Accessibility action to share selected text. 379 private static final int ACCESSIBILITY_ACTION_SHARE = 0x10000000; 380 381 /** 382 * @hide 383 */ 384 // Accessibility action start id for "process text" actions. 385 static final int ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID = 0x10000100; 386 387 /** 388 * @hide 389 */ 390 static final int PROCESS_TEXT_REQUEST_CODE = 100; 391 392 /** 393 * Return code of {@link #doKeyDown}. 394 */ 395 private static final int KEY_EVENT_NOT_HANDLED = 0; 396 private static final int KEY_EVENT_HANDLED = -1; 397 private static final int KEY_DOWN_HANDLED_BY_KEY_LISTENER = 1; 398 private static final int KEY_DOWN_HANDLED_BY_MOVEMENT_METHOD = 2; 399 400 private static final int FLOATING_TOOLBAR_SELECT_ALL_REFRESH_DELAY = 500; 401 402 // System wide time for last cut, copy or text changed action. 403 static long sLastCutCopyOrTextChangedTime; 404 405 private ColorStateList mTextColor; 406 private ColorStateList mHintTextColor; 407 private ColorStateList mLinkTextColor; 408 @ViewDebug.ExportedProperty(category = "text") 409 private int mCurTextColor; 410 private int mCurHintTextColor; 411 private boolean mFreezesText; 412 private boolean mIsAccessibilityHeading; 413 414 private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); 415 private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); 416 417 private float mShadowRadius, mShadowDx, mShadowDy; 418 private int mShadowColor; 419 420 private boolean mPreDrawRegistered; 421 private boolean mPreDrawListenerDetached; 422 423 private TextClassifier mTextClassifier; 424 425 // A flag to prevent repeated movements from escaping the enclosing text view. The idea here is 426 // that if a user is holding down a movement key to traverse text, we shouldn't also traverse 427 // the view hierarchy. On the other hand, if the user is using the movement key to traverse 428 // views (i.e. the first movement was to traverse out of this view, or this view was traversed 429 // into by the user holding the movement key down) then we shouldn't prevent the focus from 430 // changing. 431 private boolean mPreventDefaultMovement; 432 433 private TextUtils.TruncateAt mEllipsize; 434 435 static class Drawables { 436 static final int LEFT = 0; 437 static final int TOP = 1; 438 static final int RIGHT = 2; 439 static final int BOTTOM = 3; 440 441 static final int DRAWABLE_NONE = -1; 442 static final int DRAWABLE_RIGHT = 0; 443 static final int DRAWABLE_LEFT = 1; 444 445 final Rect mCompoundRect = new Rect(); 446 447 final Drawable[] mShowing = new Drawable[4]; 448 449 ColorStateList mTintList; 450 PorterDuff.Mode mTintMode; 451 boolean mHasTint; 452 boolean mHasTintMode; 453 454 Drawable mDrawableStart, mDrawableEnd, mDrawableError, mDrawableTemp; 455 Drawable mDrawableLeftInitial, mDrawableRightInitial; 456 457 boolean mIsRtlCompatibilityMode; 458 boolean mOverride; 459 460 int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight, 461 mDrawableSizeStart, mDrawableSizeEnd, mDrawableSizeError, mDrawableSizeTemp; 462 463 int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight, 464 mDrawableHeightStart, mDrawableHeightEnd, mDrawableHeightError, mDrawableHeightTemp; 465 466 int mDrawablePadding; 467 468 int mDrawableSaved = DRAWABLE_NONE; 469 470 public Drawables(Context context) { 471 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 472 mIsRtlCompatibilityMode = targetSdkVersion < VERSION_CODES.JELLY_BEAN_MR1 473 || !context.getApplicationInfo().hasRtlSupport(); 474 mOverride = false; 475 } 476 477 /** 478 * @return {@code true} if this object contains metadata that needs to 479 * be retained, {@code false} otherwise 480 */ 481 public boolean hasMetadata() { 482 return mDrawablePadding != 0 || mHasTintMode || mHasTint; 483 } 484 485 /** 486 * Updates the list of displayed drawables to account for the current 487 * layout direction. 488 * 489 * @param layoutDirection the current layout direction 490 * @return {@code true} if the displayed drawables changed 491 */ 492 public boolean resolveWithLayoutDirection(int layoutDirection) { 493 final Drawable previousLeft = mShowing[Drawables.LEFT]; 494 final Drawable previousRight = mShowing[Drawables.RIGHT]; 495 496 // First reset "left" and "right" drawables to their initial values 497 mShowing[Drawables.LEFT] = mDrawableLeftInitial; 498 mShowing[Drawables.RIGHT] = mDrawableRightInitial; 499 500 if (mIsRtlCompatibilityMode) { 501 // Use "start" drawable as "left" drawable if the "left" drawable was not defined 502 if (mDrawableStart != null && mShowing[Drawables.LEFT] == null) { 503 mShowing[Drawables.LEFT] = mDrawableStart; 504 mDrawableSizeLeft = mDrawableSizeStart; 505 mDrawableHeightLeft = mDrawableHeightStart; 506 } 507 // Use "end" drawable as "right" drawable if the "right" drawable was not defined 508 if (mDrawableEnd != null && mShowing[Drawables.RIGHT] == null) { 509 mShowing[Drawables.RIGHT] = mDrawableEnd; 510 mDrawableSizeRight = mDrawableSizeEnd; 511 mDrawableHeightRight = mDrawableHeightEnd; 512 } 513 } else { 514 // JB-MR1+ normal case: "start" / "end" drawables are overriding "left" / "right" 515 // drawable if and only if they have been defined 516 switch(layoutDirection) { 517 case LAYOUT_DIRECTION_RTL: 518 if (mOverride) { 519 mShowing[Drawables.RIGHT] = mDrawableStart; 520 mDrawableSizeRight = mDrawableSizeStart; 521 mDrawableHeightRight = mDrawableHeightStart; 522 523 mShowing[Drawables.LEFT] = mDrawableEnd; 524 mDrawableSizeLeft = mDrawableSizeEnd; 525 mDrawableHeightLeft = mDrawableHeightEnd; 526 } 527 break; 528 529 case LAYOUT_DIRECTION_LTR: 530 default: 531 if (mOverride) { 532 mShowing[Drawables.LEFT] = mDrawableStart; 533 mDrawableSizeLeft = mDrawableSizeStart; 534 mDrawableHeightLeft = mDrawableHeightStart; 535 536 mShowing[Drawables.RIGHT] = mDrawableEnd; 537 mDrawableSizeRight = mDrawableSizeEnd; 538 mDrawableHeightRight = mDrawableHeightEnd; 539 } 540 break; 541 } 542 } 543 544 applyErrorDrawableIfNeeded(layoutDirection); 545 546 return mShowing[Drawables.LEFT] != previousLeft 547 || mShowing[Drawables.RIGHT] != previousRight; 548 } 549 550 public void setErrorDrawable(Drawable dr, TextView tv) { 551 if (mDrawableError != dr && mDrawableError != null) { 552 mDrawableError.setCallback(null); 553 } 554 mDrawableError = dr; 555 556 if (mDrawableError != null) { 557 final Rect compoundRect = mCompoundRect; 558 final int[] state = tv.getDrawableState(); 559 560 mDrawableError.setState(state); 561 mDrawableError.copyBounds(compoundRect); 562 mDrawableError.setCallback(tv); 563 mDrawableSizeError = compoundRect.width(); 564 mDrawableHeightError = compoundRect.height(); 565 } else { 566 mDrawableSizeError = mDrawableHeightError = 0; 567 } 568 } 569 570 private void applyErrorDrawableIfNeeded(int layoutDirection) { 571 // first restore the initial state if needed 572 switch (mDrawableSaved) { 573 case DRAWABLE_LEFT: 574 mShowing[Drawables.LEFT] = mDrawableTemp; 575 mDrawableSizeLeft = mDrawableSizeTemp; 576 mDrawableHeightLeft = mDrawableHeightTemp; 577 break; 578 case DRAWABLE_RIGHT: 579 mShowing[Drawables.RIGHT] = mDrawableTemp; 580 mDrawableSizeRight = mDrawableSizeTemp; 581 mDrawableHeightRight = mDrawableHeightTemp; 582 break; 583 case DRAWABLE_NONE: 584 default: 585 } 586 // then, if needed, assign the Error drawable to the correct location 587 if (mDrawableError != null) { 588 switch(layoutDirection) { 589 case LAYOUT_DIRECTION_RTL: 590 mDrawableSaved = DRAWABLE_LEFT; 591 592 mDrawableTemp = mShowing[Drawables.LEFT]; 593 mDrawableSizeTemp = mDrawableSizeLeft; 594 mDrawableHeightTemp = mDrawableHeightLeft; 595 596 mShowing[Drawables.LEFT] = mDrawableError; 597 mDrawableSizeLeft = mDrawableSizeError; 598 mDrawableHeightLeft = mDrawableHeightError; 599 break; 600 case LAYOUT_DIRECTION_LTR: 601 default: 602 mDrawableSaved = DRAWABLE_RIGHT; 603 604 mDrawableTemp = mShowing[Drawables.RIGHT]; 605 mDrawableSizeTemp = mDrawableSizeRight; 606 mDrawableHeightTemp = mDrawableHeightRight; 607 608 mShowing[Drawables.RIGHT] = mDrawableError; 609 mDrawableSizeRight = mDrawableSizeError; 610 mDrawableHeightRight = mDrawableHeightError; 611 break; 612 } 613 } 614 } 615 } 616 617 Drawables mDrawables; 618 619 private CharWrapper mCharWrapper; 620 621 private Marquee mMarquee; 622 private boolean mRestartMarquee; 623 624 private int mMarqueeRepeatLimit = 3; 625 626 private int mLastLayoutDirection = -1; 627 628 /** 629 * On some devices the fading edges add a performance penalty if used 630 * extensively in the same layout. This mode indicates how the marquee 631 * is currently being shown, if applicable. (mEllipsize will == MARQUEE) 632 */ 633 private int mMarqueeFadeMode = MARQUEE_FADE_NORMAL; 634 635 /** 636 * When mMarqueeFadeMode is not MARQUEE_FADE_NORMAL, this stores 637 * the layout that should be used when the mode switches. 638 */ 639 private Layout mSavedMarqueeModeLayout; 640 641 @ViewDebug.ExportedProperty(category = "text") 642 private CharSequence mText; 643 private CharSequence mTransformed; 644 private BufferType mBufferType = BufferType.NORMAL; 645 646 private CharSequence mHint; 647 private Layout mHintLayout; 648 649 private MovementMethod mMovement; 650 651 private TransformationMethod mTransformation; 652 private boolean mAllowTransformationLengthChange; 653 private ChangeWatcher mChangeWatcher; 654 655 private ArrayList<TextWatcher> mListeners; 656 657 // display attributes 658 private final TextPaint mTextPaint; 659 private boolean mUserSetTextScaleX; 660 private Layout mLayout; 661 private boolean mLocalesChanged = false; 662 663 // True if setKeyListener() has been explicitly called 664 private boolean mListenerChanged = false; 665 // True if internationalized input should be used for numbers and date and time. 666 private final boolean mUseInternationalizedInput; 667 // True if fallback fonts that end up getting used should be allowed to affect line spacing. 668 /* package */ boolean mUseFallbackLineSpacing; 669 670 @ViewDebug.ExportedProperty(category = "text") 671 private int mGravity = Gravity.TOP | Gravity.START; 672 private boolean mHorizontallyScrolling; 673 674 private int mAutoLinkMask; 675 private boolean mLinksClickable = true; 676 677 private float mSpacingMult = 1.0f; 678 private float mSpacingAdd = 0.0f; 679 680 private int mBreakStrategy; 681 private int mHyphenationFrequency; 682 private int mJustificationMode; 683 684 private int mMaximum = Integer.MAX_VALUE; 685 private int mMaxMode = LINES; 686 private int mMinimum = 0; 687 private int mMinMode = LINES; 688 689 private int mOldMaximum = mMaximum; 690 private int mOldMaxMode = mMaxMode; 691 692 private int mMaxWidth = Integer.MAX_VALUE; 693 private int mMaxWidthMode = PIXELS; 694 private int mMinWidth = 0; 695 private int mMinWidthMode = PIXELS; 696 697 private boolean mSingleLine; 698 private int mDesiredHeightAtMeasure = -1; 699 private boolean mIncludePad = true; 700 private int mDeferScroll = -1; 701 702 // tmp primitives, so we don't alloc them on each draw 703 private Rect mTempRect; 704 private long mLastScroll; 705 private Scroller mScroller; 706 private TextPaint mTempTextPaint; 707 708 private BoringLayout.Metrics mBoring, mHintBoring; 709 private BoringLayout mSavedLayout, mSavedHintLayout; 710 711 private TextDirectionHeuristic mTextDir; 712 713 private InputFilter[] mFilters = NO_FILTERS; 714 715 private volatile Locale mCurrentSpellCheckerLocaleCache; 716 717 // It is possible to have a selection even when mEditor is null (programmatically set, like when 718 // a link is pressed). These highlight-related fields do not go in mEditor. 719 int mHighlightColor = 0x6633B5E5; 720 private Path mHighlightPath; 721 private final Paint mHighlightPaint; 722 private boolean mHighlightPathBogus = true; 723 724 // Although these fields are specific to editable text, they are not added to Editor because 725 // they are defined by the TextView's style and are theme-dependent. 726 int mCursorDrawableRes; 727 // These six fields, could be moved to Editor, since we know their default values and we 728 // could condition the creation of the Editor to a non standard value. This is however 729 // brittle since the hardcoded values here (such as 730 // com.android.internal.R.drawable.text_select_handle_left) would have to be updated if the 731 // default style is modified. 732 int mTextSelectHandleLeftRes; 733 int mTextSelectHandleRightRes; 734 int mTextSelectHandleRes; 735 int mTextEditSuggestionItemLayout; 736 int mTextEditSuggestionContainerLayout; 737 int mTextEditSuggestionHighlightStyle; 738 739 /** 740 * {@link EditText} specific data, created on demand when one of the Editor fields is used. 741 * See {@link #createEditorIfNeeded()}. 742 */ 743 private Editor mEditor; 744 745 private static final int DEVICE_PROVISIONED_UNKNOWN = 0; 746 private static final int DEVICE_PROVISIONED_NO = 1; 747 private static final int DEVICE_PROVISIONED_YES = 2; 748 749 /** 750 * Some special options such as sharing selected text should only be shown if the device 751 * is provisioned. Only check the provisioned state once for a given view instance. 752 */ 753 private int mDeviceProvisionedState = DEVICE_PROVISIONED_UNKNOWN; 754 755 /** 756 * The TextView does not auto-size text (default). 757 */ 758 public static final int AUTO_SIZE_TEXT_TYPE_NONE = 0; 759 760 /** 761 * The TextView scales text size both horizontally and vertically to fit within the 762 * container. 763 */ 764 public static final int AUTO_SIZE_TEXT_TYPE_UNIFORM = 1; 765 766 /** @hide */ 767 @IntDef(prefix = { "AUTO_SIZE_TEXT_TYPE_" }, value = { 768 AUTO_SIZE_TEXT_TYPE_NONE, 769 AUTO_SIZE_TEXT_TYPE_UNIFORM 770 }) 771 @Retention(RetentionPolicy.SOURCE) 772 public @interface AutoSizeTextType {} 773 // Default minimum size for auto-sizing text in scaled pixels. 774 private static final int DEFAULT_AUTO_SIZE_MIN_TEXT_SIZE_IN_SP = 12; 775 // Default maximum size for auto-sizing text in scaled pixels. 776 private static final int DEFAULT_AUTO_SIZE_MAX_TEXT_SIZE_IN_SP = 112; 777 // Default value for the step size in pixels. 778 private static final int DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX = 1; 779 // Use this to specify that any of the auto-size configuration int values have not been set. 780 private static final float UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE = -1f; 781 // Auto-size text type. 782 private int mAutoSizeTextType = AUTO_SIZE_TEXT_TYPE_NONE; 783 // Specify if auto-size text is needed. 784 private boolean mNeedsAutoSizeText = false; 785 // Step size for auto-sizing in pixels. 786 private float mAutoSizeStepGranularityInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 787 // Minimum text size for auto-sizing in pixels. 788 private float mAutoSizeMinTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 789 // Maximum text size for auto-sizing in pixels. 790 private float mAutoSizeMaxTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 791 // Contains a (specified or computed) distinct sorted set of text sizes in pixels to pick from 792 // when auto-sizing text. 793 private int[] mAutoSizeTextSizesInPx = EmptyArray.INT; 794 // Specifies whether auto-size should use the provided auto size steps set or if it should 795 // build the steps set using mAutoSizeMinTextSizeInPx, mAutoSizeMaxTextSizeInPx and 796 // mAutoSizeStepGranularityInPx. 797 private boolean mHasPresetAutoSizeValues = false; 798 799 // Autofill-related attributes 800 // 801 // Indicates whether the text was set statically or dynamically, so it can be used to 802 // sanitize autofill requests. 803 private boolean mTextSetFromXmlOrResourceId = false; 804 // Resource id used to set the text. 805 private @StringRes int mTextId = ResourceId.ID_NULL; 806 // Last value used on AFM.notifyValueChanged(), used to optimize autofill workflow by avoiding 807 // calls when the value did not change 808 private CharSequence mLastValueSentToAutofillManager; 809 // 810 // End of autofill-related attributes 811 812 /** 813 * Kick-start the font cache for the zygote process (to pay the cost of 814 * initializing freetype for our default font only once). 815 * @hide 816 */ 817 public static void preloadFontCache() { 818 Paint p = new Paint(); 819 p.setAntiAlias(true); 820 // Ensure that the Typeface is loaded here. 821 // Typically, Typeface is preloaded by zygote but not on all devices, e.g. Android Auto. 822 // So, sets Typeface.DEFAULT explicitly here for ensuring that the Typeface is loaded here 823 // since Paint.measureText can not be called without Typeface static initializer. 824 p.setTypeface(Typeface.DEFAULT); 825 // We don't care about the result, just the side-effect of measuring. 826 p.measureText("H"); 827 } 828 829 /** 830 * Interface definition for a callback to be invoked when an action is 831 * performed on the editor. 832 */ 833 public interface OnEditorActionListener { 834 /** 835 * Called when an action is being performed. 836 * 837 * @param v The view that was clicked. 838 * @param actionId Identifier of the action. This will be either the 839 * identifier you supplied, or {@link EditorInfo#IME_NULL 840 * EditorInfo.IME_NULL} if being called due to the enter key 841 * being pressed. 842 * @param event If triggered by an enter key, this is the event; 843 * otherwise, this is null. 844 * @return Return true if you have consumed the action, else false. 845 */ 846 boolean onEditorAction(TextView v, int actionId, KeyEvent event); 847 } 848 849 public TextView(Context context) { 850 this(context, null); 851 } 852 853 public TextView(Context context, @Nullable AttributeSet attrs) { 854 this(context, attrs, com.android.internal.R.attr.textViewStyle); 855 } 856 857 public TextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { 858 this(context, attrs, defStyleAttr, 0); 859 } 860 861 @SuppressWarnings("deprecation") 862 public TextView( 863 Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { 864 super(context, attrs, defStyleAttr, defStyleRes); 865 866 // TextView is important by default, unless app developer overrode attribute. 867 if (getImportantForAutofill() == IMPORTANT_FOR_AUTOFILL_AUTO) { 868 setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES); 869 } 870 871 mText = ""; 872 873 final Resources res = getResources(); 874 final CompatibilityInfo compat = res.getCompatibilityInfo(); 875 876 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 877 mTextPaint.density = res.getDisplayMetrics().density; 878 mTextPaint.setCompatibilityScaling(compat.applicationScale); 879 880 mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 881 mHighlightPaint.setCompatibilityScaling(compat.applicationScale); 882 883 mMovement = getDefaultMovementMethod(); 884 885 mTransformation = null; 886 887 final TextAppearanceAttributes attributes = new TextAppearanceAttributes(); 888 attributes.mTextColor = ColorStateList.valueOf(0xFF000000); 889 attributes.mTextSize = 15; 890 mBreakStrategy = Layout.BREAK_STRATEGY_SIMPLE; 891 mHyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE; 892 mJustificationMode = Layout.JUSTIFICATION_MODE_NONE; 893 894 final Resources.Theme theme = context.getTheme(); 895 896 /* 897 * Look the appearance up without checking first if it exists because 898 * almost every TextView has one and it greatly simplifies the logic 899 * to be able to parse the appearance first and then let specific tags 900 * for this View override it. 901 */ 902 TypedArray a = theme.obtainStyledAttributes(attrs, 903 com.android.internal.R.styleable.TextViewAppearance, defStyleAttr, defStyleRes); 904 TypedArray appearance = null; 905 int ap = a.getResourceId( 906 com.android.internal.R.styleable.TextViewAppearance_textAppearance, -1); 907 a.recycle(); 908 if (ap != -1) { 909 appearance = theme.obtainStyledAttributes( 910 ap, com.android.internal.R.styleable.TextAppearance); 911 } 912 if (appearance != null) { 913 readTextAppearance(context, appearance, attributes, false /* styleArray */); 914 attributes.mFontFamilyExplicit = false; 915 appearance.recycle(); 916 } 917 918 boolean editable = getDefaultEditable(); 919 CharSequence inputMethod = null; 920 int numeric = 0; 921 CharSequence digits = null; 922 boolean phone = false; 923 boolean autotext = false; 924 int autocap = -1; 925 int buffertype = 0; 926 boolean selectallonfocus = false; 927 Drawable drawableLeft = null, drawableTop = null, drawableRight = null, 928 drawableBottom = null, drawableStart = null, drawableEnd = null; 929 ColorStateList drawableTint = null; 930 PorterDuff.Mode drawableTintMode = null; 931 int drawablePadding = 0; 932 int ellipsize = ELLIPSIZE_NOT_SET; 933 boolean singleLine = false; 934 int maxlength = -1; 935 CharSequence text = ""; 936 CharSequence hint = null; 937 boolean password = false; 938 float autoSizeMinTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 939 float autoSizeMaxTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 940 float autoSizeStepGranularityInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 941 int inputType = EditorInfo.TYPE_NULL; 942 a = theme.obtainStyledAttributes( 943 attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes); 944 int firstBaselineToTopHeight = -1; 945 int lastBaselineToBottomHeight = -1; 946 int lineHeight = -1; 947 948 readTextAppearance(context, a, attributes, true /* styleArray */); 949 950 int n = a.getIndexCount(); 951 952 // Must set id in a temporary variable because it will be reset by setText() 953 boolean textIsSetFromXml = false; 954 for (int i = 0; i < n; i++) { 955 int attr = a.getIndex(i); 956 957 switch (attr) { 958 case com.android.internal.R.styleable.TextView_editable: 959 editable = a.getBoolean(attr, editable); 960 break; 961 962 case com.android.internal.R.styleable.TextView_inputMethod: 963 inputMethod = a.getText(attr); 964 break; 965 966 case com.android.internal.R.styleable.TextView_numeric: 967 numeric = a.getInt(attr, numeric); 968 break; 969 970 case com.android.internal.R.styleable.TextView_digits: 971 digits = a.getText(attr); 972 break; 973 974 case com.android.internal.R.styleable.TextView_phoneNumber: 975 phone = a.getBoolean(attr, phone); 976 break; 977 978 case com.android.internal.R.styleable.TextView_autoText: 979 autotext = a.getBoolean(attr, autotext); 980 break; 981 982 case com.android.internal.R.styleable.TextView_capitalize: 983 autocap = a.getInt(attr, autocap); 984 break; 985 986 case com.android.internal.R.styleable.TextView_bufferType: 987 buffertype = a.getInt(attr, buffertype); 988 break; 989 990 case com.android.internal.R.styleable.TextView_selectAllOnFocus: 991 selectallonfocus = a.getBoolean(attr, selectallonfocus); 992 break; 993 994 case com.android.internal.R.styleable.TextView_autoLink: 995 mAutoLinkMask = a.getInt(attr, 0); 996 break; 997 998 case com.android.internal.R.styleable.TextView_linksClickable: 999 mLinksClickable = a.getBoolean(attr, true); 1000 break; 1001 1002 case com.android.internal.R.styleable.TextView_drawableLeft: 1003 drawableLeft = a.getDrawable(attr); 1004 break; 1005 1006 case com.android.internal.R.styleable.TextView_drawableTop: 1007 drawableTop = a.getDrawable(attr); 1008 break; 1009 1010 case com.android.internal.R.styleable.TextView_drawableRight: 1011 drawableRight = a.getDrawable(attr); 1012 break; 1013 1014 case com.android.internal.R.styleable.TextView_drawableBottom: 1015 drawableBottom = a.getDrawable(attr); 1016 break; 1017 1018 case com.android.internal.R.styleable.TextView_drawableStart: 1019 drawableStart = a.getDrawable(attr); 1020 break; 1021 1022 case com.android.internal.R.styleable.TextView_drawableEnd: 1023 drawableEnd = a.getDrawable(attr); 1024 break; 1025 1026 case com.android.internal.R.styleable.TextView_drawableTint: 1027 drawableTint = a.getColorStateList(attr); 1028 break; 1029 1030 case com.android.internal.R.styleable.TextView_drawableTintMode: 1031 drawableTintMode = Drawable.parseTintMode(a.getInt(attr, -1), drawableTintMode); 1032 break; 1033 1034 case com.android.internal.R.styleable.TextView_drawablePadding: 1035 drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); 1036 break; 1037 1038 case com.android.internal.R.styleable.TextView_maxLines: 1039 setMaxLines(a.getInt(attr, -1)); 1040 break; 1041 1042 case com.android.internal.R.styleable.TextView_maxHeight: 1043 setMaxHeight(a.getDimensionPixelSize(attr, -1)); 1044 break; 1045 1046 case com.android.internal.R.styleable.TextView_lines: 1047 setLines(a.getInt(attr, -1)); 1048 break; 1049 1050 case com.android.internal.R.styleable.TextView_height: 1051 setHeight(a.getDimensionPixelSize(attr, -1)); 1052 break; 1053 1054 case com.android.internal.R.styleable.TextView_minLines: 1055 setMinLines(a.getInt(attr, -1)); 1056 break; 1057 1058 case com.android.internal.R.styleable.TextView_minHeight: 1059 setMinHeight(a.getDimensionPixelSize(attr, -1)); 1060 break; 1061 1062 case com.android.internal.R.styleable.TextView_maxEms: 1063 setMaxEms(a.getInt(attr, -1)); 1064 break; 1065 1066 case com.android.internal.R.styleable.TextView_maxWidth: 1067 setMaxWidth(a.getDimensionPixelSize(attr, -1)); 1068 break; 1069 1070 case com.android.internal.R.styleable.TextView_ems: 1071 setEms(a.getInt(attr, -1)); 1072 break; 1073 1074 case com.android.internal.R.styleable.TextView_width: 1075 setWidth(a.getDimensionPixelSize(attr, -1)); 1076 break; 1077 1078 case com.android.internal.R.styleable.TextView_minEms: 1079 setMinEms(a.getInt(attr, -1)); 1080 break; 1081 1082 case com.android.internal.R.styleable.TextView_minWidth: 1083 setMinWidth(a.getDimensionPixelSize(attr, -1)); 1084 break; 1085 1086 case com.android.internal.R.styleable.TextView_gravity: 1087 setGravity(a.getInt(attr, -1)); 1088 break; 1089 1090 case com.android.internal.R.styleable.TextView_hint: 1091 hint = a.getText(attr); 1092 break; 1093 1094 case com.android.internal.R.styleable.TextView_text: 1095 textIsSetFromXml = true; 1096 mTextId = a.getResourceId(attr, ResourceId.ID_NULL); 1097 text = a.getText(attr); 1098 break; 1099 1100 case com.android.internal.R.styleable.TextView_scrollHorizontally: 1101 if (a.getBoolean(attr, false)) { 1102 setHorizontallyScrolling(true); 1103 } 1104 break; 1105 1106 case com.android.internal.R.styleable.TextView_singleLine: 1107 singleLine = a.getBoolean(attr, singleLine); 1108 break; 1109 1110 case com.android.internal.R.styleable.TextView_ellipsize: 1111 ellipsize = a.getInt(attr, ellipsize); 1112 break; 1113 1114 case com.android.internal.R.styleable.TextView_marqueeRepeatLimit: 1115 setMarqueeRepeatLimit(a.getInt(attr, mMarqueeRepeatLimit)); 1116 break; 1117 1118 case com.android.internal.R.styleable.TextView_includeFontPadding: 1119 if (!a.getBoolean(attr, true)) { 1120 setIncludeFontPadding(false); 1121 } 1122 break; 1123 1124 case com.android.internal.R.styleable.TextView_cursorVisible: 1125 if (!a.getBoolean(attr, true)) { 1126 setCursorVisible(false); 1127 } 1128 break; 1129 1130 case com.android.internal.R.styleable.TextView_maxLength: 1131 maxlength = a.getInt(attr, -1); 1132 break; 1133 1134 case com.android.internal.R.styleable.TextView_textScaleX: 1135 setTextScaleX(a.getFloat(attr, 1.0f)); 1136 break; 1137 1138 case com.android.internal.R.styleable.TextView_freezesText: 1139 mFreezesText = a.getBoolean(attr, false); 1140 break; 1141 1142 case com.android.internal.R.styleable.TextView_enabled: 1143 setEnabled(a.getBoolean(attr, isEnabled())); 1144 break; 1145 1146 case com.android.internal.R.styleable.TextView_password: 1147 password = a.getBoolean(attr, password); 1148 break; 1149 1150 case com.android.internal.R.styleable.TextView_lineSpacingExtra: 1151 mSpacingAdd = a.getDimensionPixelSize(attr, (int) mSpacingAdd); 1152 break; 1153 1154 case com.android.internal.R.styleable.TextView_lineSpacingMultiplier: 1155 mSpacingMult = a.getFloat(attr, mSpacingMult); 1156 break; 1157 1158 case com.android.internal.R.styleable.TextView_inputType: 1159 inputType = a.getInt(attr, EditorInfo.TYPE_NULL); 1160 break; 1161 1162 case com.android.internal.R.styleable.TextView_allowUndo: 1163 createEditorIfNeeded(); 1164 mEditor.mAllowUndo = a.getBoolean(attr, true); 1165 break; 1166 1167 case com.android.internal.R.styleable.TextView_imeOptions: 1168 createEditorIfNeeded(); 1169 mEditor.createInputContentTypeIfNeeded(); 1170 mEditor.mInputContentType.imeOptions = a.getInt(attr, 1171 mEditor.mInputContentType.imeOptions); 1172 break; 1173 1174 case com.android.internal.R.styleable.TextView_imeActionLabel: 1175 createEditorIfNeeded(); 1176 mEditor.createInputContentTypeIfNeeded(); 1177 mEditor.mInputContentType.imeActionLabel = a.getText(attr); 1178 break; 1179 1180 case com.android.internal.R.styleable.TextView_imeActionId: 1181 createEditorIfNeeded(); 1182 mEditor.createInputContentTypeIfNeeded(); 1183 mEditor.mInputContentType.imeActionId = a.getInt(attr, 1184 mEditor.mInputContentType.imeActionId); 1185 break; 1186 1187 case com.android.internal.R.styleable.TextView_privateImeOptions: 1188 setPrivateImeOptions(a.getString(attr)); 1189 break; 1190 1191 case com.android.internal.R.styleable.TextView_editorExtras: 1192 try { 1193 setInputExtras(a.getResourceId(attr, 0)); 1194 } catch (XmlPullParserException e) { 1195 Log.w(LOG_TAG, "Failure reading input extras", e); 1196 } catch (IOException e) { 1197 Log.w(LOG_TAG, "Failure reading input extras", e); 1198 } 1199 break; 1200 1201 case com.android.internal.R.styleable.TextView_textCursorDrawable: 1202 mCursorDrawableRes = a.getResourceId(attr, 0); 1203 break; 1204 1205 case com.android.internal.R.styleable.TextView_textSelectHandleLeft: 1206 mTextSelectHandleLeftRes = a.getResourceId(attr, 0); 1207 break; 1208 1209 case com.android.internal.R.styleable.TextView_textSelectHandleRight: 1210 mTextSelectHandleRightRes = a.getResourceId(attr, 0); 1211 break; 1212 1213 case com.android.internal.R.styleable.TextView_textSelectHandle: 1214 mTextSelectHandleRes = a.getResourceId(attr, 0); 1215 break; 1216 1217 case com.android.internal.R.styleable.TextView_textEditSuggestionItemLayout: 1218 mTextEditSuggestionItemLayout = a.getResourceId(attr, 0); 1219 break; 1220 1221 case com.android.internal.R.styleable.TextView_textEditSuggestionContainerLayout: 1222 mTextEditSuggestionContainerLayout = a.getResourceId(attr, 0); 1223 break; 1224 1225 case com.android.internal.R.styleable.TextView_textEditSuggestionHighlightStyle: 1226 mTextEditSuggestionHighlightStyle = a.getResourceId(attr, 0); 1227 break; 1228 1229 case com.android.internal.R.styleable.TextView_textIsSelectable: 1230 setTextIsSelectable(a.getBoolean(attr, false)); 1231 break; 1232 1233 case com.android.internal.R.styleable.TextView_breakStrategy: 1234 mBreakStrategy = a.getInt(attr, Layout.BREAK_STRATEGY_SIMPLE); 1235 break; 1236 1237 case com.android.internal.R.styleable.TextView_hyphenationFrequency: 1238 mHyphenationFrequency = a.getInt(attr, Layout.HYPHENATION_FREQUENCY_NONE); 1239 break; 1240 1241 case com.android.internal.R.styleable.TextView_autoSizeTextType: 1242 mAutoSizeTextType = a.getInt(attr, AUTO_SIZE_TEXT_TYPE_NONE); 1243 break; 1244 1245 case com.android.internal.R.styleable.TextView_autoSizeStepGranularity: 1246 autoSizeStepGranularityInPx = a.getDimension(attr, 1247 UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE); 1248 break; 1249 1250 case com.android.internal.R.styleable.TextView_autoSizeMinTextSize: 1251 autoSizeMinTextSizeInPx = a.getDimension(attr, 1252 UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE); 1253 break; 1254 1255 case com.android.internal.R.styleable.TextView_autoSizeMaxTextSize: 1256 autoSizeMaxTextSizeInPx = a.getDimension(attr, 1257 UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE); 1258 break; 1259 1260 case com.android.internal.R.styleable.TextView_autoSizePresetSizes: 1261 final int autoSizeStepSizeArrayResId = a.getResourceId(attr, 0); 1262 if (autoSizeStepSizeArrayResId > 0) { 1263 final TypedArray autoSizePresetTextSizes = a.getResources() 1264 .obtainTypedArray(autoSizeStepSizeArrayResId); 1265 setupAutoSizeUniformPresetSizes(autoSizePresetTextSizes); 1266 autoSizePresetTextSizes.recycle(); 1267 } 1268 break; 1269 case com.android.internal.R.styleable.TextView_justificationMode: 1270 mJustificationMode = a.getInt(attr, Layout.JUSTIFICATION_MODE_NONE); 1271 break; 1272 1273 case com.android.internal.R.styleable.TextView_firstBaselineToTopHeight: 1274 firstBaselineToTopHeight = a.getDimensionPixelSize(attr, -1); 1275 break; 1276 1277 case com.android.internal.R.styleable.TextView_lastBaselineToBottomHeight: 1278 lastBaselineToBottomHeight = a.getDimensionPixelSize(attr, -1); 1279 break; 1280 1281 case com.android.internal.R.styleable.TextView_lineHeight: 1282 lineHeight = a.getDimensionPixelSize(attr, -1); 1283 break; 1284 case com.android.internal.R.styleable.TextView_accessibilityHeading: 1285 mIsAccessibilityHeading = a.getBoolean(attr, false); 1286 } 1287 } 1288 1289 a.recycle(); 1290 1291 BufferType bufferType = BufferType.EDITABLE; 1292 1293 final int variation = 1294 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 1295 final boolean passwordInputType = variation 1296 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); 1297 final boolean webPasswordInputType = variation 1298 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD); 1299 final boolean numberPasswordInputType = variation 1300 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 1301 1302 final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion; 1303 mUseInternationalizedInput = targetSdkVersion >= VERSION_CODES.O; 1304 mUseFallbackLineSpacing = targetSdkVersion >= VERSION_CODES.P; 1305 1306 if (inputMethod != null) { 1307 Class<?> c; 1308 1309 try { 1310 c = Class.forName(inputMethod.toString()); 1311 } catch (ClassNotFoundException ex) { 1312 throw new RuntimeException(ex); 1313 } 1314 1315 try { 1316 createEditorIfNeeded(); 1317 mEditor.mKeyListener = (KeyListener) c.newInstance(); 1318 } catch (InstantiationException ex) { 1319 throw new RuntimeException(ex); 1320 } catch (IllegalAccessException ex) { 1321 throw new RuntimeException(ex); 1322 } 1323 try { 1324 mEditor.mInputType = inputType != EditorInfo.TYPE_NULL 1325 ? inputType 1326 : mEditor.mKeyListener.getInputType(); 1327 } catch (IncompatibleClassChangeError e) { 1328 mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; 1329 } 1330 } else if (digits != null) { 1331 createEditorIfNeeded(); 1332 mEditor.mKeyListener = DigitsKeyListener.getInstance(digits.toString()); 1333 // If no input type was specified, we will default to generic 1334 // text, since we can't tell the IME about the set of digits 1335 // that was selected. 1336 mEditor.mInputType = inputType != EditorInfo.TYPE_NULL 1337 ? inputType : EditorInfo.TYPE_CLASS_TEXT; 1338 } else if (inputType != EditorInfo.TYPE_NULL) { 1339 setInputType(inputType, true); 1340 // If set, the input type overrides what was set using the deprecated singleLine flag. 1341 singleLine = !isMultilineInputType(inputType); 1342 } else if (phone) { 1343 createEditorIfNeeded(); 1344 mEditor.mKeyListener = DialerKeyListener.getInstance(); 1345 mEditor.mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE; 1346 } else if (numeric != 0) { 1347 createEditorIfNeeded(); 1348 mEditor.mKeyListener = DigitsKeyListener.getInstance( 1349 null, // locale 1350 (numeric & SIGNED) != 0, 1351 (numeric & DECIMAL) != 0); 1352 inputType = mEditor.mKeyListener.getInputType(); 1353 mEditor.mInputType = inputType; 1354 } else if (autotext || autocap != -1) { 1355 TextKeyListener.Capitalize cap; 1356 1357 inputType = EditorInfo.TYPE_CLASS_TEXT; 1358 1359 switch (autocap) { 1360 case 1: 1361 cap = TextKeyListener.Capitalize.SENTENCES; 1362 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; 1363 break; 1364 1365 case 2: 1366 cap = TextKeyListener.Capitalize.WORDS; 1367 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; 1368 break; 1369 1370 case 3: 1371 cap = TextKeyListener.Capitalize.CHARACTERS; 1372 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; 1373 break; 1374 1375 default: 1376 cap = TextKeyListener.Capitalize.NONE; 1377 break; 1378 } 1379 1380 createEditorIfNeeded(); 1381 mEditor.mKeyListener = TextKeyListener.getInstance(autotext, cap); 1382 mEditor.mInputType = inputType; 1383 } else if (editable) { 1384 createEditorIfNeeded(); 1385 mEditor.mKeyListener = TextKeyListener.getInstance(); 1386 mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; 1387 } else if (isTextSelectable()) { 1388 // Prevent text changes from keyboard. 1389 if (mEditor != null) { 1390 mEditor.mKeyListener = null; 1391 mEditor.mInputType = EditorInfo.TYPE_NULL; 1392 } 1393 bufferType = BufferType.SPANNABLE; 1394 // So that selection can be changed using arrow keys and touch is handled. 1395 setMovementMethod(ArrowKeyMovementMethod.getInstance()); 1396 } else { 1397 if (mEditor != null) mEditor.mKeyListener = null; 1398 1399 switch (buffertype) { 1400 case 0: 1401 bufferType = BufferType.NORMAL; 1402 break; 1403 case 1: 1404 bufferType = BufferType.SPANNABLE; 1405 break; 1406 case 2: 1407 bufferType = BufferType.EDITABLE; 1408 break; 1409 } 1410 } 1411 1412 if (mEditor != null) { 1413 mEditor.adjustInputType(password, passwordInputType, webPasswordInputType, 1414 numberPasswordInputType); 1415 } 1416 1417 if (selectallonfocus) { 1418 createEditorIfNeeded(); 1419 mEditor.mSelectAllOnFocus = true; 1420 1421 if (bufferType == BufferType.NORMAL) { 1422 bufferType = BufferType.SPANNABLE; 1423 } 1424 } 1425 1426 // Set up the tint (if needed) before setting the drawables so that it 1427 // gets applied correctly. 1428 if (drawableTint != null || drawableTintMode != null) { 1429 if (mDrawables == null) { 1430 mDrawables = new Drawables(context); 1431 } 1432 if (drawableTint != null) { 1433 mDrawables.mTintList = drawableTint; 1434 mDrawables.mHasTint = true; 1435 } 1436 if (drawableTintMode != null) { 1437 mDrawables.mTintMode = drawableTintMode; 1438 mDrawables.mHasTintMode = true; 1439 } 1440 } 1441 1442 // This call will save the initial left/right drawables 1443 setCompoundDrawablesWithIntrinsicBounds( 1444 drawableLeft, drawableTop, drawableRight, drawableBottom); 1445 setRelativeDrawablesIfNeeded(drawableStart, drawableEnd); 1446 setCompoundDrawablePadding(drawablePadding); 1447 1448 // Same as setSingleLine(), but make sure the transformation method and the maximum number 1449 // of lines of height are unchanged for multi-line TextViews. 1450 setInputTypeSingleLine(singleLine); 1451 applySingleLine(singleLine, singleLine, singleLine); 1452 1453 if (singleLine && getKeyListener() == null && ellipsize == ELLIPSIZE_NOT_SET) { 1454 ellipsize = ELLIPSIZE_END; 1455 } 1456 1457 switch (ellipsize) { 1458 case ELLIPSIZE_START: 1459 setEllipsize(TextUtils.TruncateAt.START); 1460 break; 1461 case ELLIPSIZE_MIDDLE: 1462 setEllipsize(TextUtils.TruncateAt.MIDDLE); 1463 break; 1464 case ELLIPSIZE_END: 1465 setEllipsize(TextUtils.TruncateAt.END); 1466 break; 1467 case ELLIPSIZE_MARQUEE: 1468 if (ViewConfiguration.get(context).isFadingMarqueeEnabled()) { 1469 setHorizontalFadingEdgeEnabled(true); 1470 mMarqueeFadeMode = MARQUEE_FADE_NORMAL; 1471 } else { 1472 setHorizontalFadingEdgeEnabled(false); 1473 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 1474 } 1475 setEllipsize(TextUtils.TruncateAt.MARQUEE); 1476 break; 1477 } 1478 1479 final boolean isPassword = password || passwordInputType || webPasswordInputType 1480 || numberPasswordInputType; 1481 final boolean isMonospaceEnforced = isPassword || (mEditor != null 1482 && (mEditor.mInputType 1483 & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION)) 1484 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)); 1485 if (isMonospaceEnforced) { 1486 attributes.mTypefaceIndex = MONOSPACE; 1487 } 1488 1489 applyTextAppearance(attributes); 1490 1491 if (isPassword) { 1492 setTransformationMethod(PasswordTransformationMethod.getInstance()); 1493 } 1494 1495 if (maxlength >= 0) { 1496 setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) }); 1497 } else { 1498 setFilters(NO_FILTERS); 1499 } 1500 1501 setText(text, bufferType); 1502 if (textIsSetFromXml) { 1503 mTextSetFromXmlOrResourceId = true; 1504 } 1505 1506 if (hint != null) setHint(hint); 1507 1508 /* 1509 * Views are not normally clickable unless specified to be. 1510 * However, TextViews that have input or movement methods *are* 1511 * clickable by default. By setting clickable here, we implicitly set focusable as well 1512 * if not overridden by the developer. 1513 */ 1514 a = context.obtainStyledAttributes( 1515 attrs, com.android.internal.R.styleable.View, defStyleAttr, defStyleRes); 1516 boolean canInputOrMove = (mMovement != null || getKeyListener() != null); 1517 boolean clickable = canInputOrMove || isClickable(); 1518 boolean longClickable = canInputOrMove || isLongClickable(); 1519 int focusable = getFocusable(); 1520 1521 n = a.getIndexCount(); 1522 for (int i = 0; i < n; i++) { 1523 int attr = a.getIndex(i); 1524 1525 switch (attr) { 1526 case com.android.internal.R.styleable.View_focusable: 1527 TypedValue val = new TypedValue(); 1528 if (a.getValue(attr, val)) { 1529 focusable = (val.type == TypedValue.TYPE_INT_BOOLEAN) 1530 ? (val.data == 0 ? NOT_FOCUSABLE : FOCUSABLE) 1531 : val.data; 1532 } 1533 break; 1534 1535 case com.android.internal.R.styleable.View_clickable: 1536 clickable = a.getBoolean(attr, clickable); 1537 break; 1538 1539 case com.android.internal.R.styleable.View_longClickable: 1540 longClickable = a.getBoolean(attr, longClickable); 1541 break; 1542 } 1543 } 1544 a.recycle(); 1545 1546 // Some apps were relying on the undefined behavior of focusable winning over 1547 // focusableInTouchMode != focusable in TextViews if both were specified in XML (usually 1548 // when starting with EditText and setting only focusable=false). To keep those apps from 1549 // breaking, re-apply the focusable attribute here. 1550 if (focusable != getFocusable()) { 1551 setFocusable(focusable); 1552 } 1553 setClickable(clickable); 1554 setLongClickable(longClickable); 1555 1556 if (mEditor != null) mEditor.prepareCursorControllers(); 1557 1558 // If not explicitly specified this view is important for accessibility. 1559 if (getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 1560 setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES); 1561 } 1562 1563 if (supportsAutoSizeText()) { 1564 if (mAutoSizeTextType == AUTO_SIZE_TEXT_TYPE_UNIFORM) { 1565 // If uniform auto-size has been specified but preset values have not been set then 1566 // replace the auto-size configuration values that have not been specified with the 1567 // defaults. 1568 if (!mHasPresetAutoSizeValues) { 1569 final DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 1570 1571 if (autoSizeMinTextSizeInPx == UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE) { 1572 autoSizeMinTextSizeInPx = TypedValue.applyDimension( 1573 TypedValue.COMPLEX_UNIT_SP, 1574 DEFAULT_AUTO_SIZE_MIN_TEXT_SIZE_IN_SP, 1575 displayMetrics); 1576 } 1577 1578 if (autoSizeMaxTextSizeInPx == UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE) { 1579 autoSizeMaxTextSizeInPx = TypedValue.applyDimension( 1580 TypedValue.COMPLEX_UNIT_SP, 1581 DEFAULT_AUTO_SIZE_MAX_TEXT_SIZE_IN_SP, 1582 displayMetrics); 1583 } 1584 1585 if (autoSizeStepGranularityInPx 1586 == UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE) { 1587 autoSizeStepGranularityInPx = DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX; 1588 } 1589 1590 validateAndSetAutoSizeTextTypeUniformConfiguration(autoSizeMinTextSizeInPx, 1591 autoSizeMaxTextSizeInPx, 1592 autoSizeStepGranularityInPx); 1593 } 1594 1595 setupAutoSizeText(); 1596 } 1597 } else { 1598 mAutoSizeTextType = AUTO_SIZE_TEXT_TYPE_NONE; 1599 } 1600 1601 if (firstBaselineToTopHeight >= 0) { 1602 setFirstBaselineToTopHeight(firstBaselineToTopHeight); 1603 } 1604 if (lastBaselineToBottomHeight >= 0) { 1605 setLastBaselineToBottomHeight(lastBaselineToBottomHeight); 1606 } 1607 if (lineHeight >= 0) { 1608 setLineHeight(lineHeight); 1609 } 1610 } 1611 1612 /** 1613 * Specify whether this widget should automatically scale the text to try to perfectly fit 1614 * within the layout bounds by using the default auto-size configuration. 1615 * 1616 * @param autoSizeTextType the type of auto-size. Must be one of 1617 * {@link TextView#AUTO_SIZE_TEXT_TYPE_NONE} or 1618 * {@link TextView#AUTO_SIZE_TEXT_TYPE_UNIFORM} 1619 * 1620 * @throws IllegalArgumentException if <code>autoSizeTextType</code> is none of the types above. 1621 * 1622 * @attr ref android.R.styleable#TextView_autoSizeTextType 1623 * 1624 * @see #getAutoSizeTextType() 1625 */ 1626 public void setAutoSizeTextTypeWithDefaults(@AutoSizeTextType int autoSizeTextType) { 1627 if (supportsAutoSizeText()) { 1628 switch (autoSizeTextType) { 1629 case AUTO_SIZE_TEXT_TYPE_NONE: 1630 clearAutoSizeConfiguration(); 1631 break; 1632 case AUTO_SIZE_TEXT_TYPE_UNIFORM: 1633 final DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 1634 final float autoSizeMinTextSizeInPx = TypedValue.applyDimension( 1635 TypedValue.COMPLEX_UNIT_SP, 1636 DEFAULT_AUTO_SIZE_MIN_TEXT_SIZE_IN_SP, 1637 displayMetrics); 1638 final float autoSizeMaxTextSizeInPx = TypedValue.applyDimension( 1639 TypedValue.COMPLEX_UNIT_SP, 1640 DEFAULT_AUTO_SIZE_MAX_TEXT_SIZE_IN_SP, 1641 displayMetrics); 1642 1643 validateAndSetAutoSizeTextTypeUniformConfiguration( 1644 autoSizeMinTextSizeInPx, 1645 autoSizeMaxTextSizeInPx, 1646 DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX); 1647 if (setupAutoSizeText()) { 1648 autoSizeText(); 1649 invalidate(); 1650 } 1651 break; 1652 default: 1653 throw new IllegalArgumentException( 1654 "Unknown auto-size text type: " + autoSizeTextType); 1655 } 1656 } 1657 } 1658 1659 /** 1660 * Specify whether this widget should automatically scale the text to try to perfectly fit 1661 * within the layout bounds. If all the configuration params are valid the type of auto-size is 1662 * set to {@link #AUTO_SIZE_TEXT_TYPE_UNIFORM}. 1663 * 1664 * @param autoSizeMinTextSize the minimum text size available for auto-size 1665 * @param autoSizeMaxTextSize the maximum text size available for auto-size 1666 * @param autoSizeStepGranularity the auto-size step granularity. It is used in conjunction with 1667 * the minimum and maximum text size in order to build the set of 1668 * text sizes the system uses to choose from when auto-sizing 1669 * @param unit the desired dimension unit for all sizes above. See {@link TypedValue} for the 1670 * possible dimension units 1671 * 1672 * @throws IllegalArgumentException if any of the configuration params are invalid. 1673 * 1674 * @attr ref android.R.styleable#TextView_autoSizeTextType 1675 * @attr ref android.R.styleable#TextView_autoSizeMinTextSize 1676 * @attr ref android.R.styleable#TextView_autoSizeMaxTextSize 1677 * @attr ref android.R.styleable#TextView_autoSizeStepGranularity 1678 * 1679 * @see #setAutoSizeTextTypeWithDefaults(int) 1680 * @see #setAutoSizeTextTypeUniformWithPresetSizes(int[], int) 1681 * @see #getAutoSizeMinTextSize() 1682 * @see #getAutoSizeMaxTextSize() 1683 * @see #getAutoSizeStepGranularity() 1684 * @see #getAutoSizeTextAvailableSizes() 1685 */ 1686 public void setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, 1687 int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit) { 1688 if (supportsAutoSizeText()) { 1689 final DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 1690 final float autoSizeMinTextSizeInPx = TypedValue.applyDimension( 1691 unit, autoSizeMinTextSize, displayMetrics); 1692 final float autoSizeMaxTextSizeInPx = TypedValue.applyDimension( 1693 unit, autoSizeMaxTextSize, displayMetrics); 1694 final float autoSizeStepGranularityInPx = TypedValue.applyDimension( 1695 unit, autoSizeStepGranularity, displayMetrics); 1696 1697 validateAndSetAutoSizeTextTypeUniformConfiguration(autoSizeMinTextSizeInPx, 1698 autoSizeMaxTextSizeInPx, 1699 autoSizeStepGranularityInPx); 1700 1701 if (setupAutoSizeText()) { 1702 autoSizeText(); 1703 invalidate(); 1704 } 1705 } 1706 } 1707 1708 /** 1709 * Specify whether this widget should automatically scale the text to try to perfectly fit 1710 * within the layout bounds. If at least one value from the <code>presetSizes</code> is valid 1711 * then the type of auto-size is set to {@link #AUTO_SIZE_TEXT_TYPE_UNIFORM}. 1712 * 1713 * @param presetSizes an {@code int} array of sizes in pixels 1714 * @param unit the desired dimension unit for the preset sizes above. See {@link TypedValue} for 1715 * the possible dimension units 1716 * 1717 * @throws IllegalArgumentException if all of the <code>presetSizes</code> are invalid. 1718 * 1719 * @attr ref android.R.styleable#TextView_autoSizeTextType 1720 * @attr ref android.R.styleable#TextView_autoSizePresetSizes 1721 * 1722 * @see #setAutoSizeTextTypeWithDefaults(int) 1723 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int) 1724 * @see #getAutoSizeMinTextSize() 1725 * @see #getAutoSizeMaxTextSize() 1726 * @see #getAutoSizeTextAvailableSizes() 1727 */ 1728 public void setAutoSizeTextTypeUniformWithPresetSizes(@NonNull int[] presetSizes, int unit) { 1729 if (supportsAutoSizeText()) { 1730 final int presetSizesLength = presetSizes.length; 1731 if (presetSizesLength > 0) { 1732 int[] presetSizesInPx = new int[presetSizesLength]; 1733 1734 if (unit == TypedValue.COMPLEX_UNIT_PX) { 1735 presetSizesInPx = Arrays.copyOf(presetSizes, presetSizesLength); 1736 } else { 1737 final DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); 1738 // Convert all to sizes to pixels. 1739 for (int i = 0; i < presetSizesLength; i++) { 1740 presetSizesInPx[i] = Math.round(TypedValue.applyDimension(unit, 1741 presetSizes[i], displayMetrics)); 1742 } 1743 } 1744 1745 mAutoSizeTextSizesInPx = cleanupAutoSizePresetSizes(presetSizesInPx); 1746 if (!setupAutoSizeUniformPresetSizesConfiguration()) { 1747 throw new IllegalArgumentException("None of the preset sizes is valid: " 1748 + Arrays.toString(presetSizes)); 1749 } 1750 } else { 1751 mHasPresetAutoSizeValues = false; 1752 } 1753 1754 if (setupAutoSizeText()) { 1755 autoSizeText(); 1756 invalidate(); 1757 } 1758 } 1759 } 1760 1761 /** 1762 * Returns the type of auto-size set for this widget. 1763 * 1764 * @return an {@code int} corresponding to one of the auto-size types: 1765 * {@link TextView#AUTO_SIZE_TEXT_TYPE_NONE} or 1766 * {@link TextView#AUTO_SIZE_TEXT_TYPE_UNIFORM} 1767 * 1768 * @attr ref android.R.styleable#TextView_autoSizeTextType 1769 * 1770 * @see #setAutoSizeTextTypeWithDefaults(int) 1771 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int) 1772 * @see #setAutoSizeTextTypeUniformWithPresetSizes(int[], int) 1773 */ 1774 @AutoSizeTextType 1775 public int getAutoSizeTextType() { 1776 return mAutoSizeTextType; 1777 } 1778 1779 /** 1780 * @return the current auto-size step granularity in pixels. 1781 * 1782 * @attr ref android.R.styleable#TextView_autoSizeStepGranularity 1783 * 1784 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int) 1785 */ 1786 public int getAutoSizeStepGranularity() { 1787 return Math.round(mAutoSizeStepGranularityInPx); 1788 } 1789 1790 /** 1791 * @return the current auto-size minimum text size in pixels (the default is 12sp). Note that 1792 * if auto-size has not been configured this function returns {@code -1}. 1793 * 1794 * @attr ref android.R.styleable#TextView_autoSizeMinTextSize 1795 * 1796 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int) 1797 * @see #setAutoSizeTextTypeUniformWithPresetSizes(int[], int) 1798 */ 1799 public int getAutoSizeMinTextSize() { 1800 return Math.round(mAutoSizeMinTextSizeInPx); 1801 } 1802 1803 /** 1804 * @return the current auto-size maximum text size in pixels (the default is 112sp). Note that 1805 * if auto-size has not been configured this function returns {@code -1}. 1806 * 1807 * @attr ref android.R.styleable#TextView_autoSizeMaxTextSize 1808 * 1809 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int) 1810 * @see #setAutoSizeTextTypeUniformWithPresetSizes(int[], int) 1811 */ 1812 public int getAutoSizeMaxTextSize() { 1813 return Math.round(mAutoSizeMaxTextSizeInPx); 1814 } 1815 1816 /** 1817 * @return the current auto-size {@code int} sizes array (in pixels). 1818 * 1819 * @see #setAutoSizeTextTypeUniformWithConfiguration(int, int, int, int) 1820 * @see #setAutoSizeTextTypeUniformWithPresetSizes(int[], int) 1821 */ 1822 public int[] getAutoSizeTextAvailableSizes() { 1823 return mAutoSizeTextSizesInPx; 1824 } 1825 1826 private void setupAutoSizeUniformPresetSizes(TypedArray textSizes) { 1827 final int textSizesLength = textSizes.length(); 1828 final int[] parsedSizes = new int[textSizesLength]; 1829 1830 if (textSizesLength > 0) { 1831 for (int i = 0; i < textSizesLength; i++) { 1832 parsedSizes[i] = textSizes.getDimensionPixelSize(i, -1); 1833 } 1834 mAutoSizeTextSizesInPx = cleanupAutoSizePresetSizes(parsedSizes); 1835 setupAutoSizeUniformPresetSizesConfiguration(); 1836 } 1837 } 1838 1839 private boolean setupAutoSizeUniformPresetSizesConfiguration() { 1840 final int sizesLength = mAutoSizeTextSizesInPx.length; 1841 mHasPresetAutoSizeValues = sizesLength > 0; 1842 if (mHasPresetAutoSizeValues) { 1843 mAutoSizeTextType = AUTO_SIZE_TEXT_TYPE_UNIFORM; 1844 mAutoSizeMinTextSizeInPx = mAutoSizeTextSizesInPx[0]; 1845 mAutoSizeMaxTextSizeInPx = mAutoSizeTextSizesInPx[sizesLength - 1]; 1846 mAutoSizeStepGranularityInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 1847 } 1848 return mHasPresetAutoSizeValues; 1849 } 1850 1851 /** 1852 * If all params are valid then save the auto-size configuration. 1853 * 1854 * @throws IllegalArgumentException if any of the params are invalid 1855 */ 1856 private void validateAndSetAutoSizeTextTypeUniformConfiguration(float autoSizeMinTextSizeInPx, 1857 float autoSizeMaxTextSizeInPx, float autoSizeStepGranularityInPx) { 1858 // First validate. 1859 if (autoSizeMinTextSizeInPx <= 0) { 1860 throw new IllegalArgumentException("Minimum auto-size text size (" 1861 + autoSizeMinTextSizeInPx + "px) is less or equal to (0px)"); 1862 } 1863 1864 if (autoSizeMaxTextSizeInPx <= autoSizeMinTextSizeInPx) { 1865 throw new IllegalArgumentException("Maximum auto-size text size (" 1866 + autoSizeMaxTextSizeInPx + "px) is less or equal to minimum auto-size " 1867 + "text size (" + autoSizeMinTextSizeInPx + "px)"); 1868 } 1869 1870 if (autoSizeStepGranularityInPx <= 0) { 1871 throw new IllegalArgumentException("The auto-size step granularity (" 1872 + autoSizeStepGranularityInPx + "px) is less or equal to (0px)"); 1873 } 1874 1875 // All good, persist the configuration. 1876 mAutoSizeTextType = AUTO_SIZE_TEXT_TYPE_UNIFORM; 1877 mAutoSizeMinTextSizeInPx = autoSizeMinTextSizeInPx; 1878 mAutoSizeMaxTextSizeInPx = autoSizeMaxTextSizeInPx; 1879 mAutoSizeStepGranularityInPx = autoSizeStepGranularityInPx; 1880 mHasPresetAutoSizeValues = false; 1881 } 1882 1883 private void clearAutoSizeConfiguration() { 1884 mAutoSizeTextType = AUTO_SIZE_TEXT_TYPE_NONE; 1885 mAutoSizeMinTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 1886 mAutoSizeMaxTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 1887 mAutoSizeStepGranularityInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE; 1888 mAutoSizeTextSizesInPx = EmptyArray.INT; 1889 mNeedsAutoSizeText = false; 1890 } 1891 1892 // Returns distinct sorted positive values. 1893 private int[] cleanupAutoSizePresetSizes(int[] presetValues) { 1894 final int presetValuesLength = presetValues.length; 1895 if (presetValuesLength == 0) { 1896 return presetValues; 1897 } 1898 Arrays.sort(presetValues); 1899 1900 final IntArray uniqueValidSizes = new IntArray(); 1901 for (int i = 0; i < presetValuesLength; i++) { 1902 final int currentPresetValue = presetValues[i]; 1903 1904 if (currentPresetValue > 0 1905 && uniqueValidSizes.binarySearch(currentPresetValue) < 0) { 1906 uniqueValidSizes.add(currentPresetValue); 1907 } 1908 } 1909 1910 return presetValuesLength == uniqueValidSizes.size() 1911 ? presetValues 1912 : uniqueValidSizes.toArray(); 1913 } 1914 1915 private boolean setupAutoSizeText() { 1916 if (supportsAutoSizeText() && mAutoSizeTextType == AUTO_SIZE_TEXT_TYPE_UNIFORM) { 1917 // Calculate the sizes set based on minimum size, maximum size and step size if we do 1918 // not have a predefined set of sizes or if the current sizes array is empty. 1919 if (!mHasPresetAutoSizeValues || mAutoSizeTextSizesInPx.length == 0) { 1920 int autoSizeValuesLength = 1; 1921 float currentSize = Math.round(mAutoSizeMinTextSizeInPx); 1922 while (Math.round(currentSize + mAutoSizeStepGranularityInPx) 1923 <= Math.round(mAutoSizeMaxTextSizeInPx)) { 1924 autoSizeValuesLength++; 1925 currentSize += mAutoSizeStepGranularityInPx; 1926 } 1927 1928 int[] autoSizeTextSizesInPx = new int[autoSizeValuesLength]; 1929 float sizeToAdd = mAutoSizeMinTextSizeInPx; 1930 for (int i = 0; i < autoSizeValuesLength; i++) { 1931 autoSizeTextSizesInPx[i] = Math.round(sizeToAdd); 1932 sizeToAdd += mAutoSizeStepGranularityInPx; 1933 } 1934 mAutoSizeTextSizesInPx = cleanupAutoSizePresetSizes(autoSizeTextSizesInPx); 1935 } 1936 1937 mNeedsAutoSizeText = true; 1938 } else { 1939 mNeedsAutoSizeText = false; 1940 } 1941 1942 return mNeedsAutoSizeText; 1943 } 1944 1945 private int[] parseDimensionArray(TypedArray dimens) { 1946 if (dimens == null) { 1947 return null; 1948 } 1949 int[] result = new int[dimens.length()]; 1950 for (int i = 0; i < result.length; i++) { 1951 result[i] = dimens.getDimensionPixelSize(i, 0); 1952 } 1953 return result; 1954 } 1955 1956 /** 1957 * @hide 1958 */ 1959 @Override 1960 public void onActivityResult(int requestCode, int resultCode, Intent data) { 1961 if (requestCode == PROCESS_TEXT_REQUEST_CODE) { 1962 if (resultCode == Activity.RESULT_OK && data != null) { 1963 CharSequence result = data.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT); 1964 if (result != null) { 1965 if (isTextEditable()) { 1966 replaceSelectionWithText(result); 1967 if (mEditor != null) { 1968 mEditor.refreshTextActionMode(); 1969 } 1970 } else { 1971 if (result.length() > 0) { 1972 Toast.makeText(getContext(), String.valueOf(result), Toast.LENGTH_LONG) 1973 .show(); 1974 } 1975 } 1976 } 1977 } else if (mText instanceof Spannable) { 1978 // Reset the selection. 1979 Selection.setSelection((Spannable) mText, getSelectionEnd()); 1980 } 1981 } 1982 } 1983 1984 /** 1985 * Sets the Typeface taking into account the given attributes. 1986 * 1987 * @param typeface a typeface 1988 * @param familyName family name string, e.g. "serif" 1989 * @param typefaceIndex an index of the typeface enum, e.g. SANS, SERIF. 1990 * @param style a typeface style 1991 * @param weight a weight value for the Typeface or -1 if not specified. 1992 */ 1993 private void setTypefaceFromAttrs(@Nullable Typeface typeface, @Nullable String familyName, 1994 @XMLTypefaceAttr int typefaceIndex, @Typeface.Style int style, 1995 @IntRange(from = -1, to = Typeface.MAX_WEIGHT) int weight) { 1996 if (typeface == null && familyName != null) { 1997 // Lookup normal Typeface from system font map. 1998 final Typeface normalTypeface = Typeface.create(familyName, Typeface.NORMAL); 1999 resolveStyleAndSetTypeface(normalTypeface, style, weight); 2000 } else if (typeface != null) { 2001 resolveStyleAndSetTypeface(typeface, style, weight); 2002 } else { // both typeface and familyName is null. 2003 switch (typefaceIndex) { 2004 case SANS: 2005 resolveStyleAndSetTypeface(Typeface.SANS_SERIF, style, weight); 2006 break; 2007 case SERIF: 2008 resolveStyleAndSetTypeface(Typeface.SERIF, style, weight); 2009 break; 2010 case MONOSPACE: 2011 resolveStyleAndSetTypeface(Typeface.MONOSPACE, style, weight); 2012 break; 2013 case DEFAULT_TYPEFACE: 2014 default: 2015 resolveStyleAndSetTypeface(null, style, weight); 2016 break; 2017 } 2018 } 2019 } 2020 2021 private void resolveStyleAndSetTypeface(@NonNull Typeface typeface, @Typeface.Style int style, 2022 @IntRange(from = -1, to = Typeface.MAX_WEIGHT) int weight) { 2023 if (weight >= 0) { 2024 weight = Math.min(Typeface.MAX_WEIGHT, weight); 2025 final boolean italic = (style & Typeface.ITALIC) != 0; 2026 setTypeface(Typeface.create(typeface, weight, italic)); 2027 } else { 2028 setTypeface(typeface, style); 2029 } 2030 } 2031 2032 private void setRelativeDrawablesIfNeeded(Drawable start, Drawable end) { 2033 boolean hasRelativeDrawables = (start != null) || (end != null); 2034 if (hasRelativeDrawables) { 2035 Drawables dr = mDrawables; 2036 if (dr == null) { 2037 mDrawables = dr = new Drawables(getContext()); 2038 } 2039 mDrawables.mOverride = true; 2040 final Rect compoundRect = dr.mCompoundRect; 2041 int[] state = getDrawableState(); 2042 if (start != null) { 2043 start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); 2044 start.setState(state); 2045 start.copyBounds(compoundRect); 2046 start.setCallback(this); 2047 2048 dr.mDrawableStart = start; 2049 dr.mDrawableSizeStart = compoundRect.width(); 2050 dr.mDrawableHeightStart = compoundRect.height(); 2051 } else { 2052 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 2053 } 2054 if (end != null) { 2055 end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); 2056 end.setState(state); 2057 end.copyBounds(compoundRect); 2058 end.setCallback(this); 2059 2060 dr.mDrawableEnd = end; 2061 dr.mDrawableSizeEnd = compoundRect.width(); 2062 dr.mDrawableHeightEnd = compoundRect.height(); 2063 } else { 2064 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 2065 } 2066 resetResolvedDrawables(); 2067 resolveDrawables(); 2068 applyCompoundDrawableTint(); 2069 } 2070 } 2071 2072 @android.view.RemotableViewMethod 2073 @Override 2074 public void setEnabled(boolean enabled) { 2075 if (enabled == isEnabled()) { 2076 return; 2077 } 2078 2079 if (!enabled) { 2080 // Hide the soft input if the currently active TextView is disabled 2081 InputMethodManager imm = InputMethodManager.peekInstance(); 2082 if (imm != null && imm.isActive(this)) { 2083 imm.hideSoftInputFromWindow(getWindowToken(), 0); 2084 } 2085 } 2086 2087 super.setEnabled(enabled); 2088 2089 if (enabled) { 2090 // Make sure IME is updated with current editor info. 2091 InputMethodManager imm = InputMethodManager.peekInstance(); 2092 if (imm != null) imm.restartInput(this); 2093 } 2094 2095 // Will change text color 2096 if (mEditor != null) { 2097 mEditor.invalidateTextDisplayList(); 2098 mEditor.prepareCursorControllers(); 2099 2100 // start or stop the cursor blinking as appropriate 2101 mEditor.makeBlink(); 2102 } 2103 } 2104 2105 /** 2106 * Sets the typeface and style in which the text should be displayed, 2107 * and turns on the fake bold and italic bits in the Paint if the 2108 * Typeface that you provided does not have all the bits in the 2109 * style that you specified. 2110 * 2111 * @attr ref android.R.styleable#TextView_typeface 2112 * @attr ref android.R.styleable#TextView_textStyle 2113 */ 2114 public void setTypeface(@Nullable Typeface tf, @Typeface.Style int style) { 2115 if (style > 0) { 2116 if (tf == null) { 2117 tf = Typeface.defaultFromStyle(style); 2118 } else { 2119 tf = Typeface.create(tf, style); 2120 } 2121 2122 setTypeface(tf); 2123 // now compute what (if any) algorithmic styling is needed 2124 int typefaceStyle = tf != null ? tf.getStyle() : 0; 2125 int need = style & ~typefaceStyle; 2126 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); 2127 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); 2128 } else { 2129 mTextPaint.setFakeBoldText(false); 2130 mTextPaint.setTextSkewX(0); 2131 setTypeface(tf); 2132 } 2133 } 2134 2135 /** 2136 * Subclasses override this to specify that they have a KeyListener 2137 * by default even if not specifically called for in the XML options. 2138 */ 2139 protected boolean getDefaultEditable() { 2140 return false; 2141 } 2142 2143 /** 2144 * Subclasses override this to specify a default movement method. 2145 */ 2146 protected MovementMethod getDefaultMovementMethod() { 2147 return null; 2148 } 2149 2150 /** 2151 * Return the text that TextView is displaying. If {@link #setText(CharSequence)} was called 2152 * with an argument of {@link android.widget.TextView.BufferType#SPANNABLE BufferType.SPANNABLE} 2153 * or {@link android.widget.TextView.BufferType#EDITABLE BufferType.EDITABLE}, you can cast 2154 * the return value from this method to Spannable or Editable, respectively. 2155 * 2156 * <p>The content of the return value should not be modified. If you want a modifiable one, you 2157 * should make your own copy first.</p> 2158 * 2159 * @return The text displayed by the text view. 2160 * @attr ref android.R.styleable#TextView_text 2161 */ 2162 @ViewDebug.CapturedViewProperty 2163 public CharSequence getText() { 2164 return mText; 2165 } 2166 2167 /** 2168 * Returns the length, in characters, of the text managed by this TextView 2169 * @return The length of the text managed by the TextView in characters. 2170 */ 2171 public int length() { 2172 return mText.length(); 2173 } 2174 2175 /** 2176 * Return the text that TextView is displaying as an Editable object. If the text is not 2177 * editable, null is returned. 2178 * 2179 * @see #getText 2180 */ 2181 public Editable getEditableText() { 2182 return (mText instanceof Editable) ? (Editable) mText : null; 2183 } 2184 2185 /** 2186 * Gets the vertical distance between lines of text, in pixels. 2187 * Note that markup within the text can cause individual lines 2188 * to be taller or shorter than this height, and the layout may 2189 * contain additional first-or last-line padding. 2190 * @return The height of one standard line in pixels. 2191 */ 2192 public int getLineHeight() { 2193 return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd); 2194 } 2195 2196 /** 2197 * Gets the {@link android.text.Layout} that is currently being used to display the text. 2198 * This value can be null if the text or width has recently changed. 2199 * @return The Layout that is currently being used to display the text. 2200 */ 2201 public final Layout getLayout() { 2202 return mLayout; 2203 } 2204 2205 /** 2206 * @return the {@link android.text.Layout} that is currently being used to 2207 * display the hint text. This can be null. 2208 */ 2209 final Layout getHintLayout() { 2210 return mHintLayout; 2211 } 2212 2213 /** 2214 * Retrieve the {@link android.content.UndoManager} that is currently associated 2215 * with this TextView. By default there is no associated UndoManager, so null 2216 * is returned. One can be associated with the TextView through 2217 * {@link #setUndoManager(android.content.UndoManager, String)} 2218 * 2219 * @hide 2220 */ 2221 public final UndoManager getUndoManager() { 2222 // TODO: Consider supporting a global undo manager. 2223 throw new UnsupportedOperationException("not implemented"); 2224 } 2225 2226 2227 /** 2228 * @hide 2229 */ 2230 @VisibleForTesting 2231 public final Editor getEditorForTesting() { 2232 return mEditor; 2233 } 2234 2235 /** 2236 * Associate an {@link android.content.UndoManager} with this TextView. Once 2237 * done, all edit operations on the TextView will result in appropriate 2238 * {@link android.content.UndoOperation} objects pushed on the given UndoManager's 2239 * stack. 2240 * 2241 * @param undoManager The {@link android.content.UndoManager} to associate with 2242 * this TextView, or null to clear any existing association. 2243 * @param tag String tag identifying this particular TextView owner in the 2244 * UndoManager. This is used to keep the correct association with the 2245 * {@link android.content.UndoOwner} of any operations inside of the UndoManager. 2246 * 2247 * @hide 2248 */ 2249 public final void setUndoManager(UndoManager undoManager, String tag) { 2250 // TODO: Consider supporting a global undo manager. An implementation will need to: 2251 // * createEditorIfNeeded() 2252 // * Promote to BufferType.EDITABLE if needed. 2253 // * Update the UndoManager and UndoOwner. 2254 // Likewise it will need to be able to restore the default UndoManager. 2255 throw new UnsupportedOperationException("not implemented"); 2256 } 2257 2258 /** 2259 * Gets the current {@link KeyListener} for the TextView. 2260 * This will frequently be null for non-EditText TextViews. 2261 * @return the current key listener for this TextView. 2262 * 2263 * @attr ref android.R.styleable#TextView_numeric 2264 * @attr ref android.R.styleable#TextView_digits 2265 * @attr ref android.R.styleable#TextView_phoneNumber 2266 * @attr ref android.R.styleable#TextView_inputMethod 2267 * @attr ref android.R.styleable#TextView_capitalize 2268 * @attr ref android.R.styleable#TextView_autoText 2269 */ 2270 public final KeyListener getKeyListener() { 2271 return mEditor == null ? null : mEditor.mKeyListener; 2272 } 2273 2274 /** 2275 * Sets the key listener to be used with this TextView. This can be null 2276 * to disallow user input. Note that this method has significant and 2277 * subtle interactions with soft keyboards and other input method: 2278 * see {@link KeyListener#getInputType() KeyListener.getContentType()} 2279 * for important details. Calling this method will replace the current 2280 * content type of the text view with the content type returned by the 2281 * key listener. 2282 * <p> 2283 * Be warned that if you want a TextView with a key listener or movement 2284 * method not to be focusable, or if you want a TextView without a 2285 * key listener or movement method to be focusable, you must call 2286 * {@link #setFocusable} again after calling this to get the focusability 2287 * back the way you want it. 2288 * 2289 * @attr ref android.R.styleable#TextView_numeric 2290 * @attr ref android.R.styleable#TextView_digits 2291 * @attr ref android.R.styleable#TextView_phoneNumber 2292 * @attr ref android.R.styleable#TextView_inputMethod 2293 * @attr ref android.R.styleable#TextView_capitalize 2294 * @attr ref android.R.styleable#TextView_autoText 2295 */ 2296 public void setKeyListener(KeyListener input) { 2297 mListenerChanged = true; 2298 setKeyListenerOnly(input); 2299 fixFocusableAndClickableSettings(); 2300 2301 if (input != null) { 2302 createEditorIfNeeded(); 2303 setInputTypeFromEditor(); 2304 } else { 2305 if (mEditor != null) mEditor.mInputType = EditorInfo.TYPE_NULL; 2306 } 2307 2308 InputMethodManager imm = InputMethodManager.peekInstance(); 2309 if (imm != null) imm.restartInput(this); 2310 } 2311 2312 private void setInputTypeFromEditor() { 2313 try { 2314 mEditor.mInputType = mEditor.mKeyListener.getInputType(); 2315 } catch (IncompatibleClassChangeError e) { 2316 mEditor.mInputType = EditorInfo.TYPE_CLASS_TEXT; 2317 } 2318 // Change inputType, without affecting transformation. 2319 // No need to applySingleLine since mSingleLine is unchanged. 2320 setInputTypeSingleLine(mSingleLine); 2321 } 2322 2323 private void setKeyListenerOnly(KeyListener input) { 2324 if (mEditor == null && input == null) return; // null is the default value 2325 2326 createEditorIfNeeded(); 2327 if (mEditor.mKeyListener != input) { 2328 mEditor.mKeyListener = input; 2329 if (input != null && !(mText instanceof Editable)) { 2330 setText(mText); 2331 } 2332 2333 setFilters((Editable) mText, mFilters); 2334 } 2335 } 2336 2337 /** 2338 * Gets the {@link android.text.method.MovementMethod} being used for this TextView, 2339 * which provides positioning, scrolling, and text selection functionality. 2340 * This will frequently be null for non-EditText TextViews. 2341 * @return the movement method being used for this TextView. 2342 * @see android.text.method.MovementMethod 2343 */ 2344 public final MovementMethod getMovementMethod() { 2345 return mMovement; 2346 } 2347 2348 /** 2349 * Sets the {@link android.text.method.MovementMethod} for handling arrow key movement 2350 * for this TextView. This can be null to disallow using the arrow keys to move the 2351 * cursor or scroll the view. 2352 * <p> 2353 * Be warned that if you want a TextView with a key listener or movement 2354 * method not to be focusable, or if you want a TextView without a 2355 * key listener or movement method to be focusable, you must call 2356 * {@link #setFocusable} again after calling this to get the focusability 2357 * back the way you want it. 2358 */ 2359 public final void setMovementMethod(MovementMethod movement) { 2360 if (mMovement != movement) { 2361 mMovement = movement; 2362 2363 if (movement != null && !(mText instanceof Spannable)) { 2364 setText(mText); 2365 } 2366 2367 fixFocusableAndClickableSettings(); 2368 2369 // SelectionModifierCursorController depends on textCanBeSelected, which depends on 2370 // mMovement 2371 if (mEditor != null) mEditor.prepareCursorControllers(); 2372 } 2373 } 2374 2375 private void fixFocusableAndClickableSettings() { 2376 if (mMovement != null || (mEditor != null && mEditor.mKeyListener != null)) { 2377 setFocusable(FOCUSABLE); 2378 setClickable(true); 2379 setLongClickable(true); 2380 } else { 2381 setFocusable(FOCUSABLE_AUTO); 2382 setClickable(false); 2383 setLongClickable(false); 2384 } 2385 } 2386 2387 /** 2388 * Gets the current {@link android.text.method.TransformationMethod} for the TextView. 2389 * This is frequently null, except for single-line and password fields. 2390 * @return the current transformation method for this TextView. 2391 * 2392 * @attr ref android.R.styleable#TextView_password 2393 * @attr ref android.R.styleable#TextView_singleLine 2394 */ 2395 public final TransformationMethod getTransformationMethod() { 2396 return mTransformation; 2397 } 2398 2399 /** 2400 * Sets the transformation that is applied to the text that this 2401 * TextView is displaying. 2402 * 2403 * @attr ref android.R.styleable#TextView_password 2404 * @attr ref android.R.styleable#TextView_singleLine 2405 */ 2406 public final void setTransformationMethod(TransformationMethod method) { 2407 if (method == mTransformation) { 2408 // Avoid the setText() below if the transformation is 2409 // the same. 2410 return; 2411 } 2412 if (mTransformation != null) { 2413 if (mText instanceof Spannable) { 2414 ((Spannable) mText).removeSpan(mTransformation); 2415 } 2416 } 2417 2418 mTransformation = method; 2419 2420 if (method instanceof TransformationMethod2) { 2421 TransformationMethod2 method2 = (TransformationMethod2) method; 2422 mAllowTransformationLengthChange = !isTextSelectable() && !(mText instanceof Editable); 2423 method2.setLengthChangesAllowed(mAllowTransformationLengthChange); 2424 } else { 2425 mAllowTransformationLengthChange = false; 2426 } 2427 2428 setText(mText); 2429 2430 if (hasPasswordTransformationMethod()) { 2431 notifyViewAccessibilityStateChangedIfNeeded( 2432 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 2433 } 2434 2435 // PasswordTransformationMethod always have LTR text direction heuristics returned by 2436 // getTextDirectionHeuristic, needs reset 2437 mTextDir = getTextDirectionHeuristic(); 2438 } 2439 2440 /** 2441 * Returns the top padding of the view, plus space for the top 2442 * Drawable if any. 2443 */ 2444 public int getCompoundPaddingTop() { 2445 final Drawables dr = mDrawables; 2446 if (dr == null || dr.mShowing[Drawables.TOP] == null) { 2447 return mPaddingTop; 2448 } else { 2449 return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop; 2450 } 2451 } 2452 2453 /** 2454 * Returns the bottom padding of the view, plus space for the bottom 2455 * Drawable if any. 2456 */ 2457 public int getCompoundPaddingBottom() { 2458 final Drawables dr = mDrawables; 2459 if (dr == null || dr.mShowing[Drawables.BOTTOM] == null) { 2460 return mPaddingBottom; 2461 } else { 2462 return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom; 2463 } 2464 } 2465 2466 /** 2467 * Returns the left padding of the view, plus space for the left 2468 * Drawable if any. 2469 */ 2470 public int getCompoundPaddingLeft() { 2471 final Drawables dr = mDrawables; 2472 if (dr == null || dr.mShowing[Drawables.LEFT] == null) { 2473 return mPaddingLeft; 2474 } else { 2475 return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft; 2476 } 2477 } 2478 2479 /** 2480 * Returns the right padding of the view, plus space for the right 2481 * Drawable if any. 2482 */ 2483 public int getCompoundPaddingRight() { 2484 final Drawables dr = mDrawables; 2485 if (dr == null || dr.mShowing[Drawables.RIGHT] == null) { 2486 return mPaddingRight; 2487 } else { 2488 return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight; 2489 } 2490 } 2491 2492 /** 2493 * Returns the start padding of the view, plus space for the start 2494 * Drawable if any. 2495 */ 2496 public int getCompoundPaddingStart() { 2497 resolveDrawables(); 2498 switch(getLayoutDirection()) { 2499 default: 2500 case LAYOUT_DIRECTION_LTR: 2501 return getCompoundPaddingLeft(); 2502 case LAYOUT_DIRECTION_RTL: 2503 return getCompoundPaddingRight(); 2504 } 2505 } 2506 2507 /** 2508 * Returns the end padding of the view, plus space for the end 2509 * Drawable if any. 2510 */ 2511 public int getCompoundPaddingEnd() { 2512 resolveDrawables(); 2513 switch(getLayoutDirection()) { 2514 default: 2515 case LAYOUT_DIRECTION_LTR: 2516 return getCompoundPaddingRight(); 2517 case LAYOUT_DIRECTION_RTL: 2518 return getCompoundPaddingLeft(); 2519 } 2520 } 2521 2522 /** 2523 * Returns the extended top padding of the view, including both the 2524 * top Drawable if any and any extra space to keep more than maxLines 2525 * of text from showing. It is only valid to call this after measuring. 2526 */ 2527 public int getExtendedPaddingTop() { 2528 if (mMaxMode != LINES) { 2529 return getCompoundPaddingTop(); 2530 } 2531 2532 if (mLayout == null) { 2533 assumeLayout(); 2534 } 2535 2536 if (mLayout.getLineCount() <= mMaximum) { 2537 return getCompoundPaddingTop(); 2538 } 2539 2540 int top = getCompoundPaddingTop(); 2541 int bottom = getCompoundPaddingBottom(); 2542 int viewht = getHeight() - top - bottom; 2543 int layoutht = mLayout.getLineTop(mMaximum); 2544 2545 if (layoutht >= viewht) { 2546 return top; 2547 } 2548 2549 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 2550 if (gravity == Gravity.TOP) { 2551 return top; 2552 } else if (gravity == Gravity.BOTTOM) { 2553 return top + viewht - layoutht; 2554 } else { // (gravity == Gravity.CENTER_VERTICAL) 2555 return top + (viewht - layoutht) / 2; 2556 } 2557 } 2558 2559 /** 2560 * Returns the extended bottom padding of the view, including both the 2561 * bottom Drawable if any and any extra space to keep more than maxLines 2562 * of text from showing. It is only valid to call this after measuring. 2563 */ 2564 public int getExtendedPaddingBottom() { 2565 if (mMaxMode != LINES) { 2566 return getCompoundPaddingBottom(); 2567 } 2568 2569 if (mLayout == null) { 2570 assumeLayout(); 2571 } 2572 2573 if (mLayout.getLineCount() <= mMaximum) { 2574 return getCompoundPaddingBottom(); 2575 } 2576 2577 int top = getCompoundPaddingTop(); 2578 int bottom = getCompoundPaddingBottom(); 2579 int viewht = getHeight() - top - bottom; 2580 int layoutht = mLayout.getLineTop(mMaximum); 2581 2582 if (layoutht >= viewht) { 2583 return bottom; 2584 } 2585 2586 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 2587 if (gravity == Gravity.TOP) { 2588 return bottom + viewht - layoutht; 2589 } else if (gravity == Gravity.BOTTOM) { 2590 return bottom; 2591 } else { // (gravity == Gravity.CENTER_VERTICAL) 2592 return bottom + (viewht - layoutht) / 2; 2593 } 2594 } 2595 2596 /** 2597 * Returns the total left padding of the view, including the left 2598 * Drawable if any. 2599 */ 2600 public int getTotalPaddingLeft() { 2601 return getCompoundPaddingLeft(); 2602 } 2603 2604 /** 2605 * Returns the total right padding of the view, including the right 2606 * Drawable if any. 2607 */ 2608 public int getTotalPaddingRight() { 2609 return getCompoundPaddingRight(); 2610 } 2611 2612 /** 2613 * Returns the total start padding of the view, including the start 2614 * Drawable if any. 2615 */ 2616 public int getTotalPaddingStart() { 2617 return getCompoundPaddingStart(); 2618 } 2619 2620 /** 2621 * Returns the total end padding of the view, including the end 2622 * Drawable if any. 2623 */ 2624 public int getTotalPaddingEnd() { 2625 return getCompoundPaddingEnd(); 2626 } 2627 2628 /** 2629 * Returns the total top padding of the view, including the top 2630 * Drawable if any, the extra space to keep more than maxLines 2631 * from showing, and the vertical offset for gravity, if any. 2632 */ 2633 public int getTotalPaddingTop() { 2634 return getExtendedPaddingTop() + getVerticalOffset(true); 2635 } 2636 2637 /** 2638 * Returns the total bottom padding of the view, including the bottom 2639 * Drawable if any, the extra space to keep more than maxLines 2640 * from showing, and the vertical offset for gravity, if any. 2641 */ 2642 public int getTotalPaddingBottom() { 2643 return getExtendedPaddingBottom() + getBottomVerticalOffset(true); 2644 } 2645 2646 /** 2647 * Sets the Drawables (if any) to appear to the left of, above, to the 2648 * right of, and below the text. Use {@code null} if you do not want a 2649 * Drawable there. The Drawables must already have had 2650 * {@link Drawable#setBounds} called. 2651 * <p> 2652 * Calling this method will overwrite any Drawables previously set using 2653 * {@link #setCompoundDrawablesRelative} or related methods. 2654 * 2655 * @attr ref android.R.styleable#TextView_drawableLeft 2656 * @attr ref android.R.styleable#TextView_drawableTop 2657 * @attr ref android.R.styleable#TextView_drawableRight 2658 * @attr ref android.R.styleable#TextView_drawableBottom 2659 */ 2660 public void setCompoundDrawables(@Nullable Drawable left, @Nullable Drawable top, 2661 @Nullable Drawable right, @Nullable Drawable bottom) { 2662 Drawables dr = mDrawables; 2663 2664 // We're switching to absolute, discard relative. 2665 if (dr != null) { 2666 if (dr.mDrawableStart != null) dr.mDrawableStart.setCallback(null); 2667 dr.mDrawableStart = null; 2668 if (dr.mDrawableEnd != null) dr.mDrawableEnd.setCallback(null); 2669 dr.mDrawableEnd = null; 2670 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 2671 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 2672 } 2673 2674 final boolean drawables = left != null || top != null || right != null || bottom != null; 2675 if (!drawables) { 2676 // Clearing drawables... can we free the data structure? 2677 if (dr != null) { 2678 if (!dr.hasMetadata()) { 2679 mDrawables = null; 2680 } else { 2681 // We need to retain the last set padding, so just clear 2682 // out all of the fields in the existing structure. 2683 for (int i = dr.mShowing.length - 1; i >= 0; i--) { 2684 if (dr.mShowing[i] != null) { 2685 dr.mShowing[i].setCallback(null); 2686 } 2687 dr.mShowing[i] = null; 2688 } 2689 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 2690 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 2691 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 2692 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 2693 } 2694 } 2695 } else { 2696 if (dr == null) { 2697 mDrawables = dr = new Drawables(getContext()); 2698 } 2699 2700 mDrawables.mOverride = false; 2701 2702 if (dr.mShowing[Drawables.LEFT] != left && dr.mShowing[Drawables.LEFT] != null) { 2703 dr.mShowing[Drawables.LEFT].setCallback(null); 2704 } 2705 dr.mShowing[Drawables.LEFT] = left; 2706 2707 if (dr.mShowing[Drawables.TOP] != top && dr.mShowing[Drawables.TOP] != null) { 2708 dr.mShowing[Drawables.TOP].setCallback(null); 2709 } 2710 dr.mShowing[Drawables.TOP] = top; 2711 2712 if (dr.mShowing[Drawables.RIGHT] != right && dr.mShowing[Drawables.RIGHT] != null) { 2713 dr.mShowing[Drawables.RIGHT].setCallback(null); 2714 } 2715 dr.mShowing[Drawables.RIGHT] = right; 2716 2717 if (dr.mShowing[Drawables.BOTTOM] != bottom && dr.mShowing[Drawables.BOTTOM] != null) { 2718 dr.mShowing[Drawables.BOTTOM].setCallback(null); 2719 } 2720 dr.mShowing[Drawables.BOTTOM] = bottom; 2721 2722 final Rect compoundRect = dr.mCompoundRect; 2723 int[] state; 2724 2725 state = getDrawableState(); 2726 2727 if (left != null) { 2728 left.setState(state); 2729 left.copyBounds(compoundRect); 2730 left.setCallback(this); 2731 dr.mDrawableSizeLeft = compoundRect.width(); 2732 dr.mDrawableHeightLeft = compoundRect.height(); 2733 } else { 2734 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 2735 } 2736 2737 if (right != null) { 2738 right.setState(state); 2739 right.copyBounds(compoundRect); 2740 right.setCallback(this); 2741 dr.mDrawableSizeRight = compoundRect.width(); 2742 dr.mDrawableHeightRight = compoundRect.height(); 2743 } else { 2744 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 2745 } 2746 2747 if (top != null) { 2748 top.setState(state); 2749 top.copyBounds(compoundRect); 2750 top.setCallback(this); 2751 dr.mDrawableSizeTop = compoundRect.height(); 2752 dr.mDrawableWidthTop = compoundRect.width(); 2753 } else { 2754 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 2755 } 2756 2757 if (bottom != null) { 2758 bottom.setState(state); 2759 bottom.copyBounds(compoundRect); 2760 bottom.setCallback(this); 2761 dr.mDrawableSizeBottom = compoundRect.height(); 2762 dr.mDrawableWidthBottom = compoundRect.width(); 2763 } else { 2764 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 2765 } 2766 } 2767 2768 // Save initial left/right drawables 2769 if (dr != null) { 2770 dr.mDrawableLeftInitial = left; 2771 dr.mDrawableRightInitial = right; 2772 } 2773 2774 resetResolvedDrawables(); 2775 resolveDrawables(); 2776 applyCompoundDrawableTint(); 2777 invalidate(); 2778 requestLayout(); 2779 } 2780 2781 /** 2782 * Sets the Drawables (if any) to appear to the left of, above, to the 2783 * right of, and below the text. Use 0 if you do not want a Drawable there. 2784 * The Drawables' bounds will be set to their intrinsic bounds. 2785 * <p> 2786 * Calling this method will overwrite any Drawables previously set using 2787 * {@link #setCompoundDrawablesRelative} or related methods. 2788 * 2789 * @param left Resource identifier of the left Drawable. 2790 * @param top Resource identifier of the top Drawable. 2791 * @param right Resource identifier of the right Drawable. 2792 * @param bottom Resource identifier of the bottom Drawable. 2793 * 2794 * @attr ref android.R.styleable#TextView_drawableLeft 2795 * @attr ref android.R.styleable#TextView_drawableTop 2796 * @attr ref android.R.styleable#TextView_drawableRight 2797 * @attr ref android.R.styleable#TextView_drawableBottom 2798 */ 2799 @android.view.RemotableViewMethod 2800 public void setCompoundDrawablesWithIntrinsicBounds(@DrawableRes int left, 2801 @DrawableRes int top, @DrawableRes int right, @DrawableRes int bottom) { 2802 final Context context = getContext(); 2803 setCompoundDrawablesWithIntrinsicBounds(left != 0 ? context.getDrawable(left) : null, 2804 top != 0 ? context.getDrawable(top) : null, 2805 right != 0 ? context.getDrawable(right) : null, 2806 bottom != 0 ? context.getDrawable(bottom) : null); 2807 } 2808 2809 /** 2810 * Sets the Drawables (if any) to appear to the left of, above, to the 2811 * right of, and below the text. Use {@code null} if you do not want a 2812 * Drawable there. The Drawables' bounds will be set to their intrinsic 2813 * bounds. 2814 * <p> 2815 * Calling this method will overwrite any Drawables previously set using 2816 * {@link #setCompoundDrawablesRelative} or related methods. 2817 * 2818 * @attr ref android.R.styleable#TextView_drawableLeft 2819 * @attr ref android.R.styleable#TextView_drawableTop 2820 * @attr ref android.R.styleable#TextView_drawableRight 2821 * @attr ref android.R.styleable#TextView_drawableBottom 2822 */ 2823 @android.view.RemotableViewMethod 2824 public void setCompoundDrawablesWithIntrinsicBounds(@Nullable Drawable left, 2825 @Nullable Drawable top, @Nullable Drawable right, @Nullable Drawable bottom) { 2826 2827 if (left != null) { 2828 left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight()); 2829 } 2830 if (right != null) { 2831 right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight()); 2832 } 2833 if (top != null) { 2834 top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); 2835 } 2836 if (bottom != null) { 2837 bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); 2838 } 2839 setCompoundDrawables(left, top, right, bottom); 2840 } 2841 2842 /** 2843 * Sets the Drawables (if any) to appear to the start of, above, to the end 2844 * of, and below the text. Use {@code null} if you do not want a Drawable 2845 * there. The Drawables must already have had {@link Drawable#setBounds} 2846 * called. 2847 * <p> 2848 * Calling this method will overwrite any Drawables previously set using 2849 * {@link #setCompoundDrawables} or related methods. 2850 * 2851 * @attr ref android.R.styleable#TextView_drawableStart 2852 * @attr ref android.R.styleable#TextView_drawableTop 2853 * @attr ref android.R.styleable#TextView_drawableEnd 2854 * @attr ref android.R.styleable#TextView_drawableBottom 2855 */ 2856 @android.view.RemotableViewMethod 2857 public void setCompoundDrawablesRelative(@Nullable Drawable start, @Nullable Drawable top, 2858 @Nullable Drawable end, @Nullable Drawable bottom) { 2859 Drawables dr = mDrawables; 2860 2861 // We're switching to relative, discard absolute. 2862 if (dr != null) { 2863 if (dr.mShowing[Drawables.LEFT] != null) { 2864 dr.mShowing[Drawables.LEFT].setCallback(null); 2865 } 2866 dr.mShowing[Drawables.LEFT] = dr.mDrawableLeftInitial = null; 2867 if (dr.mShowing[Drawables.RIGHT] != null) { 2868 dr.mShowing[Drawables.RIGHT].setCallback(null); 2869 } 2870 dr.mShowing[Drawables.RIGHT] = dr.mDrawableRightInitial = null; 2871 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 2872 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 2873 } 2874 2875 final boolean drawables = start != null || top != null 2876 || end != null || bottom != null; 2877 2878 if (!drawables) { 2879 // Clearing drawables... can we free the data structure? 2880 if (dr != null) { 2881 if (!dr.hasMetadata()) { 2882 mDrawables = null; 2883 } else { 2884 // We need to retain the last set padding, so just clear 2885 // out all of the fields in the existing structure. 2886 if (dr.mDrawableStart != null) dr.mDrawableStart.setCallback(null); 2887 dr.mDrawableStart = null; 2888 if (dr.mShowing[Drawables.TOP] != null) { 2889 dr.mShowing[Drawables.TOP].setCallback(null); 2890 } 2891 dr.mShowing[Drawables.TOP] = null; 2892 if (dr.mDrawableEnd != null) { 2893 dr.mDrawableEnd.setCallback(null); 2894 } 2895 dr.mDrawableEnd = null; 2896 if (dr.mShowing[Drawables.BOTTOM] != null) { 2897 dr.mShowing[Drawables.BOTTOM].setCallback(null); 2898 } 2899 dr.mShowing[Drawables.BOTTOM] = null; 2900 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 2901 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 2902 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 2903 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 2904 } 2905 } 2906 } else { 2907 if (dr == null) { 2908 mDrawables = dr = new Drawables(getContext()); 2909 } 2910 2911 mDrawables.mOverride = true; 2912 2913 if (dr.mDrawableStart != start && dr.mDrawableStart != null) { 2914 dr.mDrawableStart.setCallback(null); 2915 } 2916 dr.mDrawableStart = start; 2917 2918 if (dr.mShowing[Drawables.TOP] != top && dr.mShowing[Drawables.TOP] != null) { 2919 dr.mShowing[Drawables.TOP].setCallback(null); 2920 } 2921 dr.mShowing[Drawables.TOP] = top; 2922 2923 if (dr.mDrawableEnd != end && dr.mDrawableEnd != null) { 2924 dr.mDrawableEnd.setCallback(null); 2925 } 2926 dr.mDrawableEnd = end; 2927 2928 if (dr.mShowing[Drawables.BOTTOM] != bottom && dr.mShowing[Drawables.BOTTOM] != null) { 2929 dr.mShowing[Drawables.BOTTOM].setCallback(null); 2930 } 2931 dr.mShowing[Drawables.BOTTOM] = bottom; 2932 2933 final Rect compoundRect = dr.mCompoundRect; 2934 int[] state; 2935 2936 state = getDrawableState(); 2937 2938 if (start != null) { 2939 start.setState(state); 2940 start.copyBounds(compoundRect); 2941 start.setCallback(this); 2942 dr.mDrawableSizeStart = compoundRect.width(); 2943 dr.mDrawableHeightStart = compoundRect.height(); 2944 } else { 2945 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 2946 } 2947 2948 if (end != null) { 2949 end.setState(state); 2950 end.copyBounds(compoundRect); 2951 end.setCallback(this); 2952 dr.mDrawableSizeEnd = compoundRect.width(); 2953 dr.mDrawableHeightEnd = compoundRect.height(); 2954 } else { 2955 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 2956 } 2957 2958 if (top != null) { 2959 top.setState(state); 2960 top.copyBounds(compoundRect); 2961 top.setCallback(this); 2962 dr.mDrawableSizeTop = compoundRect.height(); 2963 dr.mDrawableWidthTop = compoundRect.width(); 2964 } else { 2965 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 2966 } 2967 2968 if (bottom != null) { 2969 bottom.setState(state); 2970 bottom.copyBounds(compoundRect); 2971 bottom.setCallback(this); 2972 dr.mDrawableSizeBottom = compoundRect.height(); 2973 dr.mDrawableWidthBottom = compoundRect.width(); 2974 } else { 2975 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 2976 } 2977 } 2978 2979 resetResolvedDrawables(); 2980 resolveDrawables(); 2981 invalidate(); 2982 requestLayout(); 2983 } 2984 2985 /** 2986 * Sets the Drawables (if any) to appear to the start of, above, to the end 2987 * of, and below the text. Use 0 if you do not want a Drawable there. The 2988 * Drawables' bounds will be set to their intrinsic bounds. 2989 * <p> 2990 * Calling this method will overwrite any Drawables previously set using 2991 * {@link #setCompoundDrawables} or related methods. 2992 * 2993 * @param start Resource identifier of the start Drawable. 2994 * @param top Resource identifier of the top Drawable. 2995 * @param end Resource identifier of the end Drawable. 2996 * @param bottom Resource identifier of the bottom Drawable. 2997 * 2998 * @attr ref android.R.styleable#TextView_drawableStart 2999 * @attr ref android.R.styleable#TextView_drawableTop 3000 * @attr ref android.R.styleable#TextView_drawableEnd 3001 * @attr ref android.R.styleable#TextView_drawableBottom 3002 */ 3003 @android.view.RemotableViewMethod 3004 public void setCompoundDrawablesRelativeWithIntrinsicBounds(@DrawableRes int start, 3005 @DrawableRes int top, @DrawableRes int end, @DrawableRes int bottom) { 3006 final Context context = getContext(); 3007 setCompoundDrawablesRelativeWithIntrinsicBounds( 3008 start != 0 ? context.getDrawable(start) : null, 3009 top != 0 ? context.getDrawable(top) : null, 3010 end != 0 ? context.getDrawable(end) : null, 3011 bottom != 0 ? context.getDrawable(bottom) : null); 3012 } 3013 3014 /** 3015 * Sets the Drawables (if any) to appear to the start of, above, to the end 3016 * of, and below the text. Use {@code null} if you do not want a Drawable 3017 * there. The Drawables' bounds will be set to their intrinsic bounds. 3018 * <p> 3019 * Calling this method will overwrite any Drawables previously set using 3020 * {@link #setCompoundDrawables} or related methods. 3021 * 3022 * @attr ref android.R.styleable#TextView_drawableStart 3023 * @attr ref android.R.styleable#TextView_drawableTop 3024 * @attr ref android.R.styleable#TextView_drawableEnd 3025 * @attr ref android.R.styleable#TextView_drawableBottom 3026 */ 3027 @android.view.RemotableViewMethod 3028 public void setCompoundDrawablesRelativeWithIntrinsicBounds(@Nullable Drawable start, 3029 @Nullable Drawable top, @Nullable Drawable end, @Nullable Drawable bottom) { 3030 3031 if (start != null) { 3032 start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); 3033 } 3034 if (end != null) { 3035 end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); 3036 } 3037 if (top != null) { 3038 top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); 3039 } 3040 if (bottom != null) { 3041 bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); 3042 } 3043 setCompoundDrawablesRelative(start, top, end, bottom); 3044 } 3045 3046 /** 3047 * Returns drawables for the left, top, right, and bottom borders. 3048 * 3049 * @attr ref android.R.styleable#TextView_drawableLeft 3050 * @attr ref android.R.styleable#TextView_drawableTop 3051 * @attr ref android.R.styleable#TextView_drawableRight 3052 * @attr ref android.R.styleable#TextView_drawableBottom 3053 */ 3054 @NonNull 3055 public Drawable[] getCompoundDrawables() { 3056 final Drawables dr = mDrawables; 3057 if (dr != null) { 3058 return dr.mShowing.clone(); 3059 } else { 3060 return new Drawable[] { null, null, null, null }; 3061 } 3062 } 3063 3064 /** 3065 * Returns drawables for the start, top, end, and bottom borders. 3066 * 3067 * @attr ref android.R.styleable#TextView_drawableStart 3068 * @attr ref android.R.styleable#TextView_drawableTop 3069 * @attr ref android.R.styleable#TextView_drawableEnd 3070 * @attr ref android.R.styleable#TextView_drawableBottom 3071 */ 3072 @NonNull 3073 public Drawable[] getCompoundDrawablesRelative() { 3074 final Drawables dr = mDrawables; 3075 if (dr != null) { 3076 return new Drawable[] { 3077 dr.mDrawableStart, dr.mShowing[Drawables.TOP], 3078 dr.mDrawableEnd, dr.mShowing[Drawables.BOTTOM] 3079 }; 3080 } else { 3081 return new Drawable[] { null, null, null, null }; 3082 } 3083 } 3084 3085 /** 3086 * Sets the size of the padding between the compound drawables and 3087 * the text. 3088 * 3089 * @attr ref android.R.styleable#TextView_drawablePadding 3090 */ 3091 @android.view.RemotableViewMethod 3092 public void setCompoundDrawablePadding(int pad) { 3093 Drawables dr = mDrawables; 3094 if (pad == 0) { 3095 if (dr != null) { 3096 dr.mDrawablePadding = pad; 3097 } 3098 } else { 3099 if (dr == null) { 3100 mDrawables = dr = new Drawables(getContext()); 3101 } 3102 dr.mDrawablePadding = pad; 3103 } 3104 3105 invalidate(); 3106 requestLayout(); 3107 } 3108 3109 /** 3110 * Returns the padding between the compound drawables and the text. 3111 * 3112 * @attr ref android.R.styleable#TextView_drawablePadding 3113 */ 3114 public int getCompoundDrawablePadding() { 3115 final Drawables dr = mDrawables; 3116 return dr != null ? dr.mDrawablePadding : 0; 3117 } 3118 3119 /** 3120 * Applies a tint to the compound drawables. Does not modify the 3121 * current tint mode, which is {@link PorterDuff.Mode#SRC_IN} by default. 3122 * <p> 3123 * Subsequent calls to 3124 * {@link #setCompoundDrawables(Drawable, Drawable, Drawable, Drawable)} 3125 * and related methods will automatically mutate the drawables and apply 3126 * the specified tint and tint mode using 3127 * {@link Drawable#setTintList(ColorStateList)}. 3128 * 3129 * @param tint the tint to apply, may be {@code null} to clear tint 3130 * 3131 * @attr ref android.R.styleable#TextView_drawableTint 3132 * @see #getCompoundDrawableTintList() 3133 * @see Drawable#setTintList(ColorStateList) 3134 */ 3135 public void setCompoundDrawableTintList(@Nullable ColorStateList tint) { 3136 if (mDrawables == null) { 3137 mDrawables = new Drawables(getContext()); 3138 } 3139 mDrawables.mTintList = tint; 3140 mDrawables.mHasTint = true; 3141 3142 applyCompoundDrawableTint(); 3143 } 3144 3145 /** 3146 * @return the tint applied to the compound drawables 3147 * @attr ref android.R.styleable#TextView_drawableTint 3148 * @see #setCompoundDrawableTintList(ColorStateList) 3149 */ 3150 public ColorStateList getCompoundDrawableTintList() { 3151 return mDrawables != null ? mDrawables.mTintList : null; 3152 } 3153 3154 /** 3155 * Specifies the blending mode used to apply the tint specified by 3156 * {@link #setCompoundDrawableTintList(ColorStateList)} to the compound 3157 * drawables. The default mode is {@link PorterDuff.Mode#SRC_IN}. 3158 * 3159 * @param tintMode the blending mode used to apply the tint, may be 3160 * {@code null} to clear tint 3161 * @attr ref android.R.styleable#TextView_drawableTintMode 3162 * @see #setCompoundDrawableTintList(ColorStateList) 3163 * @see Drawable#setTintMode(PorterDuff.Mode) 3164 */ 3165 public void setCompoundDrawableTintMode(@Nullable PorterDuff.Mode tintMode) { 3166 if (mDrawables == null) { 3167 mDrawables = new Drawables(getContext()); 3168 } 3169 mDrawables.mTintMode = tintMode; 3170 mDrawables.mHasTintMode = true; 3171 3172 applyCompoundDrawableTint(); 3173 } 3174 3175 /** 3176 * Returns the blending mode used to apply the tint to the compound 3177 * drawables, if specified. 3178 * 3179 * @return the blending mode used to apply the tint to the compound 3180 * drawables 3181 * @attr ref android.R.styleable#TextView_drawableTintMode 3182 * @see #setCompoundDrawableTintMode(PorterDuff.Mode) 3183 */ 3184 public PorterDuff.Mode getCompoundDrawableTintMode() { 3185 return mDrawables != null ? mDrawables.mTintMode : null; 3186 } 3187 3188 private void applyCompoundDrawableTint() { 3189 if (mDrawables == null) { 3190 return; 3191 } 3192 3193 if (mDrawables.mHasTint || mDrawables.mHasTintMode) { 3194 final ColorStateList tintList = mDrawables.mTintList; 3195 final PorterDuff.Mode tintMode = mDrawables.mTintMode; 3196 final boolean hasTint = mDrawables.mHasTint; 3197 final boolean hasTintMode = mDrawables.mHasTintMode; 3198 final int[] state = getDrawableState(); 3199 3200 for (Drawable dr : mDrawables.mShowing) { 3201 if (dr == null) { 3202 continue; 3203 } 3204 3205 if (dr == mDrawables.mDrawableError) { 3206 // From a developer's perspective, the error drawable isn't 3207 // a compound drawable. Don't apply the generic compound 3208 // drawable tint to it. 3209 continue; 3210 } 3211 3212 dr.mutate(); 3213 3214 if (hasTint) { 3215 dr.setTintList(tintList); 3216 } 3217 3218 if (hasTintMode) { 3219 dr.setTintMode(tintMode); 3220 } 3221 3222 // The drawable (or one of its children) may not have been 3223 // stateful before applying the tint, so let's try again. 3224 if (dr.isStateful()) { 3225 dr.setState(state); 3226 } 3227 } 3228 } 3229 } 3230 3231 /** 3232 * @inheritDoc 3233 * 3234 * @see #setFirstBaselineToTopHeight(int) 3235 * @see #setLastBaselineToBottomHeight(int) 3236 */ 3237 @Override 3238 public void setPadding(int left, int top, int right, int bottom) { 3239 if (left != mPaddingLeft 3240 || right != mPaddingRight 3241 || top != mPaddingTop 3242 || bottom != mPaddingBottom) { 3243 nullLayouts(); 3244 } 3245 3246 // the super call will requestLayout() 3247 super.setPadding(left, top, right, bottom); 3248 invalidate(); 3249 } 3250 3251 /** 3252 * @inheritDoc 3253 * 3254 * @see #setFirstBaselineToTopHeight(int) 3255 * @see #setLastBaselineToBottomHeight(int) 3256 */ 3257 @Override 3258 public void setPaddingRelative(int start, int top, int end, int bottom) { 3259 if (start != getPaddingStart() 3260 || end != getPaddingEnd() 3261 || top != mPaddingTop 3262 || bottom != mPaddingBottom) { 3263 nullLayouts(); 3264 } 3265 3266 // the super call will requestLayout() 3267 super.setPaddingRelative(start, top, end, bottom); 3268 invalidate(); 3269 } 3270 3271 /** 3272 * Updates the top padding of the TextView so that {@code firstBaselineToTopHeight} is 3273 * equal to the distance between the firt text baseline and the top of this TextView. 3274 * <strong>Note</strong> that if {@code FontMetrics.top} or {@code FontMetrics.ascent} was 3275 * already greater than {@code firstBaselineToTopHeight}, the top padding is not updated. 3276 * 3277 * @param firstBaselineToTopHeight distance between first baseline to top of the container 3278 * in pixels 3279 * 3280 * @see #getFirstBaselineToTopHeight() 3281 * @see #setPadding(int, int, int, int) 3282 * @see #setPaddingRelative(int, int, int, int) 3283 * 3284 * @attr ref android.R.styleable#TextView_firstBaselineToTopHeight 3285 */ 3286 public void setFirstBaselineToTopHeight(@Px @IntRange(from = 0) int firstBaselineToTopHeight) { 3287 Preconditions.checkArgumentNonnegative(firstBaselineToTopHeight); 3288 3289 final FontMetricsInt fontMetrics = getPaint().getFontMetricsInt(); 3290 final int fontMetricsTop; 3291 if (getIncludeFontPadding()) { 3292 fontMetricsTop = fontMetrics.top; 3293 } else { 3294 fontMetricsTop = fontMetrics.ascent; 3295 } 3296 3297 // TODO: Decide if we want to ignore density ratio (i.e. when the user changes font size 3298 // in settings). At the moment, we don't. 3299 3300 if (firstBaselineToTopHeight > Math.abs(fontMetricsTop)) { 3301 final int paddingTop = firstBaselineToTopHeight - (-fontMetricsTop); 3302 setPadding(getPaddingLeft(), paddingTop, getPaddingRight(), getPaddingBottom()); 3303 } 3304 } 3305 3306 /** 3307 * Updates the bottom padding of the TextView so that {@code lastBaselineToBottomHeight} is 3308 * equal to the distance between the last text baseline and the bottom of this TextView. 3309 * <strong>Note</strong> that if {@code FontMetrics.bottom} or {@code FontMetrics.descent} was 3310 * already greater than {@code lastBaselineToBottomHeight}, the bottom padding is not updated. 3311 * 3312 * @param lastBaselineToBottomHeight distance between last baseline to bottom of the container 3313 * in pixels 3314 * 3315 * @see #getLastBaselineToBottomHeight() 3316 * @see #setPadding(int, int, int, int) 3317 * @see #setPaddingRelative(int, int, int, int) 3318 * 3319 * @attr ref android.R.styleable#TextView_lastBaselineToBottomHeight 3320 */ 3321 public void setLastBaselineToBottomHeight( 3322 @Px @IntRange(from = 0) int lastBaselineToBottomHeight) { 3323 Preconditions.checkArgumentNonnegative(lastBaselineToBottomHeight); 3324 3325 final FontMetricsInt fontMetrics = getPaint().getFontMetricsInt(); 3326 final int fontMetricsBottom; 3327 if (getIncludeFontPadding()) { 3328 fontMetricsBottom = fontMetrics.bottom; 3329 } else { 3330 fontMetricsBottom = fontMetrics.descent; 3331 } 3332 3333 // TODO: Decide if we want to ignore density ratio (i.e. when the user changes font size 3334 // in settings). At the moment, we don't. 3335 3336 if (lastBaselineToBottomHeight > Math.abs(fontMetricsBottom)) { 3337 final int paddingBottom = lastBaselineToBottomHeight - fontMetricsBottom; 3338 setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), paddingBottom); 3339 } 3340 } 3341 3342 /** 3343 * Returns the distance between the first text baseline and the top of this TextView. 3344 * 3345 * @see #setFirstBaselineToTopHeight(int) 3346 * @attr ref android.R.styleable#TextView_firstBaselineToTopHeight 3347 */ 3348 public int getFirstBaselineToTopHeight() { 3349 return getPaddingTop() - getPaint().getFontMetricsInt().top; 3350 } 3351 3352 /** 3353 * Returns the distance between the last text baseline and the bottom of this TextView. 3354 * 3355 * @see #setLastBaselineToBottomHeight(int) 3356 * @attr ref android.R.styleable#TextView_lastBaselineToBottomHeight 3357 */ 3358 public int getLastBaselineToBottomHeight() { 3359 return getPaddingBottom() + getPaint().getFontMetricsInt().bottom; 3360 } 3361 3362 /** 3363 * Gets the autolink mask of the text. See {@link 3364 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 3365 * possible values. 3366 * 3367 * @attr ref android.R.styleable#TextView_autoLink 3368 */ 3369 public final int getAutoLinkMask() { 3370 return mAutoLinkMask; 3371 } 3372 3373 /** 3374 * Sets the text appearance from the specified style resource. 3375 * <p> 3376 * Use a framework-defined {@code TextAppearance} style like 3377 * {@link android.R.style#TextAppearance_Material_Body1 @android:style/TextAppearance.Material.Body1} 3378 * or see {@link android.R.styleable#TextAppearance TextAppearance} for the 3379 * set of attributes that can be used in a custom style. 3380 * 3381 * @param resId the resource identifier of the style to apply 3382 * @attr ref android.R.styleable#TextView_textAppearance 3383 */ 3384 @SuppressWarnings("deprecation") 3385 public void setTextAppearance(@StyleRes int resId) { 3386 setTextAppearance(mContext, resId); 3387 } 3388 3389 /** 3390 * Sets the text color, size, style, hint color, and highlight color 3391 * from the specified TextAppearance resource. 3392 * 3393 * @deprecated Use {@link #setTextAppearance(int)} instead. 3394 */ 3395 @Deprecated 3396 public void setTextAppearance(Context context, @StyleRes int resId) { 3397 final TypedArray ta = context.obtainStyledAttributes(resId, R.styleable.TextAppearance); 3398 final TextAppearanceAttributes attributes = new TextAppearanceAttributes(); 3399 readTextAppearance(context, ta, attributes, false /* styleArray */); 3400 ta.recycle(); 3401 applyTextAppearance(attributes); 3402 } 3403 3404 /** 3405 * Set of attributes that can be defined in a Text Appearance. This is used to simplify the code 3406 * that reads these attributes in the constructor and in {@link #setTextAppearance}. 3407 */ 3408 private static class TextAppearanceAttributes { 3409 int mTextColorHighlight = 0; 3410 ColorStateList mTextColor = null; 3411 ColorStateList mTextColorHint = null; 3412 ColorStateList mTextColorLink = null; 3413 int mTextSize = 0; 3414 String mFontFamily = null; 3415 Typeface mFontTypeface = null; 3416 boolean mFontFamilyExplicit = false; 3417 int mTypefaceIndex = -1; 3418 int mStyleIndex = -1; 3419 int mFontWeight = -1; 3420 boolean mAllCaps = false; 3421 int mShadowColor = 0; 3422 float mShadowDx = 0, mShadowDy = 0, mShadowRadius = 0; 3423 boolean mHasElegant = false; 3424 boolean mElegant = false; 3425 boolean mHasFallbackLineSpacing = false; 3426 boolean mFallbackLineSpacing = false; 3427 boolean mHasLetterSpacing = false; 3428 float mLetterSpacing = 0; 3429 String mFontFeatureSettings = null; 3430 3431 @Override 3432 public String toString() { 3433 return "TextAppearanceAttributes {\n" 3434 + " mTextColorHighlight:" + mTextColorHighlight + "\n" 3435 + " mTextColor:" + mTextColor + "\n" 3436 + " mTextColorHint:" + mTextColorHint + "\n" 3437 + " mTextColorLink:" + mTextColorLink + "\n" 3438 + " mTextSize:" + mTextSize + "\n" 3439 + " mFontFamily:" + mFontFamily + "\n" 3440 + " mFontTypeface:" + mFontTypeface + "\n" 3441 + " mFontFamilyExplicit:" + mFontFamilyExplicit + "\n" 3442 + " mTypefaceIndex:" + mTypefaceIndex + "\n" 3443 + " mStyleIndex:" + mStyleIndex + "\n" 3444 + " mFontWeight:" + mFontWeight + "\n" 3445 + " mAllCaps:" + mAllCaps + "\n" 3446 + " mShadowColor:" + mShadowColor + "\n" 3447 + " mShadowDx:" + mShadowDx + "\n" 3448 + " mShadowDy:" + mShadowDy + "\n" 3449 + " mShadowRadius:" + mShadowRadius + "\n" 3450 + " mHasElegant:" + mHasElegant + "\n" 3451 + " mElegant:" + mElegant + "\n" 3452 + " mHasFallbackLineSpacing:" + mHasFallbackLineSpacing + "\n" 3453 + " mFallbackLineSpacing:" + mFallbackLineSpacing + "\n" 3454 + " mHasLetterSpacing:" + mHasLetterSpacing + "\n" 3455 + " mLetterSpacing:" + mLetterSpacing + "\n" 3456 + " mFontFeatureSettings:" + mFontFeatureSettings + "\n" 3457 + "}"; 3458 } 3459 } 3460 3461 // Maps styleable attributes that exist both in TextView style and TextAppearance. 3462 private static final SparseIntArray sAppearanceValues = new SparseIntArray(); 3463 static { 3464 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textColorHighlight, 3465 com.android.internal.R.styleable.TextAppearance_textColorHighlight); 3466 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textColor, 3467 com.android.internal.R.styleable.TextAppearance_textColor); 3468 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textColorHint, 3469 com.android.internal.R.styleable.TextAppearance_textColorHint); 3470 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textColorLink, 3471 com.android.internal.R.styleable.TextAppearance_textColorLink); 3472 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textSize, 3473 com.android.internal.R.styleable.TextAppearance_textSize); 3474 sAppearanceValues.put(com.android.internal.R.styleable.TextView_typeface, 3475 com.android.internal.R.styleable.TextAppearance_typeface); 3476 sAppearanceValues.put(com.android.internal.R.styleable.TextView_fontFamily, 3477 com.android.internal.R.styleable.TextAppearance_fontFamily); 3478 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textStyle, 3479 com.android.internal.R.styleable.TextAppearance_textStyle); 3480 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textFontWeight, 3481 com.android.internal.R.styleable.TextAppearance_textFontWeight); 3482 sAppearanceValues.put(com.android.internal.R.styleable.TextView_textAllCaps, 3483 com.android.internal.R.styleable.TextAppearance_textAllCaps); 3484 sAppearanceValues.put(com.android.internal.R.styleable.TextView_shadowColor, 3485 com.android.internal.R.styleable.TextAppearance_shadowColor); 3486 sAppearanceValues.put(com.android.internal.R.styleable.TextView_shadowDx, 3487 com.android.internal.R.styleable.TextAppearance_shadowDx); 3488 sAppearanceValues.put(com.android.internal.R.styleable.TextView_shadowDy, 3489 com.android.internal.R.styleable.TextAppearance_shadowDy); 3490 sAppearanceValues.put(com.android.internal.R.styleable.TextView_shadowRadius, 3491 com.android.internal.R.styleable.TextAppearance_shadowRadius); 3492 sAppearanceValues.put(com.android.internal.R.styleable.TextView_elegantTextHeight, 3493 com.android.internal.R.styleable.TextAppearance_elegantTextHeight); 3494 sAppearanceValues.put(com.android.internal.R.styleable.TextView_fallbackLineSpacing, 3495 com.android.internal.R.styleable.TextAppearance_fallbackLineSpacing); 3496 sAppearanceValues.put(com.android.internal.R.styleable.TextView_letterSpacing, 3497 com.android.internal.R.styleable.TextAppearance_letterSpacing); 3498 sAppearanceValues.put(com.android.internal.R.styleable.TextView_fontFeatureSettings, 3499 com.android.internal.R.styleable.TextAppearance_fontFeatureSettings); 3500 } 3501 3502 /** 3503 * Read the Text Appearance attributes from a given TypedArray and set its values to the given 3504 * set. If the TypedArray contains a value that was already set in the given attributes, that 3505 * will be overriden. 3506 * 3507 * @param context The Context to be used 3508 * @param appearance The TypedArray to read properties from 3509 * @param attributes the TextAppearanceAttributes to fill in 3510 * @param styleArray Whether the given TypedArray is a style or a TextAppearance. This defines 3511 * what attribute indexes will be used to read the properties. 3512 */ 3513 private void readTextAppearance(Context context, TypedArray appearance, 3514 TextAppearanceAttributes attributes, boolean styleArray) { 3515 final int n = appearance.getIndexCount(); 3516 for (int i = 0; i < n; i++) { 3517 final int attr = appearance.getIndex(i); 3518 int index = attr; 3519 // Translate style array index ids to TextAppearance ids. 3520 if (styleArray) { 3521 index = sAppearanceValues.get(attr, -1); 3522 if (index == -1) { 3523 // This value is not part of a Text Appearance and should be ignored. 3524 continue; 3525 } 3526 } 3527 switch (index) { 3528 case com.android.internal.R.styleable.TextAppearance_textColorHighlight: 3529 attributes.mTextColorHighlight = 3530 appearance.getColor(attr, attributes.mTextColorHighlight); 3531 break; 3532 case com.android.internal.R.styleable.TextAppearance_textColor: 3533 attributes.mTextColor = appearance.getColorStateList(attr); 3534 break; 3535 case com.android.internal.R.styleable.TextAppearance_textColorHint: 3536 attributes.mTextColorHint = appearance.getColorStateList(attr); 3537 break; 3538 case com.android.internal.R.styleable.TextAppearance_textColorLink: 3539 attributes.mTextColorLink = appearance.getColorStateList(attr); 3540 break; 3541 case com.android.internal.R.styleable.TextAppearance_textSize: 3542 attributes.mTextSize = 3543 appearance.getDimensionPixelSize(attr, attributes.mTextSize); 3544 break; 3545 case com.android.internal.R.styleable.TextAppearance_typeface: 3546 attributes.mTypefaceIndex = appearance.getInt(attr, attributes.mTypefaceIndex); 3547 if (attributes.mTypefaceIndex != -1 && !attributes.mFontFamilyExplicit) { 3548 attributes.mFontFamily = null; 3549 } 3550 break; 3551 case com.android.internal.R.styleable.TextAppearance_fontFamily: 3552 if (!context.isRestricted() && context.canLoadUnsafeResources()) { 3553 try { 3554 attributes.mFontTypeface = appearance.getFont(attr); 3555 } catch (UnsupportedOperationException | Resources.NotFoundException e) { 3556 // Expected if it is not a font resource. 3557 } 3558 } 3559 if (attributes.mFontTypeface == null) { 3560 attributes.mFontFamily = appearance.getString(attr); 3561 } 3562 attributes.mFontFamilyExplicit = true; 3563 break; 3564 case com.android.internal.R.styleable.TextAppearance_textStyle: 3565 attributes.mStyleIndex = appearance.getInt(attr, attributes.mStyleIndex); 3566 break; 3567 case com.android.internal.R.styleable.TextAppearance_textFontWeight: 3568 attributes.mFontWeight = appearance.getInt(attr, attributes.mFontWeight); 3569 break; 3570 case com.android.internal.R.styleable.TextAppearance_textAllCaps: 3571 attributes.mAllCaps = appearance.getBoolean(attr, attributes.mAllCaps); 3572 break; 3573 case com.android.internal.R.styleable.TextAppearance_shadowColor: 3574 attributes.mShadowColor = appearance.getInt(attr, attributes.mShadowColor); 3575 break; 3576 case com.android.internal.R.styleable.TextAppearance_shadowDx: 3577 attributes.mShadowDx = appearance.getFloat(attr, attributes.mShadowDx); 3578 break; 3579 case com.android.internal.R.styleable.TextAppearance_shadowDy: 3580 attributes.mShadowDy = appearance.getFloat(attr, attributes.mShadowDy); 3581 break; 3582 case com.android.internal.R.styleable.TextAppearance_shadowRadius: 3583 attributes.mShadowRadius = appearance.getFloat(attr, attributes.mShadowRadius); 3584 break; 3585 case com.android.internal.R.styleable.TextAppearance_elegantTextHeight: 3586 attributes.mHasElegant = true; 3587 attributes.mElegant = appearance.getBoolean(attr, attributes.mElegant); 3588 break; 3589 case com.android.internal.R.styleable.TextAppearance_fallbackLineSpacing: 3590 attributes.mHasFallbackLineSpacing = true; 3591 attributes.mFallbackLineSpacing = appearance.getBoolean(attr, 3592 attributes.mFallbackLineSpacing); 3593 break; 3594 case com.android.internal.R.styleable.TextAppearance_letterSpacing: 3595 attributes.mHasLetterSpacing = true; 3596 attributes.mLetterSpacing = 3597 appearance.getFloat(attr, attributes.mLetterSpacing); 3598 break; 3599 case com.android.internal.R.styleable.TextAppearance_fontFeatureSettings: 3600 attributes.mFontFeatureSettings = appearance.getString(attr); 3601 break; 3602 default: 3603 } 3604 } 3605 } 3606 3607 private void applyTextAppearance(TextAppearanceAttributes attributes) { 3608 if (attributes.mTextColor != null) { 3609 setTextColor(attributes.mTextColor); 3610 } 3611 3612 if (attributes.mTextColorHint != null) { 3613 setHintTextColor(attributes.mTextColorHint); 3614 } 3615 3616 if (attributes.mTextColorLink != null) { 3617 setLinkTextColor(attributes.mTextColorLink); 3618 } 3619 3620 if (attributes.mTextColorHighlight != 0) { 3621 setHighlightColor(attributes.mTextColorHighlight); 3622 } 3623 3624 if (attributes.mTextSize != 0) { 3625 setRawTextSize(attributes.mTextSize, true /* shouldRequestLayout */); 3626 } 3627 3628 if (attributes.mTypefaceIndex != -1 && !attributes.mFontFamilyExplicit) { 3629 attributes.mFontFamily = null; 3630 } 3631 setTypefaceFromAttrs(attributes.mFontTypeface, attributes.mFontFamily, 3632 attributes.mTypefaceIndex, attributes.mStyleIndex, attributes.mFontWeight); 3633 3634 if (attributes.mShadowColor != 0) { 3635 setShadowLayer(attributes.mShadowRadius, attributes.mShadowDx, attributes.mShadowDy, 3636 attributes.mShadowColor); 3637 } 3638 3639 if (attributes.mAllCaps) { 3640 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 3641 } 3642 3643 if (attributes.mHasElegant) { 3644 setElegantTextHeight(attributes.mElegant); 3645 } 3646 3647 if (attributes.mHasFallbackLineSpacing) { 3648 setFallbackLineSpacing(attributes.mFallbackLineSpacing); 3649 } 3650 3651 if (attributes.mHasLetterSpacing) { 3652 setLetterSpacing(attributes.mLetterSpacing); 3653 } 3654 3655 if (attributes.mFontFeatureSettings != null) { 3656 setFontFeatureSettings(attributes.mFontFeatureSettings); 3657 } 3658 } 3659 3660 /** 3661 * Get the default primary {@link Locale} of the text in this TextView. This will always be 3662 * the first member of {@link #getTextLocales()}. 3663 * @return the default primary {@link Locale} of the text in this TextView. 3664 */ 3665 @NonNull 3666 public Locale getTextLocale() { 3667 return mTextPaint.getTextLocale(); 3668 } 3669 3670 /** 3671 * Get the default {@link LocaleList} of the text in this TextView. 3672 * @return the default {@link LocaleList} of the text in this TextView. 3673 */ 3674 @NonNull @Size(min = 1) 3675 public LocaleList getTextLocales() { 3676 return mTextPaint.getTextLocales(); 3677 } 3678 3679 private void changeListenerLocaleTo(@Nullable Locale locale) { 3680 if (mListenerChanged) { 3681 // If a listener has been explicitly set, don't change it. We may break something. 3682 return; 3683 } 3684 // The following null check is not absolutely necessary since all calling points of 3685 // changeListenerLocaleTo() guarantee a non-null mEditor at the moment. But this is left 3686 // here in case others would want to call this method in the future. 3687 if (mEditor != null) { 3688 KeyListener listener = mEditor.mKeyListener; 3689 if (listener instanceof DigitsKeyListener) { 3690 listener = DigitsKeyListener.getInstance(locale, (DigitsKeyListener) listener); 3691 } else if (listener instanceof DateKeyListener) { 3692 listener = DateKeyListener.getInstance(locale); 3693 } else if (listener instanceof TimeKeyListener) { 3694 listener = TimeKeyListener.getInstance(locale); 3695 } else if (listener instanceof DateTimeKeyListener) { 3696 listener = DateTimeKeyListener.getInstance(locale); 3697 } else { 3698 return; 3699 } 3700 final boolean wasPasswordType = isPasswordInputType(mEditor.mInputType); 3701 setKeyListenerOnly(listener); 3702 setInputTypeFromEditor(); 3703 if (wasPasswordType) { 3704 final int newInputClass = mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS; 3705 if (newInputClass == EditorInfo.TYPE_CLASS_TEXT) { 3706 mEditor.mInputType |= EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 3707 } else if (newInputClass == EditorInfo.TYPE_CLASS_NUMBER) { 3708 mEditor.mInputType |= EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD; 3709 } 3710 } 3711 } 3712 } 3713 3714 /** 3715 * Set the default {@link Locale} of the text in this TextView to a one-member 3716 * {@link LocaleList} containing just the given Locale. 3717 * 3718 * @param locale the {@link Locale} for drawing text, must not be null. 3719 * 3720 * @see #setTextLocales 3721 */ 3722 public void setTextLocale(@NonNull Locale locale) { 3723 mLocalesChanged = true; 3724 mTextPaint.setTextLocale(locale); 3725 if (mLayout != null) { 3726 nullLayouts(); 3727 requestLayout(); 3728 invalidate(); 3729 } 3730 } 3731 3732 /** 3733 * Set the default {@link LocaleList} of the text in this TextView to the given value. 3734 * 3735 * This value is used to choose appropriate typefaces for ambiguous characters (typically used 3736 * for CJK locales to disambiguate Hanzi/Kanji/Hanja characters). It also affects 3737 * other aspects of text display, including line breaking. 3738 * 3739 * @param locales the {@link LocaleList} for drawing text, must not be null or empty. 3740 * 3741 * @see Paint#setTextLocales 3742 */ 3743 public void setTextLocales(@NonNull @Size(min = 1) LocaleList locales) { 3744 mLocalesChanged = true; 3745 mTextPaint.setTextLocales(locales); 3746 if (mLayout != null) { 3747 nullLayouts(); 3748 requestLayout(); 3749 invalidate(); 3750 } 3751 } 3752 3753 @Override 3754 protected void onConfigurationChanged(Configuration newConfig) { 3755 super.onConfigurationChanged(newConfig); 3756 if (!mLocalesChanged) { 3757 mTextPaint.setTextLocales(LocaleList.getDefault()); 3758 if (mLayout != null) { 3759 nullLayouts(); 3760 requestLayout(); 3761 invalidate(); 3762 } 3763 } 3764 } 3765 3766 /** 3767 * @return the size (in pixels) of the default text size in this TextView. 3768 */ 3769 @ViewDebug.ExportedProperty(category = "text") 3770 public float getTextSize() { 3771 return mTextPaint.getTextSize(); 3772 } 3773 3774 /** 3775 * @return the size (in scaled pixels) of the default text size in this TextView. 3776 * @hide 3777 */ 3778 @ViewDebug.ExportedProperty(category = "text") 3779 public float getScaledTextSize() { 3780 return mTextPaint.getTextSize() / mTextPaint.density; 3781 } 3782 3783 /** @hide */ 3784 @ViewDebug.ExportedProperty(category = "text", mapping = { 3785 @ViewDebug.IntToString(from = Typeface.NORMAL, to = "NORMAL"), 3786 @ViewDebug.IntToString(from = Typeface.BOLD, to = "BOLD"), 3787 @ViewDebug.IntToString(from = Typeface.ITALIC, to = "ITALIC"), 3788 @ViewDebug.IntToString(from = Typeface.BOLD_ITALIC, to = "BOLD_ITALIC") 3789 }) 3790 public int getTypefaceStyle() { 3791 Typeface typeface = mTextPaint.getTypeface(); 3792 return typeface != null ? typeface.getStyle() : Typeface.NORMAL; 3793 } 3794 3795 /** 3796 * Set the default text size to the given value, interpreted as "scaled 3797 * pixel" units. This size is adjusted based on the current density and 3798 * user font size preference. 3799 * 3800 * <p>Note: if this TextView has the auto-size feature enabled than this function is no-op. 3801 * 3802 * @param size The scaled pixel size. 3803 * 3804 * @attr ref android.R.styleable#TextView_textSize 3805 */ 3806 @android.view.RemotableViewMethod 3807 public void setTextSize(float size) { 3808 setTextSize(TypedValue.COMPLEX_UNIT_SP, size); 3809 } 3810 3811 /** 3812 * Set the default text size to a given unit and value. See {@link 3813 * TypedValue} for the possible dimension units. 3814 * 3815 * <p>Note: if this TextView has the auto-size feature enabled than this function is no-op. 3816 * 3817 * @param unit The desired dimension unit. 3818 * @param size The desired size in the given units. 3819 * 3820 * @attr ref android.R.styleable#TextView_textSize 3821 */ 3822 public void setTextSize(int unit, float size) { 3823 if (!isAutoSizeEnabled()) { 3824 setTextSizeInternal(unit, size, true /* shouldRequestLayout */); 3825 } 3826 } 3827 3828 private void setTextSizeInternal(int unit, float size, boolean shouldRequestLayout) { 3829 Context c = getContext(); 3830 Resources r; 3831 3832 if (c == null) { 3833 r = Resources.getSystem(); 3834 } else { 3835 r = c.getResources(); 3836 } 3837 3838 setRawTextSize(TypedValue.applyDimension(unit, size, r.getDisplayMetrics()), 3839 shouldRequestLayout); 3840 } 3841 3842 private void setRawTextSize(float size, boolean shouldRequestLayout) { 3843 if (size != mTextPaint.getTextSize()) { 3844 mTextPaint.setTextSize(size); 3845 3846 if (shouldRequestLayout && mLayout != null) { 3847 // Do not auto-size right after setting the text size. 3848 mNeedsAutoSizeText = false; 3849 nullLayouts(); 3850 requestLayout(); 3851 invalidate(); 3852 } 3853 } 3854 } 3855 3856 /** 3857 * Gets the extent by which text should be stretched horizontally. 3858 * This will usually be 1.0. 3859 * @return The horizontal scale factor. 3860 */ 3861 public float getTextScaleX() { 3862 return mTextPaint.getTextScaleX(); 3863 } 3864 3865 /** 3866 * Sets the horizontal scale factor for text. The default value 3867 * is 1.0. Values greater than 1.0 stretch the text wider. 3868 * Values less than 1.0 make the text narrower. By default, this value is 1.0. 3869 * @param size The horizontal scale factor. 3870 * @attr ref android.R.styleable#TextView_textScaleX 3871 */ 3872 @android.view.RemotableViewMethod 3873 public void setTextScaleX(float size) { 3874 if (size != mTextPaint.getTextScaleX()) { 3875 mUserSetTextScaleX = true; 3876 mTextPaint.setTextScaleX(size); 3877 3878 if (mLayout != null) { 3879 nullLayouts(); 3880 requestLayout(); 3881 invalidate(); 3882 } 3883 } 3884 } 3885 3886 /** 3887 * Sets the typeface and style in which the text should be displayed. 3888 * Note that not all Typeface families actually have bold and italic 3889 * variants, so you may need to use 3890 * {@link #setTypeface(Typeface, int)} to get the appearance 3891 * that you actually want. 3892 * 3893 * @see #getTypeface() 3894 * 3895 * @attr ref android.R.styleable#TextView_fontFamily 3896 * @attr ref android.R.styleable#TextView_typeface 3897 * @attr ref android.R.styleable#TextView_textStyle 3898 */ 3899 public void setTypeface(@Nullable Typeface tf) { 3900 if (mTextPaint.getTypeface() != tf) { 3901 mTextPaint.setTypeface(tf); 3902 3903 if (mLayout != null) { 3904 nullLayouts(); 3905 requestLayout(); 3906 invalidate(); 3907 } 3908 } 3909 } 3910 3911 /** 3912 * Gets the current {@link Typeface} that is used to style the text. 3913 * @return The current Typeface. 3914 * 3915 * @see #setTypeface(Typeface) 3916 * 3917 * @attr ref android.R.styleable#TextView_fontFamily 3918 * @attr ref android.R.styleable#TextView_typeface 3919 * @attr ref android.R.styleable#TextView_textStyle 3920 */ 3921 public Typeface getTypeface() { 3922 return mTextPaint.getTypeface(); 3923 } 3924 3925 /** 3926 * Set the TextView's elegant height metrics flag. This setting selects font 3927 * variants that have not been compacted to fit Latin-based vertical 3928 * metrics, and also increases top and bottom bounds to provide more space. 3929 * 3930 * @param elegant set the paint's elegant metrics flag. 3931 * 3932 * @see #isElegantTextHeight() 3933 * @see Paint#isElegantTextHeight() 3934 * 3935 * @attr ref android.R.styleable#TextView_elegantTextHeight 3936 */ 3937 public void setElegantTextHeight(boolean elegant) { 3938 if (elegant != mTextPaint.isElegantTextHeight()) { 3939 mTextPaint.setElegantTextHeight(elegant); 3940 if (mLayout != null) { 3941 nullLayouts(); 3942 requestLayout(); 3943 invalidate(); 3944 } 3945 } 3946 } 3947 3948 /** 3949 * Set whether to respect the ascent and descent of the fallback fonts that are used in 3950 * displaying the text (which is needed to avoid text from consecutive lines running into 3951 * each other). If set, fallback fonts that end up getting used can increase the ascent 3952 * and descent of the lines that they are used on. 3953 * <p/> 3954 * It is required to be true if text could be in languages like Burmese or Tibetan where text 3955 * is typically much taller or deeper than Latin text. 3956 * 3957 * @param enabled whether to expand linespacing based on fallback fonts, {@code true} by default 3958 * 3959 * @see StaticLayout.Builder#setUseLineSpacingFromFallbacks(boolean) 3960 * 3961 * @attr ref android.R.styleable#TextView_fallbackLineSpacing 3962 */ 3963 public void setFallbackLineSpacing(boolean enabled) { 3964 if (mUseFallbackLineSpacing != enabled) { 3965 mUseFallbackLineSpacing = enabled; 3966 if (mLayout != null) { 3967 nullLayouts(); 3968 requestLayout(); 3969 invalidate(); 3970 } 3971 } 3972 } 3973 3974 /** 3975 * @return whether fallback line spacing is enabled, {@code true} by default 3976 * 3977 * @see #setFallbackLineSpacing(boolean) 3978 * 3979 * @attr ref android.R.styleable#TextView_fallbackLineSpacing 3980 */ 3981 public boolean isFallbackLineSpacing() { 3982 return mUseFallbackLineSpacing; 3983 } 3984 3985 /** 3986 * Get the value of the TextView's elegant height metrics flag. This setting selects font 3987 * variants that have not been compacted to fit Latin-based vertical 3988 * metrics, and also increases top and bottom bounds to provide more space. 3989 * @return {@code true} if the elegant height metrics flag is set. 3990 * 3991 * @see #setElegantTextHeight(boolean) 3992 * @see Paint#setElegantTextHeight(boolean) 3993 */ 3994 public boolean isElegantTextHeight() { 3995 return mTextPaint.isElegantTextHeight(); 3996 } 3997 3998 /** 3999 * Gets the text letter-space value, which determines the spacing between characters. 4000 * The value returned is in ems. Normally, this value is 0.0. 4001 * @return The text letter-space value in ems. 4002 * 4003 * @see #setLetterSpacing(float) 4004 * @see Paint#setLetterSpacing 4005 */ 4006 public float getLetterSpacing() { 4007 return mTextPaint.getLetterSpacing(); 4008 } 4009 4010 /** 4011 * Sets text letter-spacing in em units. Typical values 4012 * for slight expansion will be around 0.05. Negative values tighten text. 4013 * 4014 * @see #getLetterSpacing() 4015 * @see Paint#getLetterSpacing 4016 * 4017 * @param letterSpacing A text letter-space value in ems. 4018 * @attr ref android.R.styleable#TextView_letterSpacing 4019 */ 4020 @android.view.RemotableViewMethod 4021 public void setLetterSpacing(float letterSpacing) { 4022 if (letterSpacing != mTextPaint.getLetterSpacing()) { 4023 mTextPaint.setLetterSpacing(letterSpacing); 4024 4025 if (mLayout != null) { 4026 nullLayouts(); 4027 requestLayout(); 4028 invalidate(); 4029 } 4030 } 4031 } 4032 4033 /** 4034 * Returns the font feature settings. The format is the same as the CSS 4035 * font-feature-settings attribute: 4036 * <a href="https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop"> 4037 * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop</a> 4038 * 4039 * @return the currently set font feature settings. Default is null. 4040 * 4041 * @see #setFontFeatureSettings(String) 4042 * @see Paint#setFontFeatureSettings(String) Paint.setFontFeatureSettings(String) 4043 */ 4044 @Nullable 4045 public String getFontFeatureSettings() { 4046 return mTextPaint.getFontFeatureSettings(); 4047 } 4048 4049 /** 4050 * Returns the font variation settings. 4051 * 4052 * @return the currently set font variation settings. Returns null if no variation is 4053 * specified. 4054 * 4055 * @see #setFontVariationSettings(String) 4056 * @see Paint#setFontVariationSettings(String) Paint.setFontVariationSettings(String) 4057 */ 4058 @Nullable 4059 public String getFontVariationSettings() { 4060 return mTextPaint.getFontVariationSettings(); 4061 } 4062 4063 /** 4064 * Sets the break strategy for breaking paragraphs into lines. The default value for 4065 * TextView is {@link Layout#BREAK_STRATEGY_HIGH_QUALITY}, and the default value for 4066 * EditText is {@link Layout#BREAK_STRATEGY_SIMPLE}, the latter to avoid the 4067 * text "dancing" when being edited. 4068 * 4069 * @attr ref android.R.styleable#TextView_breakStrategy 4070 * @see #getBreakStrategy() 4071 */ 4072 public void setBreakStrategy(@Layout.BreakStrategy int breakStrategy) { 4073 mBreakStrategy = breakStrategy; 4074 if (mLayout != null) { 4075 nullLayouts(); 4076 requestLayout(); 4077 invalidate(); 4078 } 4079 } 4080 4081 /** 4082 * Gets the current strategy for breaking paragraphs into lines. 4083 * @return the current strategy for breaking paragraphs into lines. 4084 * 4085 * @attr ref android.R.styleable#TextView_breakStrategy 4086 * @see #setBreakStrategy(int) 4087 */ 4088 @Layout.BreakStrategy 4089 public int getBreakStrategy() { 4090 return mBreakStrategy; 4091 } 4092 4093 /** 4094 * Sets the frequency of automatic hyphenation to use when determining word breaks. 4095 * The default value for both TextView and {@link EditText} is 4096 * {@link Layout#HYPHENATION_FREQUENCY_NORMAL}. 4097 * Note that the default hyphenation frequency value is set from the theme. 4098 * 4099 * @param hyphenationFrequency The hyphenation frequency to use. 4100 * @attr ref android.R.styleable#TextView_hyphenationFrequency 4101 * @see #getHyphenationFrequency() 4102 */ 4103 public void setHyphenationFrequency(@Layout.HyphenationFrequency int hyphenationFrequency) { 4104 mHyphenationFrequency = hyphenationFrequency; 4105 if (mLayout != null) { 4106 nullLayouts(); 4107 requestLayout(); 4108 invalidate(); 4109 } 4110 } 4111 4112 /** 4113 * Gets the current frequency of automatic hyphenation to be used when determining word breaks. 4114 * @return the current frequency of automatic hyphenation to be used when determining word 4115 * breaks. 4116 * 4117 * @attr ref android.R.styleable#TextView_hyphenationFrequency 4118 * @see #setHyphenationFrequency(int) 4119 */ 4120 @Layout.HyphenationFrequency 4121 public int getHyphenationFrequency() { 4122 return mHyphenationFrequency; 4123 } 4124 4125 /** 4126 * Gets the parameters for text layout precomputation, for use with {@link PrecomputedText}. 4127 * 4128 * @return a current {@link PrecomputedText.Params} 4129 * @see PrecomputedText 4130 */ 4131 public @NonNull PrecomputedText.Params getTextMetricsParams() { 4132 return new PrecomputedText.Params(new TextPaint(mTextPaint), getTextDirectionHeuristic(), 4133 mBreakStrategy, mHyphenationFrequency); 4134 } 4135 4136 /** 4137 * Apply the text layout parameter. 4138 * 4139 * Update the TextView parameters to be compatible with {@link PrecomputedText.Params}. 4140 * @see PrecomputedText 4141 */ 4142 public void setTextMetricsParams(@NonNull PrecomputedText.Params params) { 4143 mTextPaint.set(params.getTextPaint()); 4144 mTextDir = params.getTextDirection(); 4145 mBreakStrategy = params.getBreakStrategy(); 4146 mHyphenationFrequency = params.getHyphenationFrequency(); 4147 if (mLayout != null) { 4148 nullLayouts(); 4149 requestLayout(); 4150 invalidate(); 4151 } 4152 } 4153 4154 /** 4155 * Set justification mode. The default value is {@link Layout#JUSTIFICATION_MODE_NONE}. If the 4156 * last line is too short for justification, the last line will be displayed with the 4157 * alignment set by {@link android.view.View#setTextAlignment}. 4158 * 4159 * @see #getJustificationMode() 4160 */ 4161 @Layout.JustificationMode 4162 public void setJustificationMode(@Layout.JustificationMode int justificationMode) { 4163 mJustificationMode = justificationMode; 4164 if (mLayout != null) { 4165 nullLayouts(); 4166 requestLayout(); 4167 invalidate(); 4168 } 4169 } 4170 4171 /** 4172 * @return true if currently paragraph justification mode. 4173 * 4174 * @see #setJustificationMode(int) 4175 */ 4176 public @Layout.JustificationMode int getJustificationMode() { 4177 return mJustificationMode; 4178 } 4179 4180 /** 4181 * Sets font feature settings. The format is the same as the CSS 4182 * font-feature-settings attribute: 4183 * <a href="https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop"> 4184 * https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop</a> 4185 * 4186 * @param fontFeatureSettings font feature settings represented as CSS compatible string 4187 * 4188 * @see #getFontFeatureSettings() 4189 * @see Paint#getFontFeatureSettings() Paint.getFontFeatureSettings() 4190 * 4191 * @attr ref android.R.styleable#TextView_fontFeatureSettings 4192 */ 4193 @android.view.RemotableViewMethod 4194 public void setFontFeatureSettings(@Nullable String fontFeatureSettings) { 4195 if (fontFeatureSettings != mTextPaint.getFontFeatureSettings()) { 4196 mTextPaint.setFontFeatureSettings(fontFeatureSettings); 4197 4198 if (mLayout != null) { 4199 nullLayouts(); 4200 requestLayout(); 4201 invalidate(); 4202 } 4203 } 4204 } 4205 4206 4207 /** 4208 * Sets TrueType or OpenType font variation settings. The settings string is constructed from 4209 * multiple pairs of axis tag and style values. The axis tag must contain four ASCII characters 4210 * and must be wrapped with single quotes (U+0027) or double quotes (U+0022). Axis strings that 4211 * are longer or shorter than four characters, or contain characters outside of U+0020..U+007E 4212 * are invalid. If a specified axis name is not defined in the font, the settings will be 4213 * ignored. 4214 * 4215 * <p> 4216 * Examples, 4217 * <ul> 4218 * <li>Set font width to 150. 4219 * <pre> 4220 * <code> 4221 * TextView textView = (TextView) findViewById(R.id.textView); 4222 * textView.setFontVariationSettings("'wdth' 150"); 4223 * </code> 4224 * </pre> 4225 * </li> 4226 * 4227 * <li>Set the font slant to 20 degrees and ask for italic style. 4228 * <pre> 4229 * <code> 4230 * TextView textView = (TextView) findViewById(R.id.textView); 4231 * textView.setFontVariationSettings("'slnt' 20, 'ital' 1"); 4232 * </code> 4233 * </pre> 4234 * </p> 4235 * </li> 4236 * </ul> 4237 * 4238 * @param fontVariationSettings font variation settings. You can pass null or empty string as 4239 * no variation settings. 4240 * @return true if the given settings is effective to at least one font file underlying this 4241 * TextView. This function also returns true for empty settings string. Otherwise 4242 * returns false. 4243 * 4244 * @throws IllegalArgumentException If given string is not a valid font variation settings 4245 * format. 4246 * 4247 * @see #getFontVariationSettings() 4248 * @see FontVariationAxis 4249 */ 4250 public boolean setFontVariationSettings(@Nullable String fontVariationSettings) { 4251 final String existingSettings = mTextPaint.getFontVariationSettings(); 4252 if (fontVariationSettings == existingSettings 4253 || (fontVariationSettings != null 4254 && fontVariationSettings.equals(existingSettings))) { 4255 return true; 4256 } 4257 boolean effective = mTextPaint.setFontVariationSettings(fontVariationSettings); 4258 4259 if (effective && mLayout != null) { 4260 nullLayouts(); 4261 requestLayout(); 4262 invalidate(); 4263 } 4264 return effective; 4265 } 4266 4267 /** 4268 * Sets the text color for all the states (normal, selected, 4269 * focused) to be this color. 4270 * 4271 * @param color A color value in the form 0xAARRGGBB. 4272 * Do not pass a resource ID. To get a color value from a resource ID, call 4273 * {@link android.support.v4.content.ContextCompat#getColor(Context, int) getColor}. 4274 * 4275 * @see #setTextColor(ColorStateList) 4276 * @see #getTextColors() 4277 * 4278 * @attr ref android.R.styleable#TextView_textColor 4279 */ 4280 @android.view.RemotableViewMethod 4281 public void setTextColor(@ColorInt int color) { 4282 mTextColor = ColorStateList.valueOf(color); 4283 updateTextColors(); 4284 } 4285 4286 /** 4287 * Sets the text color. 4288 * 4289 * @see #setTextColor(int) 4290 * @see #getTextColors() 4291 * @see #setHintTextColor(ColorStateList) 4292 * @see #setLinkTextColor(ColorStateList) 4293 * 4294 * @attr ref android.R.styleable#TextView_textColor 4295 */ 4296 @android.view.RemotableViewMethod 4297 public void setTextColor(ColorStateList colors) { 4298 if (colors == null) { 4299 throw new NullPointerException(); 4300 } 4301 4302 mTextColor = colors; 4303 updateTextColors(); 4304 } 4305 4306 /** 4307 * Gets the text colors for the different states (normal, selected, focused) of the TextView. 4308 * 4309 * @see #setTextColor(ColorStateList) 4310 * @see #setTextColor(int) 4311 * 4312 * @attr ref android.R.styleable#TextView_textColor 4313 */ 4314 public final ColorStateList getTextColors() { 4315 return mTextColor; 4316 } 4317 4318 /** 4319 * Return the current color selected for normal text. 4320 * 4321 * @return Returns the current text color. 4322 */ 4323 @ColorInt 4324 public final int getCurrentTextColor() { 4325 return mCurTextColor; 4326 } 4327 4328 /** 4329 * Sets the color used to display the selection highlight. 4330 * 4331 * @attr ref android.R.styleable#TextView_textColorHighlight 4332 */ 4333 @android.view.RemotableViewMethod 4334 public void setHighlightColor(@ColorInt int color) { 4335 if (mHighlightColor != color) { 4336 mHighlightColor = color; 4337 invalidate(); 4338 } 4339 } 4340 4341 /** 4342 * @return the color used to display the selection highlight 4343 * 4344 * @see #setHighlightColor(int) 4345 * 4346 * @attr ref android.R.styleable#TextView_textColorHighlight 4347 */ 4348 @ColorInt 4349 public int getHighlightColor() { 4350 return mHighlightColor; 4351 } 4352 4353 /** 4354 * Sets whether the soft input method will be made visible when this 4355 * TextView gets focused. The default is true. 4356 */ 4357 @android.view.RemotableViewMethod 4358 public final void setShowSoftInputOnFocus(boolean show) { 4359 createEditorIfNeeded(); 4360 mEditor.mShowSoftInputOnFocus = show; 4361 } 4362 4363 /** 4364 * Returns whether the soft input method will be made visible when this 4365 * TextView gets focused. The default is true. 4366 */ 4367 public final boolean getShowSoftInputOnFocus() { 4368 // When there is no Editor, return default true value 4369 return mEditor == null || mEditor.mShowSoftInputOnFocus; 4370 } 4371 4372 /** 4373 * Gives the text a shadow of the specified blur radius and color, the specified 4374 * distance from its drawn position. 4375 * <p> 4376 * The text shadow produced does not interact with the properties on view 4377 * that are responsible for real time shadows, 4378 * {@link View#getElevation() elevation} and 4379 * {@link View#getTranslationZ() translationZ}. 4380 * 4381 * @see Paint#setShadowLayer(float, float, float, int) 4382 * 4383 * @attr ref android.R.styleable#TextView_shadowColor 4384 * @attr ref android.R.styleable#TextView_shadowDx 4385 * @attr ref android.R.styleable#TextView_shadowDy 4386 * @attr ref android.R.styleable#TextView_shadowRadius 4387 */ 4388 public void setShadowLayer(float radius, float dx, float dy, int color) { 4389 mTextPaint.setShadowLayer(radius, dx, dy, color); 4390 4391 mShadowRadius = radius; 4392 mShadowDx = dx; 4393 mShadowDy = dy; 4394 mShadowColor = color; 4395 4396 // Will change text clip region 4397 if (mEditor != null) { 4398 mEditor.invalidateTextDisplayList(); 4399 mEditor.invalidateHandlesAndActionMode(); 4400 } 4401 invalidate(); 4402 } 4403 4404 /** 4405 * Gets the radius of the shadow layer. 4406 * 4407 * @return the radius of the shadow layer. If 0, the shadow layer is not visible 4408 * 4409 * @see #setShadowLayer(float, float, float, int) 4410 * 4411 * @attr ref android.R.styleable#TextView_shadowRadius 4412 */ 4413 public float getShadowRadius() { 4414 return mShadowRadius; 4415 } 4416 4417 /** 4418 * @return the horizontal offset of the shadow layer 4419 * 4420 * @see #setShadowLayer(float, float, float, int) 4421 * 4422 * @attr ref android.R.styleable#TextView_shadowDx 4423 */ 4424 public float getShadowDx() { 4425 return mShadowDx; 4426 } 4427 4428 /** 4429 * Gets the vertical offset of the shadow layer. 4430 * @return The vertical offset of the shadow layer. 4431 * 4432 * @see #setShadowLayer(float, float, float, int) 4433 * 4434 * @attr ref android.R.styleable#TextView_shadowDy 4435 */ 4436 public float getShadowDy() { 4437 return mShadowDy; 4438 } 4439 4440 /** 4441 * Gets the color of the shadow layer. 4442 * @return the color of the shadow layer 4443 * 4444 * @see #setShadowLayer(float, float, float, int) 4445 * 4446 * @attr ref android.R.styleable#TextView_shadowColor 4447 */ 4448 @ColorInt 4449 public int getShadowColor() { 4450 return mShadowColor; 4451 } 4452 4453 /** 4454 * Gets the {@link TextPaint} used for the text. 4455 * Use this only to consult the Paint's properties and not to change them. 4456 * @return The base paint used for the text. 4457 */ 4458 public TextPaint getPaint() { 4459 return mTextPaint; 4460 } 4461 4462 /** 4463 * Sets the autolink mask of the text. See {@link 4464 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 4465 * possible values. 4466 * 4467 * @attr ref android.R.styleable#TextView_autoLink 4468 */ 4469 @android.view.RemotableViewMethod 4470 public final void setAutoLinkMask(int mask) { 4471 mAutoLinkMask = mask; 4472 } 4473 4474 /** 4475 * Sets whether the movement method will automatically be set to 4476 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 4477 * set to nonzero and links are detected in {@link #setText}. 4478 * The default is true. 4479 * 4480 * @attr ref android.R.styleable#TextView_linksClickable 4481 */ 4482 @android.view.RemotableViewMethod 4483 public final void setLinksClickable(boolean whether) { 4484 mLinksClickable = whether; 4485 } 4486 4487 /** 4488 * Returns whether the movement method will automatically be set to 4489 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 4490 * set to nonzero and links are detected in {@link #setText}. 4491 * The default is true. 4492 * 4493 * @attr ref android.R.styleable#TextView_linksClickable 4494 */ 4495 public final boolean getLinksClickable() { 4496 return mLinksClickable; 4497 } 4498 4499 /** 4500 * Returns the list of {@link android.text.style.URLSpan URLSpans} attached to the text 4501 * (by {@link Linkify} or otherwise) if any. You can call 4502 * {@link URLSpan#getURL} on them to find where they link to 4503 * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd} 4504 * to find the region of the text they are attached to. 4505 */ 4506 public URLSpan[] getUrls() { 4507 if (mText instanceof Spanned) { 4508 return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class); 4509 } else { 4510 return new URLSpan[0]; 4511 } 4512 } 4513 4514 /** 4515 * Sets the color of the hint text for all the states (disabled, focussed, selected...) of this 4516 * TextView. 4517 * 4518 * @see #setHintTextColor(ColorStateList) 4519 * @see #getHintTextColors() 4520 * @see #setTextColor(int) 4521 * 4522 * @attr ref android.R.styleable#TextView_textColorHint 4523 */ 4524 @android.view.RemotableViewMethod 4525 public final void setHintTextColor(@ColorInt int color) { 4526 mHintTextColor = ColorStateList.valueOf(color); 4527 updateTextColors(); 4528 } 4529 4530 /** 4531 * Sets the color of the hint text. 4532 * 4533 * @see #getHintTextColors() 4534 * @see #setHintTextColor(int) 4535 * @see #setTextColor(ColorStateList) 4536 * @see #setLinkTextColor(ColorStateList) 4537 * 4538 * @attr ref android.R.styleable#TextView_textColorHint 4539 */ 4540 public final void setHintTextColor(ColorStateList colors) { 4541 mHintTextColor = colors; 4542 updateTextColors(); 4543 } 4544 4545 /** 4546 * @return the color of the hint text, for the different states of this TextView. 4547 * 4548 * @see #setHintTextColor(ColorStateList) 4549 * @see #setHintTextColor(int) 4550 * @see #setTextColor(ColorStateList) 4551 * @see #setLinkTextColor(ColorStateList) 4552 * 4553 * @attr ref android.R.styleable#TextView_textColorHint 4554 */ 4555 public final ColorStateList getHintTextColors() { 4556 return mHintTextColor; 4557 } 4558 4559 /** 4560 * <p>Return the current color selected to paint the hint text.</p> 4561 * 4562 * @return Returns the current hint text color. 4563 */ 4564 @ColorInt 4565 public final int getCurrentHintTextColor() { 4566 return mHintTextColor != null ? mCurHintTextColor : mCurTextColor; 4567 } 4568 4569 /** 4570 * Sets the color of links in the text. 4571 * 4572 * @see #setLinkTextColor(ColorStateList) 4573 * @see #getLinkTextColors() 4574 * 4575 * @attr ref android.R.styleable#TextView_textColorLink 4576 */ 4577 @android.view.RemotableViewMethod 4578 public final void setLinkTextColor(@ColorInt int color) { 4579 mLinkTextColor = ColorStateList.valueOf(color); 4580 updateTextColors(); 4581 } 4582 4583 /** 4584 * Sets the color of links in the text. 4585 * 4586 * @see #setLinkTextColor(int) 4587 * @see #getLinkTextColors() 4588 * @see #setTextColor(ColorStateList) 4589 * @see #setHintTextColor(ColorStateList) 4590 * 4591 * @attr ref android.R.styleable#TextView_textColorLink 4592 */ 4593 public final void setLinkTextColor(ColorStateList colors) { 4594 mLinkTextColor = colors; 4595 updateTextColors(); 4596 } 4597 4598 /** 4599 * @return the list of colors used to paint the links in the text, for the different states of 4600 * this TextView 4601 * 4602 * @see #setLinkTextColor(ColorStateList) 4603 * @see #setLinkTextColor(int) 4604 * 4605 * @attr ref android.R.styleable#TextView_textColorLink 4606 */ 4607 public final ColorStateList getLinkTextColors() { 4608 return mLinkTextColor; 4609 } 4610 4611 /** 4612 * Sets the horizontal alignment of the text and the 4613 * vertical gravity that will be used when there is extra space 4614 * in the TextView beyond what is required for the text itself. 4615 * 4616 * @see android.view.Gravity 4617 * @attr ref android.R.styleable#TextView_gravity 4618 */ 4619 public void setGravity(int gravity) { 4620 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 4621 gravity |= Gravity.START; 4622 } 4623 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 4624 gravity |= Gravity.TOP; 4625 } 4626 4627 boolean newLayout = false; 4628 4629 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) 4630 != (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK)) { 4631 newLayout = true; 4632 } 4633 4634 if (gravity != mGravity) { 4635 invalidate(); 4636 } 4637 4638 mGravity = gravity; 4639 4640 if (mLayout != null && newLayout) { 4641 // XXX this is heavy-handed because no actual content changes. 4642 int want = mLayout.getWidth(); 4643 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 4644 4645 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 4646 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), true); 4647 } 4648 } 4649 4650 /** 4651 * Returns the horizontal and vertical alignment of this TextView. 4652 * 4653 * @see android.view.Gravity 4654 * @attr ref android.R.styleable#TextView_gravity 4655 */ 4656 public int getGravity() { 4657 return mGravity; 4658 } 4659 4660 /** 4661 * Gets the flags on the Paint being used to display the text. 4662 * @return The flags on the Paint being used to display the text. 4663 * @see Paint#getFlags 4664 */ 4665 public int getPaintFlags() { 4666 return mTextPaint.getFlags(); 4667 } 4668 4669 /** 4670 * Sets flags on the Paint being used to display the text and 4671 * reflows the text if they are different from the old flags. 4672 * @see Paint#setFlags 4673 */ 4674 @android.view.RemotableViewMethod 4675 public void setPaintFlags(int flags) { 4676 if (mTextPaint.getFlags() != flags) { 4677 mTextPaint.setFlags(flags); 4678 4679 if (mLayout != null) { 4680 nullLayouts(); 4681 requestLayout(); 4682 invalidate(); 4683 } 4684 } 4685 } 4686 4687 /** 4688 * Sets whether the text should be allowed to be wider than the 4689 * View is. If false, it will be wrapped to the width of the View. 4690 * 4691 * @attr ref android.R.styleable#TextView_scrollHorizontally 4692 */ 4693 public void setHorizontallyScrolling(boolean whether) { 4694 if (mHorizontallyScrolling != whether) { 4695 mHorizontallyScrolling = whether; 4696 4697 if (mLayout != null) { 4698 nullLayouts(); 4699 requestLayout(); 4700 invalidate(); 4701 } 4702 } 4703 } 4704 4705 /** 4706 * Returns whether the text is allowed to be wider than the View is. 4707 * If false, the text will be wrapped to the width of the View. 4708 * 4709 * @attr ref android.R.styleable#TextView_scrollHorizontally 4710 * @hide 4711 */ 4712 public boolean getHorizontallyScrolling() { 4713 return mHorizontallyScrolling; 4714 } 4715 4716 /** 4717 * Sets the height of the TextView to be at least {@code minLines} tall. 4718 * <p> 4719 * This value is used for height calculation if LayoutParams does not force TextView to have an 4720 * exact height. Setting this value overrides other previous minimum height configurations such 4721 * as {@link #setMinHeight(int)} or {@link #setHeight(int)}. {@link #setSingleLine()} will set 4722 * this value to 1. 4723 * 4724 * @param minLines the minimum height of TextView in terms of number of lines 4725 * 4726 * @see #getMinLines() 4727 * @see #setLines(int) 4728 * 4729 * @attr ref android.R.styleable#TextView_minLines 4730 */ 4731 @android.view.RemotableViewMethod 4732 public void setMinLines(int minLines) { 4733 mMinimum = minLines; 4734 mMinMode = LINES; 4735 4736 requestLayout(); 4737 invalidate(); 4738 } 4739 4740 /** 4741 * Returns the minimum height of TextView in terms of number of lines or -1 if the minimum 4742 * height was set using {@link #setMinHeight(int)} or {@link #setHeight(int)}. 4743 * 4744 * @return the minimum height of TextView in terms of number of lines or -1 if the minimum 4745 * height is not defined in lines 4746 * 4747 * @see #setMinLines(int) 4748 * @see #setLines(int) 4749 * 4750 * @attr ref android.R.styleable#TextView_minLines 4751 */ 4752 public int getMinLines() { 4753 return mMinMode == LINES ? mMinimum : -1; 4754 } 4755 4756 /** 4757 * Sets the height of the TextView to be at least {@code minPixels} tall. 4758 * <p> 4759 * This value is used for height calculation if LayoutParams does not force TextView to have an 4760 * exact height. Setting this value overrides previous minimum height configurations such as 4761 * {@link #setMinLines(int)} or {@link #setLines(int)}. 4762 * <p> 4763 * The value given here is different than {@link #setMinimumHeight(int)}. Between 4764 * {@code minHeight} and the value set in {@link #setMinimumHeight(int)}, the greater one is 4765 * used to decide the final height. 4766 * 4767 * @param minPixels the minimum height of TextView in terms of pixels 4768 * 4769 * @see #getMinHeight() 4770 * @see #setHeight(int) 4771 * 4772 * @attr ref android.R.styleable#TextView_minHeight 4773 */ 4774 @android.view.RemotableViewMethod 4775 public void setMinHeight(int minPixels) { 4776 mMinimum = minPixels; 4777 mMinMode = PIXELS; 4778 4779 requestLayout(); 4780 invalidate(); 4781 } 4782 4783 /** 4784 * Returns the minimum height of TextView in terms of pixels or -1 if the minimum height was 4785 * set using {@link #setMinLines(int)} or {@link #setLines(int)}. 4786 * 4787 * @return the minimum height of TextView in terms of pixels or -1 if the minimum height is not 4788 * defined in pixels 4789 * 4790 * @see #setMinHeight(int) 4791 * @see #setHeight(int) 4792 * 4793 * @attr ref android.R.styleable#TextView_minHeight 4794 */ 4795 public int getMinHeight() { 4796 return mMinMode == PIXELS ? mMinimum : -1; 4797 } 4798 4799 /** 4800 * Sets the height of the TextView to be at most {@code maxLines} tall. 4801 * <p> 4802 * This value is used for height calculation if LayoutParams does not force TextView to have an 4803 * exact height. Setting this value overrides previous maximum height configurations such as 4804 * {@link #setMaxHeight(int)} or {@link #setLines(int)}. 4805 * 4806 * @param maxLines the maximum height of TextView in terms of number of lines 4807 * 4808 * @see #getMaxLines() 4809 * @see #setLines(int) 4810 * 4811 * @attr ref android.R.styleable#TextView_maxLines 4812 */ 4813 @android.view.RemotableViewMethod 4814 public void setMaxLines(int maxLines) { 4815 mMaximum = maxLines; 4816 mMaxMode = LINES; 4817 4818 requestLayout(); 4819 invalidate(); 4820 } 4821 4822 /** 4823 * Returns the maximum height of TextView in terms of number of lines or -1 if the 4824 * maximum height was set using {@link #setMaxHeight(int)} or {@link #setHeight(int)}. 4825 * 4826 * @return the maximum height of TextView in terms of number of lines. -1 if the maximum height 4827 * is not defined in lines. 4828 * 4829 * @see #setMaxLines(int) 4830 * @see #setLines(int) 4831 * 4832 * @attr ref android.R.styleable#TextView_maxLines 4833 */ 4834 public int getMaxLines() { 4835 return mMaxMode == LINES ? mMaximum : -1; 4836 } 4837 4838 /** 4839 * Sets the height of the TextView to be at most {@code maxPixels} tall. 4840 * <p> 4841 * This value is used for height calculation if LayoutParams does not force TextView to have an 4842 * exact height. Setting this value overrides previous maximum height configurations such as 4843 * {@link #setMaxLines(int)} or {@link #setLines(int)}. 4844 * 4845 * @param maxPixels the maximum height of TextView in terms of pixels 4846 * 4847 * @see #getMaxHeight() 4848 * @see #setHeight(int) 4849 * 4850 * @attr ref android.R.styleable#TextView_maxHeight 4851 */ 4852 @android.view.RemotableViewMethod 4853 public void setMaxHeight(int maxPixels) { 4854 mMaximum = maxPixels; 4855 mMaxMode = PIXELS; 4856 4857 requestLayout(); 4858 invalidate(); 4859 } 4860 4861 /** 4862 * Returns the maximum height of TextView in terms of pixels or -1 if the maximum height was 4863 * set using {@link #setMaxLines(int)} or {@link #setLines(int)}. 4864 * 4865 * @return the maximum height of TextView in terms of pixels or -1 if the maximum height 4866 * is not defined in pixels 4867 * 4868 * @see #setMaxHeight(int) 4869 * @see #setHeight(int) 4870 * 4871 * @attr ref android.R.styleable#TextView_maxHeight 4872 */ 4873 public int getMaxHeight() { 4874 return mMaxMode == PIXELS ? mMaximum : -1; 4875 } 4876 4877 /** 4878 * Sets the height of the TextView to be exactly {@code lines} tall. 4879 * <p> 4880 * This value is used for height calculation if LayoutParams does not force TextView to have an 4881 * exact height. Setting this value overrides previous minimum/maximum height configurations 4882 * such as {@link #setMinLines(int)} or {@link #setMaxLines(int)}. {@link #setSingleLine()} will 4883 * set this value to 1. 4884 * 4885 * @param lines the exact height of the TextView in terms of lines 4886 * 4887 * @see #setHeight(int) 4888 * 4889 * @attr ref android.R.styleable#TextView_lines 4890 */ 4891 @android.view.RemotableViewMethod 4892 public void setLines(int lines) { 4893 mMaximum = mMinimum = lines; 4894 mMaxMode = mMinMode = LINES; 4895 4896 requestLayout(); 4897 invalidate(); 4898 } 4899 4900 /** 4901 * Sets the height of the TextView to be exactly <code>pixels</code> tall. 4902 * <p> 4903 * This value is used for height calculation if LayoutParams does not force TextView to have an 4904 * exact height. Setting this value overrides previous minimum/maximum height configurations 4905 * such as {@link #setMinHeight(int)} or {@link #setMaxHeight(int)}. 4906 * 4907 * @param pixels the exact height of the TextView in terms of pixels 4908 * 4909 * @see #setLines(int) 4910 * 4911 * @attr ref android.R.styleable#TextView_height 4912 */ 4913 @android.view.RemotableViewMethod 4914 public void setHeight(int pixels) { 4915 mMaximum = mMinimum = pixels; 4916 mMaxMode = mMinMode = PIXELS; 4917 4918 requestLayout(); 4919 invalidate(); 4920 } 4921 4922 /** 4923 * Sets the width of the TextView to be at least {@code minEms} wide. 4924 * <p> 4925 * This value is used for width calculation if LayoutParams does not force TextView to have an 4926 * exact width. Setting this value overrides previous minimum width configurations such as 4927 * {@link #setMinWidth(int)} or {@link #setWidth(int)}. 4928 * 4929 * @param minEms the minimum width of TextView in terms of ems 4930 * 4931 * @see #getMinEms() 4932 * @see #setEms(int) 4933 * 4934 * @attr ref android.R.styleable#TextView_minEms 4935 */ 4936 @android.view.RemotableViewMethod 4937 public void setMinEms(int minEms) { 4938 mMinWidth = minEms; 4939 mMinWidthMode = EMS; 4940 4941 requestLayout(); 4942 invalidate(); 4943 } 4944 4945 /** 4946 * Returns the minimum width of TextView in terms of ems or -1 if the minimum width was set 4947 * using {@link #setMinWidth(int)} or {@link #setWidth(int)}. 4948 * 4949 * @return the minimum width of TextView in terms of ems. -1 if the minimum width is not 4950 * defined in ems 4951 * 4952 * @see #setMinEms(int) 4953 * @see #setEms(int) 4954 * 4955 * @attr ref android.R.styleable#TextView_minEms 4956 */ 4957 public int getMinEms() { 4958 return mMinWidthMode == EMS ? mMinWidth : -1; 4959 } 4960 4961 /** 4962 * Sets the width of the TextView to be at least {@code minPixels} wide. 4963 * <p> 4964 * This value is used for width calculation if LayoutParams does not force TextView to have an 4965 * exact width. Setting this value overrides previous minimum width configurations such as 4966 * {@link #setMinEms(int)} or {@link #setEms(int)}. 4967 * <p> 4968 * The value given here is different than {@link #setMinimumWidth(int)}. Between 4969 * {@code minWidth} and the value set in {@link #setMinimumWidth(int)}, the greater one is used 4970 * to decide the final width. 4971 * 4972 * @param minPixels the minimum width of TextView in terms of pixels 4973 * 4974 * @see #getMinWidth() 4975 * @see #setWidth(int) 4976 * 4977 * @attr ref android.R.styleable#TextView_minWidth 4978 */ 4979 @android.view.RemotableViewMethod 4980 public void setMinWidth(int minPixels) { 4981 mMinWidth = minPixels; 4982 mMinWidthMode = PIXELS; 4983 4984 requestLayout(); 4985 invalidate(); 4986 } 4987 4988 /** 4989 * Returns the minimum width of TextView in terms of pixels or -1 if the minimum width was set 4990 * using {@link #setMinEms(int)} or {@link #setEms(int)}. 4991 * 4992 * @return the minimum width of TextView in terms of pixels or -1 if the minimum width is not 4993 * defined in pixels 4994 * 4995 * @see #setMinWidth(int) 4996 * @see #setWidth(int) 4997 * 4998 * @attr ref android.R.styleable#TextView_minWidth 4999 */ 5000 public int getMinWidth() { 5001 return mMinWidthMode == PIXELS ? mMinWidth : -1; 5002 } 5003 5004 /** 5005 * Sets the width of the TextView to be at most {@code maxEms} wide. 5006 * <p> 5007 * This value is used for width calculation if LayoutParams does not force TextView to have an 5008 * exact width. Setting this value overrides previous maximum width configurations such as 5009 * {@link #setMaxWidth(int)} or {@link #setWidth(int)}. 5010 * 5011 * @param maxEms the maximum width of TextView in terms of ems 5012 * 5013 * @see #getMaxEms() 5014 * @see #setEms(int) 5015 * 5016 * @attr ref android.R.styleable#TextView_maxEms 5017 */ 5018 @android.view.RemotableViewMethod 5019 public void setMaxEms(int maxEms) { 5020 mMaxWidth = maxEms; 5021 mMaxWidthMode = EMS; 5022 5023 requestLayout(); 5024 invalidate(); 5025 } 5026 5027 /** 5028 * Returns the maximum width of TextView in terms of ems or -1 if the maximum width was set 5029 * using {@link #setMaxWidth(int)} or {@link #setWidth(int)}. 5030 * 5031 * @return the maximum width of TextView in terms of ems or -1 if the maximum width is not 5032 * defined in ems 5033 * 5034 * @see #setMaxEms(int) 5035 * @see #setEms(int) 5036 * 5037 * @attr ref android.R.styleable#TextView_maxEms 5038 */ 5039 public int getMaxEms() { 5040 return mMaxWidthMode == EMS ? mMaxWidth : -1; 5041 } 5042 5043 /** 5044 * Sets the width of the TextView to be at most {@code maxPixels} wide. 5045 * <p> 5046 * This value is used for width calculation if LayoutParams does not force TextView to have an 5047 * exact width. Setting this value overrides previous maximum width configurations such as 5048 * {@link #setMaxEms(int)} or {@link #setEms(int)}. 5049 * 5050 * @param maxPixels the maximum width of TextView in terms of pixels 5051 * 5052 * @see #getMaxWidth() 5053 * @see #setWidth(int) 5054 * 5055 * @attr ref android.R.styleable#TextView_maxWidth 5056 */ 5057 @android.view.RemotableViewMethod 5058 public void setMaxWidth(int maxPixels) { 5059 mMaxWidth = maxPixels; 5060 mMaxWidthMode = PIXELS; 5061 5062 requestLayout(); 5063 invalidate(); 5064 } 5065 5066 /** 5067 * Returns the maximum width of TextView in terms of pixels or -1 if the maximum width was set 5068 * using {@link #setMaxEms(int)} or {@link #setEms(int)}. 5069 * 5070 * @return the maximum width of TextView in terms of pixels. -1 if the maximum width is not 5071 * defined in pixels 5072 * 5073 * @see #setMaxWidth(int) 5074 * @see #setWidth(int) 5075 * 5076 * @attr ref android.R.styleable#TextView_maxWidth 5077 */ 5078 public int getMaxWidth() { 5079 return mMaxWidthMode == PIXELS ? mMaxWidth : -1; 5080 } 5081 5082 /** 5083 * Sets the width of the TextView to be exactly {@code ems} wide. 5084 * 5085 * This value is used for width calculation if LayoutParams does not force TextView to have an 5086 * exact width. Setting this value overrides previous minimum/maximum configurations such as 5087 * {@link #setMinEms(int)} or {@link #setMaxEms(int)}. 5088 * 5089 * @param ems the exact width of the TextView in terms of ems 5090 * 5091 * @see #setWidth(int) 5092 * 5093 * @attr ref android.R.styleable#TextView_ems 5094 */ 5095 @android.view.RemotableViewMethod 5096 public void setEms(int ems) { 5097 mMaxWidth = mMinWidth = ems; 5098 mMaxWidthMode = mMinWidthMode = EMS; 5099 5100 requestLayout(); 5101 invalidate(); 5102 } 5103 5104 /** 5105 * Sets the width of the TextView to be exactly {@code pixels} wide. 5106 * <p> 5107 * This value is used for width calculation if LayoutParams does not force TextView to have an 5108 * exact width. Setting this value overrides previous minimum/maximum width configurations 5109 * such as {@link #setMinWidth(int)} or {@link #setMaxWidth(int)}. 5110 * 5111 * @param pixels the exact width of the TextView in terms of pixels 5112 * 5113 * @see #setEms(int) 5114 * 5115 * @attr ref android.R.styleable#TextView_width 5116 */ 5117 @android.view.RemotableViewMethod 5118 public void setWidth(int pixels) { 5119 mMaxWidth = mMinWidth = pixels; 5120 mMaxWidthMode = mMinWidthMode = PIXELS; 5121 5122 requestLayout(); 5123 invalidate(); 5124 } 5125 5126 /** 5127 * Sets line spacing for this TextView. Each line other than the last line will have its height 5128 * multiplied by {@code mult} and have {@code add} added to it. 5129 * 5130 * @param add The value in pixels that should be added to each line other than the last line. 5131 * This will be applied after the multiplier 5132 * @param mult The value by which each line height other than the last line will be multiplied 5133 * by 5134 * 5135 * @attr ref android.R.styleable#TextView_lineSpacingExtra 5136 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 5137 */ 5138 public void setLineSpacing(float add, float mult) { 5139 if (mSpacingAdd != add || mSpacingMult != mult) { 5140 mSpacingAdd = add; 5141 mSpacingMult = mult; 5142 5143 if (mLayout != null) { 5144 nullLayouts(); 5145 requestLayout(); 5146 invalidate(); 5147 } 5148 } 5149 } 5150 5151 /** 5152 * Gets the line spacing multiplier 5153 * 5154 * @return the value by which each line's height is multiplied to get its actual height. 5155 * 5156 * @see #setLineSpacing(float, float) 5157 * @see #getLineSpacingExtra() 5158 * 5159 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 5160 */ 5161 public float getLineSpacingMultiplier() { 5162 return mSpacingMult; 5163 } 5164 5165 /** 5166 * Gets the line spacing extra space 5167 * 5168 * @return the extra space that is added to the height of each lines of this TextView. 5169 * 5170 * @see #setLineSpacing(float, float) 5171 * @see #getLineSpacingMultiplier() 5172 * 5173 * @attr ref android.R.styleable#TextView_lineSpacingExtra 5174 */ 5175 public float getLineSpacingExtra() { 5176 return mSpacingAdd; 5177 } 5178 5179 /** 5180 * Sets an explicit line height for this TextView. This is equivalent to the vertical distance 5181 * between subsequent baselines in the TextView. 5182 * 5183 * @param lineHeight the line height in pixels 5184 * 5185 * @see #setLineSpacing(float, float) 5186 * @see #getLineSpacing() 5187 * 5188 * @attr ref android.R.styleable#TextView_lineHeight 5189 */ 5190 public void setLineHeight(@Px @IntRange(from = 0) int lineHeight) { 5191 Preconditions.checkArgumentNonnegative(lineHeight); 5192 5193 final int fontHeight = getPaint().getFontMetricsInt(null); 5194 // Make sure we don't setLineSpacing if it's not needed to avoid unnecessary redraw. 5195 if (lineHeight != fontHeight) { 5196 // Set lineSpacingExtra by the difference of lineSpacing with lineHeight 5197 setLineSpacing(lineHeight - fontHeight, 1f); 5198 } 5199 } 5200 5201 /** 5202 * Gets whether this view is a heading for accessibility purposes. 5203 * 5204 * @return {@code true} if the view is a heading, {@code false} otherwise. 5205 * 5206 * @attr ref android.R.styleable#TextView_accessibilityHeading 5207 */ 5208 public boolean isAccessibilityHeading() { 5209 return mIsAccessibilityHeading; 5210 } 5211 5212 /** 5213 * Set if view is a heading for a section of content for accessibility purposes. 5214 * 5215 * @param isHeading {@code true} if the view is a heading, {@code false} otherwise. 5216 * 5217 * @attr ref android.R.styleable#TextView_accessibilityHeading 5218 */ 5219 public void setAccessibilityHeading(boolean isHeading) { 5220 if (isHeading != mIsAccessibilityHeading) { 5221 mIsAccessibilityHeading = isHeading; 5222 notifyViewAccessibilityStateChangedIfNeeded( 5223 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 5224 } 5225 } 5226 5227 /** 5228 * Convenience method to append the specified text to the TextView's 5229 * display buffer, upgrading it to {@link android.widget.TextView.BufferType#EDITABLE} 5230 * if it was not already editable. 5231 * 5232 * @param text text to be appended to the already displayed text 5233 */ 5234 public final void append(CharSequence text) { 5235 append(text, 0, text.length()); 5236 } 5237 5238 /** 5239 * Convenience method to append the specified text slice to the TextView's 5240 * display buffer, upgrading it to {@link android.widget.TextView.BufferType#EDITABLE} 5241 * if it was not already editable. 5242 * 5243 * @param text text to be appended to the already displayed text 5244 * @param start the index of the first character in the {@code text} 5245 * @param end the index of the character following the last character in the {@code text} 5246 * 5247 * @see Appendable#append(CharSequence, int, int) 5248 */ 5249 public void append(CharSequence text, int start, int end) { 5250 if (!(mText instanceof Editable)) { 5251 setText(mText, BufferType.EDITABLE); 5252 } 5253 5254 ((Editable) mText).append(text, start, end); 5255 5256 if (mAutoLinkMask != 0) { 5257 boolean linksWereAdded = Linkify.addLinks((Spannable) mText, mAutoLinkMask); 5258 // Do not change the movement method for text that support text selection as it 5259 // would prevent an arbitrary cursor displacement. 5260 if (linksWereAdded && mLinksClickable && !textCanBeSelected()) { 5261 setMovementMethod(LinkMovementMethod.getInstance()); 5262 } 5263 } 5264 } 5265 5266 private void updateTextColors() { 5267 boolean inval = false; 5268 final int[] drawableState = getDrawableState(); 5269 int color = mTextColor.getColorForState(drawableState, 0); 5270 if (color != mCurTextColor) { 5271 mCurTextColor = color; 5272 inval = true; 5273 } 5274 if (mLinkTextColor != null) { 5275 color = mLinkTextColor.getColorForState(drawableState, 0); 5276 if (color != mTextPaint.linkColor) { 5277 mTextPaint.linkColor = color; 5278 inval = true; 5279 } 5280 } 5281 if (mHintTextColor != null) { 5282 color = mHintTextColor.getColorForState(drawableState, 0); 5283 if (color != mCurHintTextColor) { 5284 mCurHintTextColor = color; 5285 if (mText.length() == 0) { 5286 inval = true; 5287 } 5288 } 5289 } 5290 if (inval) { 5291 // Text needs to be redrawn with the new color 5292 if (mEditor != null) mEditor.invalidateTextDisplayList(); 5293 invalidate(); 5294 } 5295 } 5296 5297 @Override 5298 protected void drawableStateChanged() { 5299 super.drawableStateChanged(); 5300 5301 if (mTextColor != null && mTextColor.isStateful() 5302 || (mHintTextColor != null && mHintTextColor.isStateful()) 5303 || (mLinkTextColor != null && mLinkTextColor.isStateful())) { 5304 updateTextColors(); 5305 } 5306 5307 if (mDrawables != null) { 5308 final int[] state = getDrawableState(); 5309 for (Drawable dr : mDrawables.mShowing) { 5310 if (dr != null && dr.isStateful() && dr.setState(state)) { 5311 invalidateDrawable(dr); 5312 } 5313 } 5314 } 5315 } 5316 5317 @Override 5318 public void drawableHotspotChanged(float x, float y) { 5319 super.drawableHotspotChanged(x, y); 5320 5321 if (mDrawables != null) { 5322 for (Drawable dr : mDrawables.mShowing) { 5323 if (dr != null) { 5324 dr.setHotspot(x, y); 5325 } 5326 } 5327 } 5328 } 5329 5330 @Override 5331 public Parcelable onSaveInstanceState() { 5332 Parcelable superState = super.onSaveInstanceState(); 5333 5334 // Save state if we are forced to 5335 final boolean freezesText = getFreezesText(); 5336 boolean hasSelection = false; 5337 int start = -1; 5338 int end = -1; 5339 5340 if (mText != null) { 5341 start = getSelectionStart(); 5342 end = getSelectionEnd(); 5343 if (start >= 0 || end >= 0) { 5344 // Or save state if there is a selection 5345 hasSelection = true; 5346 } 5347 } 5348 5349 if (freezesText || hasSelection) { 5350 SavedState ss = new SavedState(superState); 5351 5352 if (freezesText) { 5353 if (mText instanceof Spanned) { 5354 final Spannable sp = new SpannableStringBuilder(mText); 5355 5356 if (mEditor != null) { 5357 removeMisspelledSpans(sp); 5358 sp.removeSpan(mEditor.mSuggestionRangeSpan); 5359 } 5360 5361 ss.text = sp; 5362 } else { 5363 ss.text = mText.toString(); 5364 } 5365 } 5366 5367 if (hasSelection) { 5368 // XXX Should also save the current scroll position! 5369 ss.selStart = start; 5370 ss.selEnd = end; 5371 } 5372 5373 if (isFocused() && start >= 0 && end >= 0) { 5374 ss.frozenWithFocus = true; 5375 } 5376 5377 ss.error = getError(); 5378 5379 if (mEditor != null) { 5380 ss.editorState = mEditor.saveInstanceState(); 5381 } 5382 return ss; 5383 } 5384 5385 return superState; 5386 } 5387 5388 void removeMisspelledSpans(Spannable spannable) { 5389 SuggestionSpan[] suggestionSpans = spannable.getSpans(0, spannable.length(), 5390 SuggestionSpan.class); 5391 for (int i = 0; i < suggestionSpans.length; i++) { 5392 int flags = suggestionSpans[i].getFlags(); 5393 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 5394 && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) { 5395 spannable.removeSpan(suggestionSpans[i]); 5396 } 5397 } 5398 } 5399 5400 @Override 5401 public void onRestoreInstanceState(Parcelable state) { 5402 if (!(state instanceof SavedState)) { 5403 super.onRestoreInstanceState(state); 5404 return; 5405 } 5406 5407 SavedState ss = (SavedState) state; 5408 super.onRestoreInstanceState(ss.getSuperState()); 5409 5410 // XXX restore buffer type too, as well as lots of other stuff 5411 if (ss.text != null) { 5412 setText(ss.text); 5413 } 5414 5415 if (ss.selStart >= 0 && ss.selEnd >= 0) { 5416 if (mText instanceof Spannable) { 5417 int len = mText.length(); 5418 5419 if (ss.selStart > len || ss.selEnd > len) { 5420 String restored = ""; 5421 5422 if (ss.text != null) { 5423 restored = "(restored) "; 5424 } 5425 5426 Log.e(LOG_TAG, "Saved cursor position " + ss.selStart + "/" + ss.selEnd 5427 + " out of range for " + restored + "text " + mText); 5428 } else { 5429 Selection.setSelection((Spannable) mText, ss.selStart, ss.selEnd); 5430 5431 if (ss.frozenWithFocus) { 5432 createEditorIfNeeded(); 5433 mEditor.mFrozenWithFocus = true; 5434 } 5435 } 5436 } 5437 } 5438 5439 if (ss.error != null) { 5440 final CharSequence error = ss.error; 5441 // Display the error later, after the first layout pass 5442 post(new Runnable() { 5443 public void run() { 5444 if (mEditor == null || !mEditor.mErrorWasChanged) { 5445 setError(error); 5446 } 5447 } 5448 }); 5449 } 5450 5451 if (ss.editorState != null) { 5452 createEditorIfNeeded(); 5453 mEditor.restoreInstanceState(ss.editorState); 5454 } 5455 } 5456 5457 /** 5458 * Control whether this text view saves its entire text contents when 5459 * freezing to an icicle, in addition to dynamic state such as cursor 5460 * position. By default this is false, not saving the text. Set to true 5461 * if the text in the text view is not being saved somewhere else in 5462 * persistent storage (such as in a content provider) so that if the 5463 * view is later thawed the user will not lose their data. For 5464 * {@link android.widget.EditText} it is always enabled, regardless of 5465 * the value of the attribute. 5466 * 5467 * @param freezesText Controls whether a frozen icicle should include the 5468 * entire text data: true to include it, false to not. 5469 * 5470 * @attr ref android.R.styleable#TextView_freezesText 5471 */ 5472 @android.view.RemotableViewMethod 5473 public void setFreezesText(boolean freezesText) { 5474 mFreezesText = freezesText; 5475 } 5476 5477 /** 5478 * Return whether this text view is including its entire text contents 5479 * in frozen icicles. For {@link android.widget.EditText} it always returns true. 5480 * 5481 * @return Returns true if text is included, false if it isn't. 5482 * 5483 * @see #setFreezesText 5484 */ 5485 public boolean getFreezesText() { 5486 return mFreezesText; 5487 } 5488 5489 /////////////////////////////////////////////////////////////////////////// 5490 5491 /** 5492 * Sets the Factory used to create new {@link Editable Editables}. 5493 * 5494 * @param factory {@link android.text.Editable.Factory Editable.Factory} to be used 5495 * 5496 * @see android.text.Editable.Factory 5497 * @see android.widget.TextView.BufferType#EDITABLE 5498 */ 5499 public final void setEditableFactory(Editable.Factory factory) { 5500 mEditableFactory = factory; 5501 setText(mText); 5502 } 5503 5504 /** 5505 * Sets the Factory used to create new {@link Spannable Spannables}. 5506 * 5507 * @param factory {@link android.text.Spannable.Factory Spannable.Factory} to be used 5508 * 5509 * @see android.text.Spannable.Factory 5510 * @see android.widget.TextView.BufferType#SPANNABLE 5511 */ 5512 public final void setSpannableFactory(Spannable.Factory factory) { 5513 mSpannableFactory = factory; 5514 setText(mText); 5515 } 5516 5517 /** 5518 * Sets the text to be displayed. TextView <em>does not</em> accept 5519 * HTML-like formatting, which you can do with text strings in XML resource files. 5520 * To style your strings, attach android.text.style.* objects to a 5521 * {@link android.text.SpannableString}, or see the 5522 * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources"> 5523 * Available Resource Types</a> documentation for an example of setting 5524 * formatted text in the XML resource file. 5525 * <p/> 5526 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or 5527 * intermediate {@link Spannable Spannables}. Likewise it will use 5528 * {@link android.text.Editable.Factory} to create final or intermediate 5529 * {@link Editable Editables}. 5530 * 5531 * @param text text to be displayed 5532 * 5533 * @attr ref android.R.styleable#TextView_text 5534 */ 5535 @android.view.RemotableViewMethod 5536 public final void setText(CharSequence text) { 5537 setText(text, mBufferType); 5538 } 5539 5540 /** 5541 * Sets the text to be displayed but retains the cursor position. Same as 5542 * {@link #setText(CharSequence)} except that the cursor position (if any) is retained in the 5543 * new text. 5544 * <p/> 5545 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or 5546 * intermediate {@link Spannable Spannables}. Likewise it will use 5547 * {@link android.text.Editable.Factory} to create final or intermediate 5548 * {@link Editable Editables}. 5549 * 5550 * @param text text to be displayed 5551 * 5552 * @see #setText(CharSequence) 5553 */ 5554 @android.view.RemotableViewMethod 5555 public final void setTextKeepState(CharSequence text) { 5556 setTextKeepState(text, mBufferType); 5557 } 5558 5559 /** 5560 * Sets the text to be displayed and the {@link android.widget.TextView.BufferType}. 5561 * <p/> 5562 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or 5563 * intermediate {@link Spannable Spannables}. Likewise it will use 5564 * {@link android.text.Editable.Factory} to create final or intermediate 5565 * {@link Editable Editables}. 5566 * 5567 * @param text text to be displayed 5568 * @param type a {@link android.widget.TextView.BufferType} which defines whether the text is 5569 * stored as a static text, styleable/spannable text, or editable text 5570 * 5571 * @see #setText(CharSequence) 5572 * @see android.widget.TextView.BufferType 5573 * @see #setSpannableFactory(Spannable.Factory) 5574 * @see #setEditableFactory(Editable.Factory) 5575 * 5576 * @attr ref android.R.styleable#TextView_text 5577 * @attr ref android.R.styleable#TextView_bufferType 5578 */ 5579 public void setText(CharSequence text, BufferType type) { 5580 setText(text, type, true, 0); 5581 5582 if (mCharWrapper != null) { 5583 mCharWrapper.mChars = null; 5584 } 5585 } 5586 5587 private void setText(CharSequence text, BufferType type, 5588 boolean notifyBefore, int oldlen) { 5589 mTextSetFromXmlOrResourceId = false; 5590 if (text == null) { 5591 text = ""; 5592 } 5593 5594 // If suggestions are not enabled, remove the suggestion spans from the text 5595 if (!isSuggestionsEnabled()) { 5596 text = removeSuggestionSpans(text); 5597 } 5598 5599 if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f); 5600 5601 if (text instanceof Spanned 5602 && ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) { 5603 if (ViewConfiguration.get(mContext).isFadingMarqueeEnabled()) { 5604 setHorizontalFadingEdgeEnabled(true); 5605 mMarqueeFadeMode = MARQUEE_FADE_NORMAL; 5606 } else { 5607 setHorizontalFadingEdgeEnabled(false); 5608 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 5609 } 5610 setEllipsize(TextUtils.TruncateAt.MARQUEE); 5611 } 5612 5613 int n = mFilters.length; 5614 for (int i = 0; i < n; i++) { 5615 CharSequence out = mFilters[i].filter(text, 0, text.length(), EMPTY_SPANNED, 0, 0); 5616 if (out != null) { 5617 text = out; 5618 } 5619 } 5620 5621 if (notifyBefore) { 5622 if (mText != null) { 5623 oldlen = mText.length(); 5624 sendBeforeTextChanged(mText, 0, oldlen, text.length()); 5625 } else { 5626 sendBeforeTextChanged("", 0, 0, text.length()); 5627 } 5628 } 5629 5630 boolean needEditableForNotification = false; 5631 5632 if (mListeners != null && mListeners.size() != 0) { 5633 needEditableForNotification = true; 5634 } 5635 5636 if (type == BufferType.EDITABLE || getKeyListener() != null 5637 || needEditableForNotification) { 5638 createEditorIfNeeded(); 5639 mEditor.forgetUndoRedo(); 5640 Editable t = mEditableFactory.newEditable(text); 5641 text = t; 5642 setFilters(t, mFilters); 5643 InputMethodManager imm = InputMethodManager.peekInstance(); 5644 if (imm != null) imm.restartInput(this); 5645 } else if (type == BufferType.SPANNABLE || mMovement != null) { 5646 text = mSpannableFactory.newSpannable(text); 5647 } else if (!(text instanceof PrecomputedText || text instanceof CharWrapper)) { 5648 text = TextUtils.stringOrSpannedString(text); 5649 } 5650 5651 if (mAutoLinkMask != 0) { 5652 Spannable s2; 5653 5654 if (type == BufferType.EDITABLE || text instanceof Spannable) { 5655 s2 = (Spannable) text; 5656 } else { 5657 s2 = mSpannableFactory.newSpannable(text); 5658 } 5659 5660 if (Linkify.addLinks(s2, mAutoLinkMask)) { 5661 text = s2; 5662 type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE; 5663 5664 /* 5665 * We must go ahead and set the text before changing the 5666 * movement method, because setMovementMethod() may call 5667 * setText() again to try to upgrade the buffer type. 5668 */ 5669 mText = text; 5670 5671 // Do not change the movement method for text that support text selection as it 5672 // would prevent an arbitrary cursor displacement. 5673 if (mLinksClickable && !textCanBeSelected()) { 5674 setMovementMethod(LinkMovementMethod.getInstance()); 5675 } 5676 } 5677 } 5678 5679 mBufferType = type; 5680 mText = text; 5681 5682 if (mTransformation == null) { 5683 mTransformed = text; 5684 } else { 5685 mTransformed = mTransformation.getTransformation(text, this); 5686 } 5687 5688 final int textLength = text.length(); 5689 5690 if (text instanceof Spannable && !mAllowTransformationLengthChange) { 5691 Spannable sp = (Spannable) text; 5692 5693 // Remove any ChangeWatchers that might have come from other TextViews. 5694 final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class); 5695 final int count = watchers.length; 5696 for (int i = 0; i < count; i++) { 5697 sp.removeSpan(watchers[i]); 5698 } 5699 5700 if (mChangeWatcher == null) mChangeWatcher = new ChangeWatcher(); 5701 5702 sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE 5703 | (CHANGE_WATCHER_PRIORITY << Spanned.SPAN_PRIORITY_SHIFT)); 5704 5705 if (mEditor != null) mEditor.addSpanWatchers(sp); 5706 5707 if (mTransformation != null) { 5708 sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 5709 } 5710 5711 if (mMovement != null) { 5712 mMovement.initialize(this, (Spannable) text); 5713 5714 /* 5715 * Initializing the movement method will have set the 5716 * selection, so reset mSelectionMoved to keep that from 5717 * interfering with the normal on-focus selection-setting. 5718 */ 5719 if (mEditor != null) mEditor.mSelectionMoved = false; 5720 } 5721 } 5722 5723 if (mLayout != null) { 5724 checkForRelayout(); 5725 } 5726 5727 sendOnTextChanged(text, 0, oldlen, textLength); 5728 onTextChanged(text, 0, oldlen, textLength); 5729 5730 notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT); 5731 5732 if (needEditableForNotification) { 5733 sendAfterTextChanged((Editable) text); 5734 } else { 5735 notifyAutoFillManagerAfterTextChangedIfNeeded(); 5736 } 5737 5738 // SelectionModifierCursorController depends on textCanBeSelected, which depends on text 5739 if (mEditor != null) mEditor.prepareCursorControllers(); 5740 } 5741 5742 /** 5743 * Sets the TextView to display the specified slice of the specified 5744 * char array. You must promise that you will not change the contents 5745 * of the array except for right before another call to setText(), 5746 * since the TextView has no way to know that the text 5747 * has changed and that it needs to invalidate and re-layout. 5748 * 5749 * @param text char array to be displayed 5750 * @param start start index in the char array 5751 * @param len length of char count after {@code start} 5752 */ 5753 public final void setText(char[] text, int start, int len) { 5754 int oldlen = 0; 5755 5756 if (start < 0 || len < 0 || start + len > text.length) { 5757 throw new IndexOutOfBoundsException(start + ", " + len); 5758 } 5759 5760 /* 5761 * We must do the before-notification here ourselves because if 5762 * the old text is a CharWrapper we destroy it before calling 5763 * into the normal path. 5764 */ 5765 if (mText != null) { 5766 oldlen = mText.length(); 5767 sendBeforeTextChanged(mText, 0, oldlen, len); 5768 } else { 5769 sendBeforeTextChanged("", 0, 0, len); 5770 } 5771 5772 if (mCharWrapper == null) { 5773 mCharWrapper = new CharWrapper(text, start, len); 5774 } else { 5775 mCharWrapper.set(text, start, len); 5776 } 5777 5778 setText(mCharWrapper, mBufferType, false, oldlen); 5779 } 5780 5781 /** 5782 * Sets the text to be displayed and the {@link android.widget.TextView.BufferType} but retains 5783 * the cursor position. Same as 5784 * {@link #setText(CharSequence, android.widget.TextView.BufferType)} except that the cursor 5785 * position (if any) is retained in the new text. 5786 * <p/> 5787 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or 5788 * intermediate {@link Spannable Spannables}. Likewise it will use 5789 * {@link android.text.Editable.Factory} to create final or intermediate 5790 * {@link Editable Editables}. 5791 * 5792 * @param text text to be displayed 5793 * @param type a {@link android.widget.TextView.BufferType} which defines whether the text is 5794 * stored as a static text, styleable/spannable text, or editable text 5795 * 5796 * @see #setText(CharSequence, android.widget.TextView.BufferType) 5797 */ 5798 public final void setTextKeepState(CharSequence text, BufferType type) { 5799 int start = getSelectionStart(); 5800 int end = getSelectionEnd(); 5801 int len = text.length(); 5802 5803 setText(text, type); 5804 5805 if (start >= 0 || end >= 0) { 5806 if (mText instanceof Spannable) { 5807 Selection.setSelection((Spannable) mText, 5808 Math.max(0, Math.min(start, len)), 5809 Math.max(0, Math.min(end, len))); 5810 } 5811 } 5812 } 5813 5814 /** 5815 * Sets the text to be displayed using a string resource identifier. 5816 * 5817 * @param resid the resource identifier of the string resource to be displayed 5818 * 5819 * @see #setText(CharSequence) 5820 * 5821 * @attr ref android.R.styleable#TextView_text 5822 */ 5823 @android.view.RemotableViewMethod 5824 public final void setText(@StringRes int resid) { 5825 setText(getContext().getResources().getText(resid)); 5826 mTextSetFromXmlOrResourceId = true; 5827 mTextId = resid; 5828 } 5829 5830 /** 5831 * Sets the text to be displayed using a string resource identifier and the 5832 * {@link android.widget.TextView.BufferType}. 5833 * <p/> 5834 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or 5835 * intermediate {@link Spannable Spannables}. Likewise it will use 5836 * {@link android.text.Editable.Factory} to create final or intermediate 5837 * {@link Editable Editables}. 5838 * 5839 * @param resid the resource identifier of the string resource to be displayed 5840 * @param type a {@link android.widget.TextView.BufferType} which defines whether the text is 5841 * stored as a static text, styleable/spannable text, or editable text 5842 * 5843 * @see #setText(int) 5844 * @see #setText(CharSequence) 5845 * @see android.widget.TextView.BufferType 5846 * @see #setSpannableFactory(Spannable.Factory) 5847 * @see #setEditableFactory(Editable.Factory) 5848 * 5849 * @attr ref android.R.styleable#TextView_text 5850 * @attr ref android.R.styleable#TextView_bufferType 5851 */ 5852 public final void setText(@StringRes int resid, BufferType type) { 5853 setText(getContext().getResources().getText(resid), type); 5854 mTextSetFromXmlOrResourceId = true; 5855 mTextId = resid; 5856 } 5857 5858 /** 5859 * Sets the text to be displayed when the text of the TextView is empty. 5860 * Null means to use the normal empty text. The hint does not currently 5861 * participate in determining the size of the view. 5862 * 5863 * @attr ref android.R.styleable#TextView_hint 5864 */ 5865 @android.view.RemotableViewMethod 5866 public final void setHint(CharSequence hint) { 5867 setHintInternal(hint); 5868 5869 if (mEditor != null && isInputMethodTarget()) { 5870 mEditor.reportExtractedText(); 5871 } 5872 } 5873 5874 private void setHintInternal(CharSequence hint) { 5875 mHint = TextUtils.stringOrSpannedString(hint); 5876 5877 if (mLayout != null) { 5878 checkForRelayout(); 5879 } 5880 5881 if (mText.length() == 0) { 5882 invalidate(); 5883 } 5884 5885 // Invalidate display list if hint is currently used 5886 if (mEditor != null && mText.length() == 0 && mHint != null) { 5887 mEditor.invalidateTextDisplayList(); 5888 } 5889 } 5890 5891 /** 5892 * Sets the text to be displayed when the text of the TextView is empty, 5893 * from a resource. 5894 * 5895 * @attr ref android.R.styleable#TextView_hint 5896 */ 5897 @android.view.RemotableViewMethod 5898 public final void setHint(@StringRes int resid) { 5899 setHint(getContext().getResources().getText(resid)); 5900 } 5901 5902 /** 5903 * Returns the hint that is displayed when the text of the TextView 5904 * is empty. 5905 * 5906 * @attr ref android.R.styleable#TextView_hint 5907 */ 5908 @ViewDebug.CapturedViewProperty 5909 public CharSequence getHint() { 5910 return mHint; 5911 } 5912 5913 boolean isSingleLine() { 5914 return mSingleLine; 5915 } 5916 5917 private static boolean isMultilineInputType(int type) { 5918 return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) 5919 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); 5920 } 5921 5922 /** 5923 * Removes the suggestion spans. 5924 */ 5925 CharSequence removeSuggestionSpans(CharSequence text) { 5926 if (text instanceof Spanned) { 5927 Spannable spannable; 5928 if (text instanceof Spannable) { 5929 spannable = (Spannable) text; 5930 } else { 5931 spannable = mSpannableFactory.newSpannable(text); 5932 } 5933 5934 SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class); 5935 if (spans.length == 0) { 5936 return text; 5937 } else { 5938 text = spannable; 5939 } 5940 5941 for (int i = 0; i < spans.length; i++) { 5942 spannable.removeSpan(spans[i]); 5943 } 5944 } 5945 return text; 5946 } 5947 5948 /** 5949 * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This 5950 * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, 5951 * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} 5952 * then a soft keyboard will not be displayed for this text view. 5953 * 5954 * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be 5955 * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input 5956 * type. 5957 * 5958 * @see #getInputType() 5959 * @see #setRawInputType(int) 5960 * @see android.text.InputType 5961 * @attr ref android.R.styleable#TextView_inputType 5962 */ 5963 public void setInputType(int type) { 5964 final boolean wasPassword = isPasswordInputType(getInputType()); 5965 final boolean wasVisiblePassword = isVisiblePasswordInputType(getInputType()); 5966 setInputType(type, false); 5967 final boolean isPassword = isPasswordInputType(type); 5968 final boolean isVisiblePassword = isVisiblePasswordInputType(type); 5969 boolean forceUpdate = false; 5970 if (isPassword) { 5971 setTransformationMethod(PasswordTransformationMethod.getInstance()); 5972 setTypefaceFromAttrs(null/* fontTypeface */, null /* fontFamily */, MONOSPACE, 5973 Typeface.NORMAL, -1 /* weight, not specifeid */); 5974 } else if (isVisiblePassword) { 5975 if (mTransformation == PasswordTransformationMethod.getInstance()) { 5976 forceUpdate = true; 5977 } 5978 setTypefaceFromAttrs(null/* fontTypeface */, null /* fontFamily */, MONOSPACE, 5979 Typeface.NORMAL, -1 /* weight, not specified */); 5980 } else if (wasPassword || wasVisiblePassword) { 5981 // not in password mode, clean up typeface and transformation 5982 setTypefaceFromAttrs(null/* fontTypeface */, null /* fontFamily */, 5983 DEFAULT_TYPEFACE /* typeface index */, Typeface.NORMAL, 5984 -1 /* weight, not specified */); 5985 if (mTransformation == PasswordTransformationMethod.getInstance()) { 5986 forceUpdate = true; 5987 } 5988 } 5989 5990 boolean singleLine = !isMultilineInputType(type); 5991 5992 // We need to update the single line mode if it has changed or we 5993 // were previously in password mode. 5994 if (mSingleLine != singleLine || forceUpdate) { 5995 // Change single line mode, but only change the transformation if 5996 // we are not in password mode. 5997 applySingleLine(singleLine, !isPassword, true); 5998 } 5999 6000 if (!isSuggestionsEnabled()) { 6001 mText = removeSuggestionSpans(mText); 6002 } 6003 6004 InputMethodManager imm = InputMethodManager.peekInstance(); 6005 if (imm != null) imm.restartInput(this); 6006 } 6007 6008 /** 6009 * It would be better to rely on the input type for everything. A password inputType should have 6010 * a password transformation. We should hence use isPasswordInputType instead of this method. 6011 * 6012 * We should: 6013 * - Call setInputType in setKeyListener instead of changing the input type directly (which 6014 * would install the correct transformation). 6015 * - Refuse the installation of a non-password transformation in setTransformation if the input 6016 * type is password. 6017 * 6018 * However, this is like this for legacy reasons and we cannot break existing apps. This method 6019 * is useful since it matches what the user can see (obfuscated text or not). 6020 * 6021 * @return true if the current transformation method is of the password type. 6022 */ 6023 boolean hasPasswordTransformationMethod() { 6024 return mTransformation instanceof PasswordTransformationMethod; 6025 } 6026 6027 static boolean isPasswordInputType(int inputType) { 6028 final int variation = 6029 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 6030 return variation 6031 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD) 6032 || variation 6033 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD) 6034 || variation 6035 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 6036 } 6037 6038 private static boolean isVisiblePasswordInputType(int inputType) { 6039 final int variation = 6040 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 6041 return variation 6042 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); 6043 } 6044 6045 /** 6046 * Directly change the content type integer of the text view, without 6047 * modifying any other state. 6048 * @see #setInputType(int) 6049 * @see android.text.InputType 6050 * @attr ref android.R.styleable#TextView_inputType 6051 */ 6052 public void setRawInputType(int type) { 6053 if (type == InputType.TYPE_NULL && mEditor == null) return; //TYPE_NULL is the default value 6054 createEditorIfNeeded(); 6055 mEditor.mInputType = type; 6056 } 6057 6058 /** 6059 * @return {@code null} if the key listener should use pre-O (locale-independent). Otherwise 6060 * a {@code Locale} object that can be used to customize key various listeners. 6061 * @see DateKeyListener#getInstance(Locale) 6062 * @see DateTimeKeyListener#getInstance(Locale) 6063 * @see DigitsKeyListener#getInstance(Locale) 6064 * @see TimeKeyListener#getInstance(Locale) 6065 */ 6066 @Nullable 6067 private Locale getCustomLocaleForKeyListenerOrNull() { 6068 if (!mUseInternationalizedInput) { 6069 // If the application does not target O, stick to the previous behavior. 6070 return null; 6071 } 6072 final LocaleList locales = getImeHintLocales(); 6073 if (locales == null) { 6074 // If the application does not explicitly specify IME hint locale, also stick to the 6075 // previous behavior. 6076 return null; 6077 } 6078 return locales.get(0); 6079 } 6080 6081 private void setInputType(int type, boolean direct) { 6082 final int cls = type & EditorInfo.TYPE_MASK_CLASS; 6083 KeyListener input; 6084 if (cls == EditorInfo.TYPE_CLASS_TEXT) { 6085 boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0; 6086 TextKeyListener.Capitalize cap; 6087 if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) { 6088 cap = TextKeyListener.Capitalize.CHARACTERS; 6089 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) { 6090 cap = TextKeyListener.Capitalize.WORDS; 6091 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) { 6092 cap = TextKeyListener.Capitalize.SENTENCES; 6093 } else { 6094 cap = TextKeyListener.Capitalize.NONE; 6095 } 6096 input = TextKeyListener.getInstance(autotext, cap); 6097 } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) { 6098 final Locale locale = getCustomLocaleForKeyListenerOrNull(); 6099 input = DigitsKeyListener.getInstance( 6100 locale, 6101 (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0, 6102 (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0); 6103 if (locale != null) { 6104 // Override type, if necessary for i18n. 6105 int newType = input.getInputType(); 6106 final int newClass = newType & EditorInfo.TYPE_MASK_CLASS; 6107 if (newClass != EditorInfo.TYPE_CLASS_NUMBER) { 6108 // The class is different from the original class. So we need to override 6109 // 'type'. But we want to keep the password flag if it's there. 6110 if ((type & EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD) != 0) { 6111 newType |= EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 6112 } 6113 type = newType; 6114 } 6115 } 6116 } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) { 6117 final Locale locale = getCustomLocaleForKeyListenerOrNull(); 6118 switch (type & EditorInfo.TYPE_MASK_VARIATION) { 6119 case EditorInfo.TYPE_DATETIME_VARIATION_DATE: 6120 input = DateKeyListener.getInstance(locale); 6121 break; 6122 case EditorInfo.TYPE_DATETIME_VARIATION_TIME: 6123 input = TimeKeyListener.getInstance(locale); 6124 break; 6125 default: 6126 input = DateTimeKeyListener.getInstance(locale); 6127 break; 6128 } 6129 if (mUseInternationalizedInput) { 6130 type = input.getInputType(); // Override type, if necessary for i18n. 6131 } 6132 } else if (cls == EditorInfo.TYPE_CLASS_PHONE) { 6133 input = DialerKeyListener.getInstance(); 6134 } else { 6135 input = TextKeyListener.getInstance(); 6136 } 6137 setRawInputType(type); 6138 mListenerChanged = false; 6139 if (direct) { 6140 createEditorIfNeeded(); 6141 mEditor.mKeyListener = input; 6142 } else { 6143 setKeyListenerOnly(input); 6144 } 6145 } 6146 6147 /** 6148 * Get the type of the editable content. 6149 * 6150 * @see #setInputType(int) 6151 * @see android.text.InputType 6152 */ 6153 public int getInputType() { 6154 return mEditor == null ? EditorInfo.TYPE_NULL : mEditor.mInputType; 6155 } 6156 6157 /** 6158 * Change the editor type integer associated with the text view, which 6159 * is reported to an Input Method Editor (IME) with {@link EditorInfo#imeOptions} 6160 * when it has focus. 6161 * @see #getImeOptions 6162 * @see android.view.inputmethod.EditorInfo 6163 * @attr ref android.R.styleable#TextView_imeOptions 6164 */ 6165 public void setImeOptions(int imeOptions) { 6166 createEditorIfNeeded(); 6167 mEditor.createInputContentTypeIfNeeded(); 6168 mEditor.mInputContentType.imeOptions = imeOptions; 6169 } 6170 6171 /** 6172 * Get the type of the Input Method Editor (IME). 6173 * @return the type of the IME 6174 * @see #setImeOptions(int) 6175 * @see android.view.inputmethod.EditorInfo 6176 */ 6177 public int getImeOptions() { 6178 return mEditor != null && mEditor.mInputContentType != null 6179 ? mEditor.mInputContentType.imeOptions : EditorInfo.IME_NULL; 6180 } 6181 6182 /** 6183 * Change the custom IME action associated with the text view, which 6184 * will be reported to an IME with {@link EditorInfo#actionLabel} 6185 * and {@link EditorInfo#actionId} when it has focus. 6186 * @see #getImeActionLabel 6187 * @see #getImeActionId 6188 * @see android.view.inputmethod.EditorInfo 6189 * @attr ref android.R.styleable#TextView_imeActionLabel 6190 * @attr ref android.R.styleable#TextView_imeActionId 6191 */ 6192 public void setImeActionLabel(CharSequence label, int actionId) { 6193 createEditorIfNeeded(); 6194 mEditor.createInputContentTypeIfNeeded(); 6195 mEditor.mInputContentType.imeActionLabel = label; 6196 mEditor.mInputContentType.imeActionId = actionId; 6197 } 6198 6199 /** 6200 * Get the IME action label previous set with {@link #setImeActionLabel}. 6201 * 6202 * @see #setImeActionLabel 6203 * @see android.view.inputmethod.EditorInfo 6204 */ 6205 public CharSequence getImeActionLabel() { 6206 return mEditor != null && mEditor.mInputContentType != null 6207 ? mEditor.mInputContentType.imeActionLabel : null; 6208 } 6209 6210 /** 6211 * Get the IME action ID previous set with {@link #setImeActionLabel}. 6212 * 6213 * @see #setImeActionLabel 6214 * @see android.view.inputmethod.EditorInfo 6215 */ 6216 public int getImeActionId() { 6217 return mEditor != null && mEditor.mInputContentType != null 6218 ? mEditor.mInputContentType.imeActionId : 0; 6219 } 6220 6221 /** 6222 * Set a special listener to be called when an action is performed 6223 * on the text view. This will be called when the enter key is pressed, 6224 * or when an action supplied to the IME is selected by the user. Setting 6225 * this means that the normal hard key event will not insert a newline 6226 * into the text view, even if it is multi-line; holding down the ALT 6227 * modifier will, however, allow the user to insert a newline character. 6228 */ 6229 public void setOnEditorActionListener(OnEditorActionListener l) { 6230 createEditorIfNeeded(); 6231 mEditor.createInputContentTypeIfNeeded(); 6232 mEditor.mInputContentType.onEditorActionListener = l; 6233 } 6234 6235 /** 6236 * Called when an attached input method calls 6237 * {@link InputConnection#performEditorAction(int) 6238 * InputConnection.performEditorAction()} 6239 * for this text view. The default implementation will call your action 6240 * listener supplied to {@link #setOnEditorActionListener}, or perform 6241 * a standard operation for {@link EditorInfo#IME_ACTION_NEXT 6242 * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS 6243 * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE 6244 * EditorInfo.IME_ACTION_DONE}. 6245 * 6246 * <p>For backwards compatibility, if no IME options have been set and the 6247 * text view would not normally advance focus on enter, then 6248 * the NEXT and DONE actions received here will be turned into an enter 6249 * key down/up pair to go through the normal key handling. 6250 * 6251 * @param actionCode The code of the action being performed. 6252 * 6253 * @see #setOnEditorActionListener 6254 */ 6255 public void onEditorAction(int actionCode) { 6256 final Editor.InputContentType ict = mEditor == null ? null : mEditor.mInputContentType; 6257 if (ict != null) { 6258 if (ict.onEditorActionListener != null) { 6259 if (ict.onEditorActionListener.onEditorAction(this, 6260 actionCode, null)) { 6261 return; 6262 } 6263 } 6264 6265 // This is the handling for some default action. 6266 // Note that for backwards compatibility we don't do this 6267 // default handling if explicit ime options have not been given, 6268 // instead turning this into the normal enter key codes that an 6269 // app may be expecting. 6270 if (actionCode == EditorInfo.IME_ACTION_NEXT) { 6271 View v = focusSearch(FOCUS_FORWARD); 6272 if (v != null) { 6273 if (!v.requestFocus(FOCUS_FORWARD)) { 6274 throw new IllegalStateException("focus search returned a view " 6275 + "that wasn't able to take focus!"); 6276 } 6277 } 6278 return; 6279 6280 } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) { 6281 View v = focusSearch(FOCUS_BACKWARD); 6282 if (v != null) { 6283 if (!v.requestFocus(FOCUS_BACKWARD)) { 6284 throw new IllegalStateException("focus search returned a view " 6285 + "that wasn't able to take focus!"); 6286 } 6287 } 6288 return; 6289 6290 } else if (actionCode == EditorInfo.IME_ACTION_DONE) { 6291 InputMethodManager imm = InputMethodManager.peekInstance(); 6292 if (imm != null && imm.isActive(this)) { 6293 imm.hideSoftInputFromWindow(getWindowToken(), 0); 6294 } 6295 return; 6296 } 6297 } 6298 6299 ViewRootImpl viewRootImpl = getViewRootImpl(); 6300 if (viewRootImpl != null) { 6301 long eventTime = SystemClock.uptimeMillis(); 6302 viewRootImpl.dispatchKeyFromIme( 6303 new KeyEvent(eventTime, eventTime, 6304 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, 6305 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 6306 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 6307 | KeyEvent.FLAG_EDITOR_ACTION)); 6308 viewRootImpl.dispatchKeyFromIme( 6309 new KeyEvent(SystemClock.uptimeMillis(), eventTime, 6310 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 6311 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 6312 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 6313 | KeyEvent.FLAG_EDITOR_ACTION)); 6314 } 6315 } 6316 6317 /** 6318 * Set the private content type of the text, which is the 6319 * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} 6320 * field that will be filled in when creating an input connection. 6321 * 6322 * @see #getPrivateImeOptions() 6323 * @see EditorInfo#privateImeOptions 6324 * @attr ref android.R.styleable#TextView_privateImeOptions 6325 */ 6326 public void setPrivateImeOptions(String type) { 6327 createEditorIfNeeded(); 6328 mEditor.createInputContentTypeIfNeeded(); 6329 mEditor.mInputContentType.privateImeOptions = type; 6330 } 6331 6332 /** 6333 * Get the private type of the content. 6334 * 6335 * @see #setPrivateImeOptions(String) 6336 * @see EditorInfo#privateImeOptions 6337 */ 6338 public String getPrivateImeOptions() { 6339 return mEditor != null && mEditor.mInputContentType != null 6340 ? mEditor.mInputContentType.privateImeOptions : null; 6341 } 6342 6343 /** 6344 * Set the extra input data of the text, which is the 6345 * {@link EditorInfo#extras TextBoxAttribute.extras} 6346 * Bundle that will be filled in when creating an input connection. The 6347 * given integer is the resource identifier of an XML resource holding an 6348 * {@link android.R.styleable#InputExtras <input-extras>} XML tree. 6349 * 6350 * @see #getInputExtras(boolean) 6351 * @see EditorInfo#extras 6352 * @attr ref android.R.styleable#TextView_editorExtras 6353 */ 6354 public void setInputExtras(@XmlRes int xmlResId) throws XmlPullParserException, IOException { 6355 createEditorIfNeeded(); 6356 XmlResourceParser parser = getResources().getXml(xmlResId); 6357 mEditor.createInputContentTypeIfNeeded(); 6358 mEditor.mInputContentType.extras = new Bundle(); 6359 getResources().parseBundleExtras(parser, mEditor.mInputContentType.extras); 6360 } 6361 6362 /** 6363 * Retrieve the input extras currently associated with the text view, which 6364 * can be viewed as well as modified. 6365 * 6366 * @param create If true, the extras will be created if they don't already 6367 * exist. Otherwise, null will be returned if none have been created. 6368 * @see #setInputExtras(int) 6369 * @see EditorInfo#extras 6370 * @attr ref android.R.styleable#TextView_editorExtras 6371 */ 6372 public Bundle getInputExtras(boolean create) { 6373 if (mEditor == null && !create) return null; 6374 createEditorIfNeeded(); 6375 if (mEditor.mInputContentType == null) { 6376 if (!create) return null; 6377 mEditor.createInputContentTypeIfNeeded(); 6378 } 6379 if (mEditor.mInputContentType.extras == null) { 6380 if (!create) return null; 6381 mEditor.mInputContentType.extras = new Bundle(); 6382 } 6383 return mEditor.mInputContentType.extras; 6384 } 6385 6386 /** 6387 * Change "hint" locales associated with the text view, which will be reported to an IME with 6388 * {@link EditorInfo#hintLocales} when it has focus. 6389 * 6390 * Starting with Android O, this also causes internationalized listeners to be created (or 6391 * change locale) based on the first locale in the input locale list. 6392 * 6393 * <p><strong>Note:</strong> If you want new "hint" to take effect immediately you need to 6394 * call {@link InputMethodManager#restartInput(View)}.</p> 6395 * @param hintLocales List of the languages that the user is supposed to switch to no matter 6396 * what input method subtype is currently used. Set {@code null} to clear the current "hint". 6397 * @see #getImeHintLocales() 6398 * @see android.view.inputmethod.EditorInfo#hintLocales 6399 */ 6400 public void setImeHintLocales(@Nullable LocaleList hintLocales) { 6401 createEditorIfNeeded(); 6402 mEditor.createInputContentTypeIfNeeded(); 6403 mEditor.mInputContentType.imeHintLocales = hintLocales; 6404 if (mUseInternationalizedInput) { 6405 changeListenerLocaleTo(hintLocales == null ? null : hintLocales.get(0)); 6406 } 6407 } 6408 6409 /** 6410 * @return The current languages list "hint". {@code null} when no "hint" is available. 6411 * @see #setImeHintLocales(LocaleList) 6412 * @see android.view.inputmethod.EditorInfo#hintLocales 6413 */ 6414 @Nullable 6415 public LocaleList getImeHintLocales() { 6416 if (mEditor == null) { 6417 return null; 6418 } 6419 if (mEditor.mInputContentType == null) { 6420 return null; 6421 } 6422 return mEditor.mInputContentType.imeHintLocales; 6423 } 6424 6425 /** 6426 * Returns the error message that was set to be displayed with 6427 * {@link #setError}, or <code>null</code> if no error was set 6428 * or if it the error was cleared by the widget after user input. 6429 */ 6430 public CharSequence getError() { 6431 return mEditor == null ? null : mEditor.mError; 6432 } 6433 6434 /** 6435 * Sets the right-hand compound drawable of the TextView to the "error" 6436 * icon and sets an error message that will be displayed in a popup when 6437 * the TextView has focus. The icon and error message will be reset to 6438 * null when any key events cause changes to the TextView's text. If the 6439 * <code>error</code> is <code>null</code>, the error message and icon 6440 * will be cleared. 6441 */ 6442 @android.view.RemotableViewMethod 6443 public void setError(CharSequence error) { 6444 if (error == null) { 6445 setError(null, null); 6446 } else { 6447 Drawable dr = getContext().getDrawable( 6448 com.android.internal.R.drawable.indicator_input_error); 6449 6450 dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); 6451 setError(error, dr); 6452 } 6453 } 6454 6455 /** 6456 * Sets the right-hand compound drawable of the TextView to the specified 6457 * icon and sets an error message that will be displayed in a popup when 6458 * the TextView has focus. The icon and error message will be reset to 6459 * null when any key events cause changes to the TextView's text. The 6460 * drawable must already have had {@link Drawable#setBounds} set on it. 6461 * If the <code>error</code> is <code>null</code>, the error message will 6462 * be cleared (and you should provide a <code>null</code> icon as well). 6463 */ 6464 public void setError(CharSequence error, Drawable icon) { 6465 createEditorIfNeeded(); 6466 mEditor.setError(error, icon); 6467 notifyViewAccessibilityStateChangedIfNeeded( 6468 AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED); 6469 } 6470 6471 @Override 6472 protected boolean setFrame(int l, int t, int r, int b) { 6473 boolean result = super.setFrame(l, t, r, b); 6474 6475 if (mEditor != null) mEditor.setFrame(); 6476 6477 restartMarqueeIfNeeded(); 6478 6479 return result; 6480 } 6481 6482 private void restartMarqueeIfNeeded() { 6483 if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6484 mRestartMarquee = false; 6485 startMarquee(); 6486 } 6487 } 6488 6489 /** 6490 * Sets the list of input filters that will be used if the buffer is 6491 * Editable. Has no effect otherwise. 6492 * 6493 * @attr ref android.R.styleable#TextView_maxLength 6494 */ 6495 public void setFilters(InputFilter[] filters) { 6496 if (filters == null) { 6497 throw new IllegalArgumentException(); 6498 } 6499 6500 mFilters = filters; 6501 6502 if (mText instanceof Editable) { 6503 setFilters((Editable) mText, filters); 6504 } 6505 } 6506 6507 /** 6508 * Sets the list of input filters on the specified Editable, 6509 * and includes mInput in the list if it is an InputFilter. 6510 */ 6511 private void setFilters(Editable e, InputFilter[] filters) { 6512 if (mEditor != null) { 6513 final boolean undoFilter = mEditor.mUndoInputFilter != null; 6514 final boolean keyFilter = mEditor.mKeyListener instanceof InputFilter; 6515 int num = 0; 6516 if (undoFilter) num++; 6517 if (keyFilter) num++; 6518 if (num > 0) { 6519 InputFilter[] nf = new InputFilter[filters.length + num]; 6520 6521 System.arraycopy(filters, 0, nf, 0, filters.length); 6522 num = 0; 6523 if (undoFilter) { 6524 nf[filters.length] = mEditor.mUndoInputFilter; 6525 num++; 6526 } 6527 if (keyFilter) { 6528 nf[filters.length + num] = (InputFilter) mEditor.mKeyListener; 6529 } 6530 6531 e.setFilters(nf); 6532 return; 6533 } 6534 } 6535 e.setFilters(filters); 6536 } 6537 6538 /** 6539 * Returns the current list of input filters. 6540 * 6541 * @attr ref android.R.styleable#TextView_maxLength 6542 */ 6543 public InputFilter[] getFilters() { 6544 return mFilters; 6545 } 6546 6547 ///////////////////////////////////////////////////////////////////////// 6548 6549 private int getBoxHeight(Layout l) { 6550 Insets opticalInsets = isLayoutModeOptical(mParent) ? getOpticalInsets() : Insets.NONE; 6551 int padding = (l == mHintLayout) 6552 ? getCompoundPaddingTop() + getCompoundPaddingBottom() 6553 : getExtendedPaddingTop() + getExtendedPaddingBottom(); 6554 return getMeasuredHeight() - padding + opticalInsets.top + opticalInsets.bottom; 6555 } 6556 6557 int getVerticalOffset(boolean forceNormal) { 6558 int voffset = 0; 6559 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 6560 6561 Layout l = mLayout; 6562 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 6563 l = mHintLayout; 6564 } 6565 6566 if (gravity != Gravity.TOP) { 6567 int boxht = getBoxHeight(l); 6568 int textht = l.getHeight(); 6569 6570 if (textht < boxht) { 6571 if (gravity == Gravity.BOTTOM) { 6572 voffset = boxht - textht; 6573 } else { // (gravity == Gravity.CENTER_VERTICAL) 6574 voffset = (boxht - textht) >> 1; 6575 } 6576 } 6577 } 6578 return voffset; 6579 } 6580 6581 private int getBottomVerticalOffset(boolean forceNormal) { 6582 int voffset = 0; 6583 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 6584 6585 Layout l = mLayout; 6586 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 6587 l = mHintLayout; 6588 } 6589 6590 if (gravity != Gravity.BOTTOM) { 6591 int boxht = getBoxHeight(l); 6592 int textht = l.getHeight(); 6593 6594 if (textht < boxht) { 6595 if (gravity == Gravity.TOP) { 6596 voffset = boxht - textht; 6597 } else { // (gravity == Gravity.CENTER_VERTICAL) 6598 voffset = (boxht - textht) >> 1; 6599 } 6600 } 6601 } 6602 return voffset; 6603 } 6604 6605 void invalidateCursorPath() { 6606 if (mHighlightPathBogus) { 6607 invalidateCursor(); 6608 } else { 6609 final int horizontalPadding = getCompoundPaddingLeft(); 6610 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 6611 6612 if (mEditor.mDrawableForCursor == null) { 6613 synchronized (TEMP_RECTF) { 6614 /* 6615 * The reason for this concern about the thickness of the 6616 * cursor and doing the floor/ceil on the coordinates is that 6617 * some EditTexts (notably textfields in the Browser) have 6618 * anti-aliased text where not all the characters are 6619 * necessarily at integer-multiple locations. This should 6620 * make sure the entire cursor gets invalidated instead of 6621 * sometimes missing half a pixel. 6622 */ 6623 float thick = (float) Math.ceil(mTextPaint.getStrokeWidth()); 6624 if (thick < 1.0f) { 6625 thick = 1.0f; 6626 } 6627 6628 thick /= 2.0f; 6629 6630 // mHighlightPath is guaranteed to be non null at that point. 6631 mHighlightPath.computeBounds(TEMP_RECTF, false); 6632 6633 invalidate((int) Math.floor(horizontalPadding + TEMP_RECTF.left - thick), 6634 (int) Math.floor(verticalPadding + TEMP_RECTF.top - thick), 6635 (int) Math.ceil(horizontalPadding + TEMP_RECTF.right + thick), 6636 (int) Math.ceil(verticalPadding + TEMP_RECTF.bottom + thick)); 6637 } 6638 } else { 6639 final Rect bounds = mEditor.mDrawableForCursor.getBounds(); 6640 invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding, 6641 bounds.right + horizontalPadding, bounds.bottom + verticalPadding); 6642 } 6643 } 6644 } 6645 6646 void invalidateCursor() { 6647 int where = getSelectionEnd(); 6648 6649 invalidateCursor(where, where, where); 6650 } 6651 6652 private void invalidateCursor(int a, int b, int c) { 6653 if (a >= 0 || b >= 0 || c >= 0) { 6654 int start = Math.min(Math.min(a, b), c); 6655 int end = Math.max(Math.max(a, b), c); 6656 invalidateRegion(start, end, true /* Also invalidates blinking cursor */); 6657 } 6658 } 6659 6660 /** 6661 * Invalidates the region of text enclosed between the start and end text offsets. 6662 */ 6663 void invalidateRegion(int start, int end, boolean invalidateCursor) { 6664 if (mLayout == null) { 6665 invalidate(); 6666 } else { 6667 int lineStart = mLayout.getLineForOffset(start); 6668 int top = mLayout.getLineTop(lineStart); 6669 6670 // This is ridiculous, but the descent from the line above 6671 // can hang down into the line we really want to redraw, 6672 // so we have to invalidate part of the line above to make 6673 // sure everything that needs to be redrawn really is. 6674 // (But not the whole line above, because that would cause 6675 // the same problem with the descenders on the line above it!) 6676 if (lineStart > 0) { 6677 top -= mLayout.getLineDescent(lineStart - 1); 6678 } 6679 6680 int lineEnd; 6681 6682 if (start == end) { 6683 lineEnd = lineStart; 6684 } else { 6685 lineEnd = mLayout.getLineForOffset(end); 6686 } 6687 6688 int bottom = mLayout.getLineBottom(lineEnd); 6689 6690 // mEditor can be null in case selection is set programmatically. 6691 if (invalidateCursor && mEditor != null && mEditor.mDrawableForCursor != null) { 6692 final Rect bounds = mEditor.mDrawableForCursor.getBounds(); 6693 top = Math.min(top, bounds.top); 6694 bottom = Math.max(bottom, bounds.bottom); 6695 } 6696 6697 final int compoundPaddingLeft = getCompoundPaddingLeft(); 6698 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 6699 6700 int left, right; 6701 if (lineStart == lineEnd && !invalidateCursor) { 6702 left = (int) mLayout.getPrimaryHorizontal(start); 6703 right = (int) (mLayout.getPrimaryHorizontal(end) + 1.0); 6704 left += compoundPaddingLeft; 6705 right += compoundPaddingLeft; 6706 } else { 6707 // Rectangle bounding box when the region spans several lines 6708 left = compoundPaddingLeft; 6709 right = getWidth() - getCompoundPaddingRight(); 6710 } 6711 6712 invalidate(mScrollX + left, verticalPadding + top, 6713 mScrollX + right, verticalPadding + bottom); 6714 } 6715 } 6716 6717 private void registerForPreDraw() { 6718 if (!mPreDrawRegistered) { 6719 getViewTreeObserver().addOnPreDrawListener(this); 6720 mPreDrawRegistered = true; 6721 } 6722 } 6723 6724 private void unregisterForPreDraw() { 6725 getViewTreeObserver().removeOnPreDrawListener(this); 6726 mPreDrawRegistered = false; 6727 mPreDrawListenerDetached = false; 6728 } 6729 6730 /** 6731 * {@inheritDoc} 6732 */ 6733 @Override 6734 public boolean onPreDraw() { 6735 if (mLayout == null) { 6736 assumeLayout(); 6737 } 6738 6739 if (mMovement != null) { 6740 /* This code also provides auto-scrolling when a cursor is moved using a 6741 * CursorController (insertion point or selection limits). 6742 * For selection, ensure start or end is visible depending on controller's state. 6743 */ 6744 int curs = getSelectionEnd(); 6745 // Do not create the controller if it is not already created. 6746 if (mEditor != null && mEditor.mSelectionModifierCursorController != null 6747 && mEditor.mSelectionModifierCursorController.isSelectionStartDragged()) { 6748 curs = getSelectionStart(); 6749 } 6750 6751 /* 6752 * TODO: This should really only keep the end in view if 6753 * it already was before the text changed. I'm not sure 6754 * of a good way to tell from here if it was. 6755 */ 6756 if (curs < 0 && (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6757 curs = mText.length(); 6758 } 6759 6760 if (curs >= 0) { 6761 bringPointIntoView(curs); 6762 } 6763 } else { 6764 bringTextIntoView(); 6765 } 6766 6767 // This has to be checked here since: 6768 // - onFocusChanged cannot start it when focus is given to a view with selected text (after 6769 // a screen rotation) since layout is not yet initialized at that point. 6770 if (mEditor != null && mEditor.mCreatedWithASelection) { 6771 mEditor.refreshTextActionMode(); 6772 mEditor.mCreatedWithASelection = false; 6773 } 6774 6775 unregisterForPreDraw(); 6776 6777 return true; 6778 } 6779 6780 @Override 6781 protected void onAttachedToWindow() { 6782 super.onAttachedToWindow(); 6783 6784 if (mEditor != null) mEditor.onAttachedToWindow(); 6785 6786 if (mPreDrawListenerDetached) { 6787 getViewTreeObserver().addOnPreDrawListener(this); 6788 mPreDrawListenerDetached = false; 6789 } 6790 } 6791 6792 /** @hide */ 6793 @Override 6794 protected void onDetachedFromWindowInternal() { 6795 if (mPreDrawRegistered) { 6796 getViewTreeObserver().removeOnPreDrawListener(this); 6797 mPreDrawListenerDetached = true; 6798 } 6799 6800 resetResolvedDrawables(); 6801 6802 if (mEditor != null) mEditor.onDetachedFromWindow(); 6803 6804 super.onDetachedFromWindowInternal(); 6805 } 6806 6807 @Override 6808 public void onScreenStateChanged(int screenState) { 6809 super.onScreenStateChanged(screenState); 6810 if (mEditor != null) mEditor.onScreenStateChanged(screenState); 6811 } 6812 6813 @Override 6814 protected boolean isPaddingOffsetRequired() { 6815 return mShadowRadius != 0 || mDrawables != null; 6816 } 6817 6818 @Override 6819 protected int getLeftPaddingOffset() { 6820 return getCompoundPaddingLeft() - mPaddingLeft 6821 + (int) Math.min(0, mShadowDx - mShadowRadius); 6822 } 6823 6824 @Override 6825 protected int getTopPaddingOffset() { 6826 return (int) Math.min(0, mShadowDy - mShadowRadius); 6827 } 6828 6829 @Override 6830 protected int getBottomPaddingOffset() { 6831 return (int) Math.max(0, mShadowDy + mShadowRadius); 6832 } 6833 6834 @Override 6835 protected int getRightPaddingOffset() { 6836 return -(getCompoundPaddingRight() - mPaddingRight) 6837 + (int) Math.max(0, mShadowDx + mShadowRadius); 6838 } 6839 6840 @Override 6841 protected boolean verifyDrawable(@NonNull Drawable who) { 6842 final boolean verified = super.verifyDrawable(who); 6843 if (!verified && mDrawables != null) { 6844 for (Drawable dr : mDrawables.mShowing) { 6845 if (who == dr) { 6846 return true; 6847 } 6848 } 6849 } 6850 return verified; 6851 } 6852 6853 @Override 6854 public void jumpDrawablesToCurrentState() { 6855 super.jumpDrawablesToCurrentState(); 6856 if (mDrawables != null) { 6857 for (Drawable dr : mDrawables.mShowing) { 6858 if (dr != null) { 6859 dr.jumpToCurrentState(); 6860 } 6861 } 6862 } 6863 } 6864 6865 @Override 6866 public void invalidateDrawable(@NonNull Drawable drawable) { 6867 boolean handled = false; 6868 6869 if (verifyDrawable(drawable)) { 6870 final Rect dirty = drawable.getBounds(); 6871 int scrollX = mScrollX; 6872 int scrollY = mScrollY; 6873 6874 // IMPORTANT: The coordinates below are based on the coordinates computed 6875 // for each compound drawable in onDraw(). Make sure to update each section 6876 // accordingly. 6877 final TextView.Drawables drawables = mDrawables; 6878 if (drawables != null) { 6879 if (drawable == drawables.mShowing[Drawables.LEFT]) { 6880 final int compoundPaddingTop = getCompoundPaddingTop(); 6881 final int compoundPaddingBottom = getCompoundPaddingBottom(); 6882 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 6883 6884 scrollX += mPaddingLeft; 6885 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 6886 handled = true; 6887 } else if (drawable == drawables.mShowing[Drawables.RIGHT]) { 6888 final int compoundPaddingTop = getCompoundPaddingTop(); 6889 final int compoundPaddingBottom = getCompoundPaddingBottom(); 6890 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 6891 6892 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 6893 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 6894 handled = true; 6895 } else if (drawable == drawables.mShowing[Drawables.TOP]) { 6896 final int compoundPaddingLeft = getCompoundPaddingLeft(); 6897 final int compoundPaddingRight = getCompoundPaddingRight(); 6898 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 6899 6900 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 6901 scrollY += mPaddingTop; 6902 handled = true; 6903 } else if (drawable == drawables.mShowing[Drawables.BOTTOM]) { 6904 final int compoundPaddingLeft = getCompoundPaddingLeft(); 6905 final int compoundPaddingRight = getCompoundPaddingRight(); 6906 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 6907 6908 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 6909 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 6910 handled = true; 6911 } 6912 } 6913 6914 if (handled) { 6915 invalidate(dirty.left + scrollX, dirty.top + scrollY, 6916 dirty.right + scrollX, dirty.bottom + scrollY); 6917 } 6918 } 6919 6920 if (!handled) { 6921 super.invalidateDrawable(drawable); 6922 } 6923 } 6924 6925 @Override 6926 public boolean hasOverlappingRendering() { 6927 // horizontal fading edge causes SaveLayerAlpha, which doesn't support alpha modulation 6928 return ((getBackground() != null && getBackground().getCurrent() != null) 6929 || mText instanceof Spannable || hasSelection() 6930 || isHorizontalFadingEdgeEnabled()); 6931 } 6932 6933 /** 6934 * 6935 * Returns the state of the {@code textIsSelectable} flag (See 6936 * {@link #setTextIsSelectable setTextIsSelectable()}). Although you have to set this flag 6937 * to allow users to select and copy text in a non-editable TextView, the content of an 6938 * {@link EditText} can always be selected, independently of the value of this flag. 6939 * <p> 6940 * 6941 * @return True if the text displayed in this TextView can be selected by the user. 6942 * 6943 * @attr ref android.R.styleable#TextView_textIsSelectable 6944 */ 6945 public boolean isTextSelectable() { 6946 return mEditor == null ? false : mEditor.mTextIsSelectable; 6947 } 6948 6949 /** 6950 * Sets whether the content of this view is selectable by the user. The default is 6951 * {@code false}, meaning that the content is not selectable. 6952 * <p> 6953 * When you use a TextView to display a useful piece of information to the user (such as a 6954 * contact's address), make it selectable, so that the user can select and copy its 6955 * content. You can also use set the XML attribute 6956 * {@link android.R.styleable#TextView_textIsSelectable} to "true". 6957 * <p> 6958 * When you call this method to set the value of {@code textIsSelectable}, it sets 6959 * the flags {@code focusable}, {@code focusableInTouchMode}, {@code clickable}, 6960 * and {@code longClickable} to the same value. These flags correspond to the attributes 6961 * {@link android.R.styleable#View_focusable android:focusable}, 6962 * {@link android.R.styleable#View_focusableInTouchMode android:focusableInTouchMode}, 6963 * {@link android.R.styleable#View_clickable android:clickable}, and 6964 * {@link android.R.styleable#View_longClickable android:longClickable}. To restore any of these 6965 * flags to a state you had set previously, call one or more of the following methods: 6966 * {@link #setFocusable(boolean) setFocusable()}, 6967 * {@link #setFocusableInTouchMode(boolean) setFocusableInTouchMode()}, 6968 * {@link #setClickable(boolean) setClickable()} or 6969 * {@link #setLongClickable(boolean) setLongClickable()}. 6970 * 6971 * @param selectable Whether the content of this TextView should be selectable. 6972 */ 6973 public void setTextIsSelectable(boolean selectable) { 6974 if (!selectable && mEditor == null) return; // false is default value with no edit data 6975 6976 createEditorIfNeeded(); 6977 if (mEditor.mTextIsSelectable == selectable) return; 6978 6979 mEditor.mTextIsSelectable = selectable; 6980 setFocusableInTouchMode(selectable); 6981 setFocusable(FOCUSABLE_AUTO); 6982 setClickable(selectable); 6983 setLongClickable(selectable); 6984 6985 // mInputType should already be EditorInfo.TYPE_NULL and mInput should be null 6986 6987 setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); 6988 setText(mText, selectable ? BufferType.SPANNABLE : BufferType.NORMAL); 6989 6990 // Called by setText above, but safer in case of future code changes 6991 mEditor.prepareCursorControllers(); 6992 } 6993 6994 @Override 6995 protected int[] onCreateDrawableState(int extraSpace) { 6996 final int[] drawableState; 6997 6998 if (mSingleLine) { 6999 drawableState = super.onCreateDrawableState(extraSpace); 7000 } else { 7001 drawableState = super.onCreateDrawableState(extraSpace + 1); 7002 mergeDrawableStates(drawableState, MULTILINE_STATE_SET); 7003 } 7004 7005 if (isTextSelectable()) { 7006 // Disable pressed state, which was introduced when TextView was made clickable. 7007 // Prevents text color change. 7008 // setClickable(false) would have a similar effect, but it also disables focus changes 7009 // and long press actions, which are both needed by text selection. 7010 final int length = drawableState.length; 7011 for (int i = 0; i < length; i++) { 7012 if (drawableState[i] == R.attr.state_pressed) { 7013 final int[] nonPressedState = new int[length - 1]; 7014 System.arraycopy(drawableState, 0, nonPressedState, 0, i); 7015 System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); 7016 return nonPressedState; 7017 } 7018 } 7019 } 7020 7021 return drawableState; 7022 } 7023 7024 private Path getUpdatedHighlightPath() { 7025 Path highlight = null; 7026 Paint highlightPaint = mHighlightPaint; 7027 7028 final int selStart = getSelectionStart(); 7029 final int selEnd = getSelectionEnd(); 7030 if (mMovement != null && (isFocused() || isPressed()) && selStart >= 0) { 7031 if (selStart == selEnd) { 7032 if (mEditor != null && mEditor.shouldRenderCursor()) { 7033 if (mHighlightPathBogus) { 7034 if (mHighlightPath == null) mHighlightPath = new Path(); 7035 mHighlightPath.reset(); 7036 mLayout.getCursorPath(selStart, mHighlightPath, mText); 7037 mEditor.updateCursorPosition(); 7038 mHighlightPathBogus = false; 7039 } 7040 7041 // XXX should pass to skin instead of drawing directly 7042 highlightPaint.setColor(mCurTextColor); 7043 highlightPaint.setStyle(Paint.Style.STROKE); 7044 highlight = mHighlightPath; 7045 } 7046 } else { 7047 if (mHighlightPathBogus) { 7048 if (mHighlightPath == null) mHighlightPath = new Path(); 7049 mHighlightPath.reset(); 7050 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 7051 mHighlightPathBogus = false; 7052 } 7053 7054 // XXX should pass to skin instead of drawing directly 7055 highlightPaint.setColor(mHighlightColor); 7056 highlightPaint.setStyle(Paint.Style.FILL); 7057 7058 highlight = mHighlightPath; 7059 } 7060 } 7061 return highlight; 7062 } 7063 7064 /** 7065 * @hide 7066 */ 7067 public int getHorizontalOffsetForDrawables() { 7068 return 0; 7069 } 7070 7071 @Override 7072 protected void onDraw(Canvas canvas) { 7073 restartMarqueeIfNeeded(); 7074 7075 // Draw the background for this view 7076 super.onDraw(canvas); 7077 7078 final int compoundPaddingLeft = getCompoundPaddingLeft(); 7079 final int compoundPaddingTop = getCompoundPaddingTop(); 7080 final int compoundPaddingRight = getCompoundPaddingRight(); 7081 final int compoundPaddingBottom = getCompoundPaddingBottom(); 7082 final int scrollX = mScrollX; 7083 final int scrollY = mScrollY; 7084 final int right = mRight; 7085 final int left = mLeft; 7086 final int bottom = mBottom; 7087 final int top = mTop; 7088 final boolean isLayoutRtl = isLayoutRtl(); 7089 final int offset = getHorizontalOffsetForDrawables(); 7090 final int leftOffset = isLayoutRtl ? 0 : offset; 7091 final int rightOffset = isLayoutRtl ? offset : 0; 7092 7093 final Drawables dr = mDrawables; 7094 if (dr != null) { 7095 /* 7096 * Compound, not extended, because the icon is not clipped 7097 * if the text height is smaller. 7098 */ 7099 7100 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 7101 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 7102 7103 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 7104 // Make sure to update invalidateDrawable() when changing this code. 7105 if (dr.mShowing[Drawables.LEFT] != null) { 7106 canvas.save(); 7107 canvas.translate(scrollX + mPaddingLeft + leftOffset, 7108 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightLeft) / 2); 7109 dr.mShowing[Drawables.LEFT].draw(canvas); 7110 canvas.restore(); 7111 } 7112 7113 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 7114 // Make sure to update invalidateDrawable() when changing this code. 7115 if (dr.mShowing[Drawables.RIGHT] != null) { 7116 canvas.save(); 7117 canvas.translate(scrollX + right - left - mPaddingRight 7118 - dr.mDrawableSizeRight - rightOffset, 7119 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 7120 dr.mShowing[Drawables.RIGHT].draw(canvas); 7121 canvas.restore(); 7122 } 7123 7124 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 7125 // Make sure to update invalidateDrawable() when changing this code. 7126 if (dr.mShowing[Drawables.TOP] != null) { 7127 canvas.save(); 7128 canvas.translate(scrollX + compoundPaddingLeft 7129 + (hspace - dr.mDrawableWidthTop) / 2, scrollY + mPaddingTop); 7130 dr.mShowing[Drawables.TOP].draw(canvas); 7131 canvas.restore(); 7132 } 7133 7134 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 7135 // Make sure to update invalidateDrawable() when changing this code. 7136 if (dr.mShowing[Drawables.BOTTOM] != null) { 7137 canvas.save(); 7138 canvas.translate(scrollX + compoundPaddingLeft 7139 + (hspace - dr.mDrawableWidthBottom) / 2, 7140 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 7141 dr.mShowing[Drawables.BOTTOM].draw(canvas); 7142 canvas.restore(); 7143 } 7144 } 7145 7146 int color = mCurTextColor; 7147 7148 if (mLayout == null) { 7149 assumeLayout(); 7150 } 7151 7152 Layout layout = mLayout; 7153 7154 if (mHint != null && mText.length() == 0) { 7155 if (mHintTextColor != null) { 7156 color = mCurHintTextColor; 7157 } 7158 7159 layout = mHintLayout; 7160 } 7161 7162 mTextPaint.setColor(color); 7163 mTextPaint.drawableState = getDrawableState(); 7164 7165 canvas.save(); 7166 /* Would be faster if we didn't have to do this. Can we chop the 7167 (displayable) text so that we don't need to do this ever? 7168 */ 7169 7170 int extendedPaddingTop = getExtendedPaddingTop(); 7171 int extendedPaddingBottom = getExtendedPaddingBottom(); 7172 7173 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 7174 final int maxScrollY = mLayout.getHeight() - vspace; 7175 7176 float clipLeft = compoundPaddingLeft + scrollX; 7177 float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY; 7178 float clipRight = right - left - getCompoundPaddingRight() + scrollX; 7179 float clipBottom = bottom - top + scrollY 7180 - ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom); 7181 7182 if (mShadowRadius != 0) { 7183 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 7184 clipRight += Math.max(0, mShadowDx + mShadowRadius); 7185 7186 clipTop += Math.min(0, mShadowDy - mShadowRadius); 7187 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 7188 } 7189 7190 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 7191 7192 int voffsetText = 0; 7193 int voffsetCursor = 0; 7194 7195 // translate in by our padding 7196 /* shortcircuit calling getVerticaOffset() */ 7197 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7198 voffsetText = getVerticalOffset(false); 7199 voffsetCursor = getVerticalOffset(true); 7200 } 7201 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 7202 7203 final int layoutDirection = getLayoutDirection(); 7204 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 7205 if (isMarqueeFadeEnabled()) { 7206 if (!mSingleLine && getLineCount() == 1 && canMarquee() 7207 && (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 7208 final int width = mRight - mLeft; 7209 final int padding = getCompoundPaddingLeft() + getCompoundPaddingRight(); 7210 final float dx = mLayout.getLineRight(0) - (width - padding); 7211 canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f); 7212 } 7213 7214 if (mMarquee != null && mMarquee.isRunning()) { 7215 final float dx = -mMarquee.getScroll(); 7216 canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f); 7217 } 7218 } 7219 7220 final int cursorOffsetVertical = voffsetCursor - voffsetText; 7221 7222 Path highlight = getUpdatedHighlightPath(); 7223 if (mEditor != null) { 7224 mEditor.onDraw(canvas, layout, highlight, mHighlightPaint, cursorOffsetVertical); 7225 } else { 7226 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 7227 } 7228 7229 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 7230 final float dx = mMarquee.getGhostOffset(); 7231 canvas.translate(layout.getParagraphDirection(0) * dx, 0.0f); 7232 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 7233 } 7234 7235 canvas.restore(); 7236 } 7237 7238 @Override 7239 public void getFocusedRect(Rect r) { 7240 if (mLayout == null) { 7241 super.getFocusedRect(r); 7242 return; 7243 } 7244 7245 int selEnd = getSelectionEnd(); 7246 if (selEnd < 0) { 7247 super.getFocusedRect(r); 7248 return; 7249 } 7250 7251 int selStart = getSelectionStart(); 7252 if (selStart < 0 || selStart >= selEnd) { 7253 int line = mLayout.getLineForOffset(selEnd); 7254 r.top = mLayout.getLineTop(line); 7255 r.bottom = mLayout.getLineBottom(line); 7256 r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2; 7257 r.right = r.left + 4; 7258 } else { 7259 int lineStart = mLayout.getLineForOffset(selStart); 7260 int lineEnd = mLayout.getLineForOffset(selEnd); 7261 r.top = mLayout.getLineTop(lineStart); 7262 r.bottom = mLayout.getLineBottom(lineEnd); 7263 if (lineStart == lineEnd) { 7264 r.left = (int) mLayout.getPrimaryHorizontal(selStart); 7265 r.right = (int) mLayout.getPrimaryHorizontal(selEnd); 7266 } else { 7267 // Selection extends across multiple lines -- make the focused 7268 // rect cover the entire width. 7269 if (mHighlightPathBogus) { 7270 if (mHighlightPath == null) mHighlightPath = new Path(); 7271 mHighlightPath.reset(); 7272 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 7273 mHighlightPathBogus = false; 7274 } 7275 synchronized (TEMP_RECTF) { 7276 mHighlightPath.computeBounds(TEMP_RECTF, true); 7277 r.left = (int) TEMP_RECTF.left - 1; 7278 r.right = (int) TEMP_RECTF.right + 1; 7279 } 7280 } 7281 } 7282 7283 // Adjust for padding and gravity. 7284 int paddingLeft = getCompoundPaddingLeft(); 7285 int paddingTop = getExtendedPaddingTop(); 7286 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7287 paddingTop += getVerticalOffset(false); 7288 } 7289 r.offset(paddingLeft, paddingTop); 7290 int paddingBottom = getExtendedPaddingBottom(); 7291 r.bottom += paddingBottom; 7292 } 7293 7294 /** 7295 * Return the number of lines of text, or 0 if the internal Layout has not 7296 * been built. 7297 */ 7298 public int getLineCount() { 7299 return mLayout != null ? mLayout.getLineCount() : 0; 7300 } 7301 7302 /** 7303 * Return the baseline for the specified line (0...getLineCount() - 1) 7304 * If bounds is not null, return the top, left, right, bottom extents 7305 * of the specified line in it. If the internal Layout has not been built, 7306 * return 0 and set bounds to (0, 0, 0, 0) 7307 * @param line which line to examine (0..getLineCount() - 1) 7308 * @param bounds Optional. If not null, it returns the extent of the line 7309 * @return the Y-coordinate of the baseline 7310 */ 7311 public int getLineBounds(int line, Rect bounds) { 7312 if (mLayout == null) { 7313 if (bounds != null) { 7314 bounds.set(0, 0, 0, 0); 7315 } 7316 return 0; 7317 } else { 7318 int baseline = mLayout.getLineBounds(line, bounds); 7319 7320 int voffset = getExtendedPaddingTop(); 7321 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7322 voffset += getVerticalOffset(true); 7323 } 7324 if (bounds != null) { 7325 bounds.offset(getCompoundPaddingLeft(), voffset); 7326 } 7327 return baseline + voffset; 7328 } 7329 } 7330 7331 @Override 7332 public int getBaseline() { 7333 if (mLayout == null) { 7334 return super.getBaseline(); 7335 } 7336 7337 return getBaselineOffset() + mLayout.getLineBaseline(0); 7338 } 7339 7340 int getBaselineOffset() { 7341 int voffset = 0; 7342 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7343 voffset = getVerticalOffset(true); 7344 } 7345 7346 if (isLayoutModeOptical(mParent)) { 7347 voffset -= getOpticalInsets().top; 7348 } 7349 7350 return getExtendedPaddingTop() + voffset; 7351 } 7352 7353 /** 7354 * @hide 7355 */ 7356 @Override 7357 protected int getFadeTop(boolean offsetRequired) { 7358 if (mLayout == null) return 0; 7359 7360 int voffset = 0; 7361 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7362 voffset = getVerticalOffset(true); 7363 } 7364 7365 if (offsetRequired) voffset += getTopPaddingOffset(); 7366 7367 return getExtendedPaddingTop() + voffset; 7368 } 7369 7370 /** 7371 * @hide 7372 */ 7373 @Override 7374 protected int getFadeHeight(boolean offsetRequired) { 7375 return mLayout != null ? mLayout.getHeight() : 0; 7376 } 7377 7378 @Override 7379 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) { 7380 if (mText instanceof Spannable && mLinksClickable) { 7381 final float x = event.getX(pointerIndex); 7382 final float y = event.getY(pointerIndex); 7383 final int offset = getOffsetForPosition(x, y); 7384 final ClickableSpan[] clickables = ((Spannable) mText).getSpans(offset, offset, 7385 ClickableSpan.class); 7386 if (clickables.length > 0) { 7387 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_HAND); 7388 } 7389 } 7390 if (isTextSelectable() || isTextEditable()) { 7391 return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_TEXT); 7392 } 7393 return super.onResolvePointerIcon(event, pointerIndex); 7394 } 7395 7396 @Override 7397 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 7398 // Note: If the IME is in fullscreen mode and IMS#mExtractEditText is in text action mode, 7399 // InputMethodService#onKeyDown and InputMethodService#onKeyUp are responsible to call 7400 // InputMethodService#mExtractEditText.maybeHandleBackInTextActionMode(event). 7401 if (keyCode == KeyEvent.KEYCODE_BACK && handleBackInTextActionModeIfNeeded(event)) { 7402 return true; 7403 } 7404 return super.onKeyPreIme(keyCode, event); 7405 } 7406 7407 /** 7408 * @hide 7409 */ 7410 public boolean handleBackInTextActionModeIfNeeded(KeyEvent event) { 7411 // Do nothing unless mEditor is in text action mode. 7412 if (mEditor == null || mEditor.getTextActionMode() == null) { 7413 return false; 7414 } 7415 7416 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { 7417 KeyEvent.DispatcherState state = getKeyDispatcherState(); 7418 if (state != null) { 7419 state.startTracking(event, this); 7420 } 7421 return true; 7422 } else if (event.getAction() == KeyEvent.ACTION_UP) { 7423 KeyEvent.DispatcherState state = getKeyDispatcherState(); 7424 if (state != null) { 7425 state.handleUpEvent(event); 7426 } 7427 if (event.isTracking() && !event.isCanceled()) { 7428 stopTextActionMode(); 7429 return true; 7430 } 7431 } 7432 return false; 7433 } 7434 7435 @Override 7436 public boolean onKeyDown(int keyCode, KeyEvent event) { 7437 final int which = doKeyDown(keyCode, event, null); 7438 if (which == KEY_EVENT_NOT_HANDLED) { 7439 return super.onKeyDown(keyCode, event); 7440 } 7441 7442 return true; 7443 } 7444 7445 @Override 7446 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 7447 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 7448 final int which = doKeyDown(keyCode, down, event); 7449 if (which == KEY_EVENT_NOT_HANDLED) { 7450 // Go through default dispatching. 7451 return super.onKeyMultiple(keyCode, repeatCount, event); 7452 } 7453 if (which == KEY_EVENT_HANDLED) { 7454 // Consumed the whole thing. 7455 return true; 7456 } 7457 7458 repeatCount--; 7459 7460 // We are going to dispatch the remaining events to either the input 7461 // or movement method. To do this, we will just send a repeated stream 7462 // of down and up events until we have done the complete repeatCount. 7463 // It would be nice if those interfaces had an onKeyMultiple() method, 7464 // but adding that is a more complicated change. 7465 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 7466 if (which == KEY_DOWN_HANDLED_BY_KEY_LISTENER) { 7467 // mEditor and mEditor.mInput are not null from doKeyDown 7468 mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, up); 7469 while (--repeatCount > 0) { 7470 mEditor.mKeyListener.onKeyDown(this, (Editable) mText, keyCode, down); 7471 mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, up); 7472 } 7473 hideErrorIfUnchanged(); 7474 7475 } else if (which == KEY_DOWN_HANDLED_BY_MOVEMENT_METHOD) { 7476 // mMovement is not null from doKeyDown 7477 mMovement.onKeyUp(this, (Spannable) mText, keyCode, up); 7478 while (--repeatCount > 0) { 7479 mMovement.onKeyDown(this, (Spannable) mText, keyCode, down); 7480 mMovement.onKeyUp(this, (Spannable) mText, keyCode, up); 7481 } 7482 } 7483 7484 return true; 7485 } 7486 7487 /** 7488 * Returns true if pressing ENTER in this field advances focus instead 7489 * of inserting the character. This is true mostly in single-line fields, 7490 * but also in mail addresses and subjects which will display on multiple 7491 * lines but where it doesn't make sense to insert newlines. 7492 */ 7493 private boolean shouldAdvanceFocusOnEnter() { 7494 if (getKeyListener() == null) { 7495 return false; 7496 } 7497 7498 if (mSingleLine) { 7499 return true; 7500 } 7501 7502 if (mEditor != null 7503 && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) 7504 == EditorInfo.TYPE_CLASS_TEXT) { 7505 int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; 7506 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS 7507 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 7508 return true; 7509 } 7510 } 7511 7512 return false; 7513 } 7514 7515 /** 7516 * Returns true if pressing TAB in this field advances focus instead 7517 * of inserting the character. Insert tabs only in multi-line editors. 7518 */ 7519 private boolean shouldAdvanceFocusOnTab() { 7520 if (getKeyListener() != null && !mSingleLine && mEditor != null 7521 && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) 7522 == EditorInfo.TYPE_CLASS_TEXT) { 7523 int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; 7524 if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE 7525 || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { 7526 return false; 7527 } 7528 } 7529 return true; 7530 } 7531 7532 private boolean isDirectionalNavigationKey(int keyCode) { 7533 switch(keyCode) { 7534 case KeyEvent.KEYCODE_DPAD_UP: 7535 case KeyEvent.KEYCODE_DPAD_DOWN: 7536 case KeyEvent.KEYCODE_DPAD_LEFT: 7537 case KeyEvent.KEYCODE_DPAD_RIGHT: 7538 return true; 7539 } 7540 return false; 7541 } 7542 7543 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 7544 if (!isEnabled()) { 7545 return KEY_EVENT_NOT_HANDLED; 7546 } 7547 7548 // If this is the initial keydown, we don't want to prevent a movement away from this view. 7549 // While this shouldn't be necessary because any time we're preventing default movement we 7550 // should be restricting the focus to remain within this view, thus we'll also receive 7551 // the key up event, occasionally key up events will get dropped and we don't want to 7552 // prevent the user from traversing out of this on the next key down. 7553 if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) { 7554 mPreventDefaultMovement = false; 7555 } 7556 7557 switch (keyCode) { 7558 case KeyEvent.KEYCODE_ENTER: 7559 if (event.hasNoModifiers()) { 7560 // When mInputContentType is set, we know that we are 7561 // running in a "modern" cupcake environment, so don't need 7562 // to worry about the application trying to capture 7563 // enter key events. 7564 if (mEditor != null && mEditor.mInputContentType != null) { 7565 // If there is an action listener, given them a 7566 // chance to consume the event. 7567 if (mEditor.mInputContentType.onEditorActionListener != null 7568 && mEditor.mInputContentType.onEditorActionListener.onEditorAction( 7569 this, EditorInfo.IME_NULL, event)) { 7570 mEditor.mInputContentType.enterDown = true; 7571 // We are consuming the enter key for them. 7572 return KEY_EVENT_HANDLED; 7573 } 7574 } 7575 7576 // If our editor should move focus when enter is pressed, or 7577 // this is a generated event from an IME action button, then 7578 // don't let it be inserted into the text. 7579 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 7580 || shouldAdvanceFocusOnEnter()) { 7581 if (hasOnClickListeners()) { 7582 return KEY_EVENT_NOT_HANDLED; 7583 } 7584 return KEY_EVENT_HANDLED; 7585 } 7586 } 7587 break; 7588 7589 case KeyEvent.KEYCODE_DPAD_CENTER: 7590 if (event.hasNoModifiers()) { 7591 if (shouldAdvanceFocusOnEnter()) { 7592 return KEY_EVENT_NOT_HANDLED; 7593 } 7594 } 7595 break; 7596 7597 case KeyEvent.KEYCODE_TAB: 7598 if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 7599 if (shouldAdvanceFocusOnTab()) { 7600 return KEY_EVENT_NOT_HANDLED; 7601 } 7602 } 7603 break; 7604 7605 // Has to be done on key down (and not on key up) to correctly be intercepted. 7606 case KeyEvent.KEYCODE_BACK: 7607 if (mEditor != null && mEditor.getTextActionMode() != null) { 7608 stopTextActionMode(); 7609 return KEY_EVENT_HANDLED; 7610 } 7611 break; 7612 7613 case KeyEvent.KEYCODE_CUT: 7614 if (event.hasNoModifiers() && canCut()) { 7615 if (onTextContextMenuItem(ID_CUT)) { 7616 return KEY_EVENT_HANDLED; 7617 } 7618 } 7619 break; 7620 7621 case KeyEvent.KEYCODE_COPY: 7622 if (event.hasNoModifiers() && canCopy()) { 7623 if (onTextContextMenuItem(ID_COPY)) { 7624 return KEY_EVENT_HANDLED; 7625 } 7626 } 7627 break; 7628 7629 case KeyEvent.KEYCODE_PASTE: 7630 if (event.hasNoModifiers() && canPaste()) { 7631 if (onTextContextMenuItem(ID_PASTE)) { 7632 return KEY_EVENT_HANDLED; 7633 } 7634 } 7635 break; 7636 } 7637 7638 if (mEditor != null && mEditor.mKeyListener != null) { 7639 boolean doDown = true; 7640 if (otherEvent != null) { 7641 try { 7642 beginBatchEdit(); 7643 final boolean handled = mEditor.mKeyListener.onKeyOther(this, (Editable) mText, 7644 otherEvent); 7645 hideErrorIfUnchanged(); 7646 doDown = false; 7647 if (handled) { 7648 return KEY_EVENT_HANDLED; 7649 } 7650 } catch (AbstractMethodError e) { 7651 // onKeyOther was added after 1.0, so if it isn't 7652 // implemented we need to try to dispatch as a regular down. 7653 } finally { 7654 endBatchEdit(); 7655 } 7656 } 7657 7658 if (doDown) { 7659 beginBatchEdit(); 7660 final boolean handled = mEditor.mKeyListener.onKeyDown(this, (Editable) mText, 7661 keyCode, event); 7662 endBatchEdit(); 7663 hideErrorIfUnchanged(); 7664 if (handled) return KEY_DOWN_HANDLED_BY_KEY_LISTENER; 7665 } 7666 } 7667 7668 // bug 650865: sometimes we get a key event before a layout. 7669 // don't try to move around if we don't know the layout. 7670 7671 if (mMovement != null && mLayout != null) { 7672 boolean doDown = true; 7673 if (otherEvent != null) { 7674 try { 7675 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 7676 otherEvent); 7677 doDown = false; 7678 if (handled) { 7679 return KEY_EVENT_HANDLED; 7680 } 7681 } catch (AbstractMethodError e) { 7682 // onKeyOther was added after 1.0, so if it isn't 7683 // implemented we need to try to dispatch as a regular down. 7684 } 7685 } 7686 if (doDown) { 7687 if (mMovement.onKeyDown(this, (Spannable) mText, keyCode, event)) { 7688 if (event.getRepeatCount() == 0 && !KeyEvent.isModifierKey(keyCode)) { 7689 mPreventDefaultMovement = true; 7690 } 7691 return KEY_DOWN_HANDLED_BY_MOVEMENT_METHOD; 7692 } 7693 } 7694 // Consume arrows from keyboard devices to prevent focus leaving the editor. 7695 // DPAD/JOY devices (Gamepads, TV remotes) often lack a TAB key so allow those 7696 // to move focus with arrows. 7697 if (event.getSource() == InputDevice.SOURCE_KEYBOARD 7698 && isDirectionalNavigationKey(keyCode)) { 7699 return KEY_EVENT_HANDLED; 7700 } 7701 } 7702 7703 return mPreventDefaultMovement && !KeyEvent.isModifierKey(keyCode) 7704 ? KEY_EVENT_HANDLED : KEY_EVENT_NOT_HANDLED; 7705 } 7706 7707 /** 7708 * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} 7709 * can be recorded. 7710 * @hide 7711 */ 7712 public void resetErrorChangedFlag() { 7713 /* 7714 * Keep track of what the error was before doing the input 7715 * so that if an input filter changed the error, we leave 7716 * that error showing. Otherwise, we take down whatever 7717 * error was showing when the user types something. 7718 */ 7719 if (mEditor != null) mEditor.mErrorWasChanged = false; 7720 } 7721 7722 /** 7723 * @hide 7724 */ 7725 public void hideErrorIfUnchanged() { 7726 if (mEditor != null && mEditor.mError != null && !mEditor.mErrorWasChanged) { 7727 setError(null, null); 7728 } 7729 } 7730 7731 @Override 7732 public boolean onKeyUp(int keyCode, KeyEvent event) { 7733 if (!isEnabled()) { 7734 return super.onKeyUp(keyCode, event); 7735 } 7736 7737 if (!KeyEvent.isModifierKey(keyCode)) { 7738 mPreventDefaultMovement = false; 7739 } 7740 7741 switch (keyCode) { 7742 case KeyEvent.KEYCODE_DPAD_CENTER: 7743 if (event.hasNoModifiers()) { 7744 /* 7745 * If there is a click listener, just call through to 7746 * super, which will invoke it. 7747 * 7748 * If there isn't a click listener, try to show the soft 7749 * input method. (It will also 7750 * call performClick(), but that won't do anything in 7751 * this case.) 7752 */ 7753 if (!hasOnClickListeners()) { 7754 if (mMovement != null && mText instanceof Editable 7755 && mLayout != null && onCheckIsTextEditor()) { 7756 InputMethodManager imm = InputMethodManager.peekInstance(); 7757 viewClicked(imm); 7758 if (imm != null && getShowSoftInputOnFocus()) { 7759 imm.showSoftInput(this, 0); 7760 } 7761 } 7762 } 7763 } 7764 return super.onKeyUp(keyCode, event); 7765 7766 case KeyEvent.KEYCODE_ENTER: 7767 if (event.hasNoModifiers()) { 7768 if (mEditor != null && mEditor.mInputContentType != null 7769 && mEditor.mInputContentType.onEditorActionListener != null 7770 && mEditor.mInputContentType.enterDown) { 7771 mEditor.mInputContentType.enterDown = false; 7772 if (mEditor.mInputContentType.onEditorActionListener.onEditorAction( 7773 this, EditorInfo.IME_NULL, event)) { 7774 return true; 7775 } 7776 } 7777 7778 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 7779 || shouldAdvanceFocusOnEnter()) { 7780 /* 7781 * If there is a click listener, just call through to 7782 * super, which will invoke it. 7783 * 7784 * If there isn't a click listener, try to advance focus, 7785 * but still call through to super, which will reset the 7786 * pressed state and longpress state. (It will also 7787 * call performClick(), but that won't do anything in 7788 * this case.) 7789 */ 7790 if (!hasOnClickListeners()) { 7791 View v = focusSearch(FOCUS_DOWN); 7792 7793 if (v != null) { 7794 if (!v.requestFocus(FOCUS_DOWN)) { 7795 throw new IllegalStateException("focus search returned a view " 7796 + "that wasn't able to take focus!"); 7797 } 7798 7799 /* 7800 * Return true because we handled the key; super 7801 * will return false because there was no click 7802 * listener. 7803 */ 7804 super.onKeyUp(keyCode, event); 7805 return true; 7806 } else if ((event.getFlags() 7807 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 7808 // No target for next focus, but make sure the IME 7809 // if this came from it. 7810 InputMethodManager imm = InputMethodManager.peekInstance(); 7811 if (imm != null && imm.isActive(this)) { 7812 imm.hideSoftInputFromWindow(getWindowToken(), 0); 7813 } 7814 } 7815 } 7816 } 7817 return super.onKeyUp(keyCode, event); 7818 } 7819 break; 7820 } 7821 7822 if (mEditor != null && mEditor.mKeyListener != null) { 7823 if (mEditor.mKeyListener.onKeyUp(this, (Editable) mText, keyCode, event)) { 7824 return true; 7825 } 7826 } 7827 7828 if (mMovement != null && mLayout != null) { 7829 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) { 7830 return true; 7831 } 7832 } 7833 7834 return super.onKeyUp(keyCode, event); 7835 } 7836 7837 @Override 7838 public boolean onCheckIsTextEditor() { 7839 return mEditor != null && mEditor.mInputType != EditorInfo.TYPE_NULL; 7840 } 7841 7842 @Override 7843 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 7844 if (onCheckIsTextEditor() && isEnabled()) { 7845 mEditor.createInputMethodStateIfNeeded(); 7846 outAttrs.inputType = getInputType(); 7847 if (mEditor.mInputContentType != null) { 7848 outAttrs.imeOptions = mEditor.mInputContentType.imeOptions; 7849 outAttrs.privateImeOptions = mEditor.mInputContentType.privateImeOptions; 7850 outAttrs.actionLabel = mEditor.mInputContentType.imeActionLabel; 7851 outAttrs.actionId = mEditor.mInputContentType.imeActionId; 7852 outAttrs.extras = mEditor.mInputContentType.extras; 7853 outAttrs.hintLocales = mEditor.mInputContentType.imeHintLocales; 7854 } else { 7855 outAttrs.imeOptions = EditorInfo.IME_NULL; 7856 outAttrs.hintLocales = null; 7857 } 7858 if (focusSearch(FOCUS_DOWN) != null) { 7859 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 7860 } 7861 if (focusSearch(FOCUS_UP) != null) { 7862 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 7863 } 7864 if ((outAttrs.imeOptions & EditorInfo.IME_MASK_ACTION) 7865 == EditorInfo.IME_ACTION_UNSPECIFIED) { 7866 if ((outAttrs.imeOptions & EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 7867 // An action has not been set, but the enter key will move to 7868 // the next focus, so set the action to that. 7869 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 7870 } else { 7871 // An action has not been set, and there is no focus to move 7872 // to, so let's just supply a "done" action. 7873 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 7874 } 7875 if (!shouldAdvanceFocusOnEnter()) { 7876 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 7877 } 7878 } 7879 if (isMultilineInputType(outAttrs.inputType)) { 7880 // Multi-line text editors should always show an enter key. 7881 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 7882 } 7883 outAttrs.hintText = mHint; 7884 if (mText instanceof Editable) { 7885 InputConnection ic = new EditableInputConnection(this); 7886 outAttrs.initialSelStart = getSelectionStart(); 7887 outAttrs.initialSelEnd = getSelectionEnd(); 7888 outAttrs.initialCapsMode = ic.getCursorCapsMode(getInputType()); 7889 return ic; 7890 } 7891 } 7892 return null; 7893 } 7894 7895 /** 7896 * If this TextView contains editable content, extract a portion of it 7897 * based on the information in <var>request</var> in to <var>outText</var>. 7898 * @return Returns true if the text was successfully extracted, else false. 7899 */ 7900 public boolean extractText(ExtractedTextRequest request, ExtractedText outText) { 7901 createEditorIfNeeded(); 7902 return mEditor.extractText(request, outText); 7903 } 7904 7905 /** 7906 * This is used to remove all style-impacting spans from text before new 7907 * extracted text is being replaced into it, so that we don't have any 7908 * lingering spans applied during the replace. 7909 */ 7910 static void removeParcelableSpans(Spannable spannable, int start, int end) { 7911 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 7912 int i = spans.length; 7913 while (i > 0) { 7914 i--; 7915 spannable.removeSpan(spans[i]); 7916 } 7917 } 7918 7919 /** 7920 * Apply to this text view the given extracted text, as previously 7921 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 7922 */ 7923 public void setExtractedText(ExtractedText text) { 7924 Editable content = getEditableText(); 7925 if (text.text != null) { 7926 if (content == null) { 7927 setText(text.text, TextView.BufferType.EDITABLE); 7928 } else { 7929 int start = 0; 7930 int end = content.length(); 7931 7932 if (text.partialStartOffset >= 0) { 7933 final int N = content.length(); 7934 start = text.partialStartOffset; 7935 if (start > N) start = N; 7936 end = text.partialEndOffset; 7937 if (end > N) end = N; 7938 } 7939 7940 removeParcelableSpans(content, start, end); 7941 if (TextUtils.equals(content.subSequence(start, end), text.text)) { 7942 if (text.text instanceof Spanned) { 7943 // OK to copy spans only. 7944 TextUtils.copySpansFrom((Spanned) text.text, 0, end - start, 7945 Object.class, content, start); 7946 } 7947 } else { 7948 content.replace(start, end, text.text); 7949 } 7950 } 7951 } 7952 7953 // Now set the selection position... make sure it is in range, to 7954 // avoid crashes. If this is a partial update, it is possible that 7955 // the underlying text may have changed, causing us problems here. 7956 // Also we just don't want to trust clients to do the right thing. 7957 Spannable sp = (Spannable) getText(); 7958 final int N = sp.length(); 7959 int start = text.selectionStart; 7960 if (start < 0) { 7961 start = 0; 7962 } else if (start > N) { 7963 start = N; 7964 } 7965 int end = text.selectionEnd; 7966 if (end < 0) { 7967 end = 0; 7968 } else if (end > N) { 7969 end = N; 7970 } 7971 Selection.setSelection(sp, start, end); 7972 7973 // Finally, update the selection mode. 7974 if ((text.flags & ExtractedText.FLAG_SELECTING) != 0) { 7975 MetaKeyKeyListener.startSelecting(this, sp); 7976 } else { 7977 MetaKeyKeyListener.stopSelecting(this, sp); 7978 } 7979 7980 setHintInternal(text.hint); 7981 } 7982 7983 /** 7984 * @hide 7985 */ 7986 public void setExtracting(ExtractedTextRequest req) { 7987 if (mEditor.mInputMethodState != null) { 7988 mEditor.mInputMethodState.mExtractedTextRequest = req; 7989 } 7990 // This would stop a possible selection mode, but no such mode is started in case 7991 // extracted mode will start. Some text is selected though, and will trigger an action mode 7992 // in the extracted view. 7993 mEditor.hideCursorAndSpanControllers(); 7994 stopTextActionMode(); 7995 if (mEditor.mSelectionModifierCursorController != null) { 7996 mEditor.mSelectionModifierCursorController.resetTouchOffsets(); 7997 } 7998 } 7999 8000 /** 8001 * Called by the framework in response to a text completion from 8002 * the current input method, provided by it calling 8003 * {@link InputConnection#commitCompletion 8004 * InputConnection.commitCompletion()}. The default implementation does 8005 * nothing; text views that are supporting auto-completion should override 8006 * this to do their desired behavior. 8007 * 8008 * @param text The auto complete text the user has selected. 8009 */ 8010 public void onCommitCompletion(CompletionInfo text) { 8011 // intentionally empty 8012 } 8013 8014 /** 8015 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 8016 * dictionary) from the current input method, provided by it calling 8017 * {@link InputConnection#commitCorrection(CorrectionInfo) InputConnection.commitCorrection()}. 8018 * The default implementation flashes the background of the corrected word to provide 8019 * feedback to the user. 8020 * 8021 * @param info The auto correct info about the text that was corrected. 8022 */ 8023 public void onCommitCorrection(CorrectionInfo info) { 8024 if (mEditor != null) mEditor.onCommitCorrection(info); 8025 } 8026 8027 public void beginBatchEdit() { 8028 if (mEditor != null) mEditor.beginBatchEdit(); 8029 } 8030 8031 public void endBatchEdit() { 8032 if (mEditor != null) mEditor.endBatchEdit(); 8033 } 8034 8035 /** 8036 * Called by the framework in response to a request to begin a batch 8037 * of edit operations through a call to link {@link #beginBatchEdit()}. 8038 */ 8039 public void onBeginBatchEdit() { 8040 // intentionally empty 8041 } 8042 8043 /** 8044 * Called by the framework in response to a request to end a batch 8045 * of edit operations through a call to link {@link #endBatchEdit}. 8046 */ 8047 public void onEndBatchEdit() { 8048 // intentionally empty 8049 } 8050 8051 /** 8052 * Called by the framework in response to a private command from the 8053 * current method, provided by it calling 8054 * {@link InputConnection#performPrivateCommand 8055 * InputConnection.performPrivateCommand()}. 8056 * 8057 * @param action The action name of the command. 8058 * @param data Any additional data for the command. This may be null. 8059 * @return Return true if you handled the command, else false. 8060 */ 8061 public boolean onPrivateIMECommand(String action, Bundle data) { 8062 return false; 8063 } 8064 8065 private void nullLayouts() { 8066 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 8067 mSavedLayout = (BoringLayout) mLayout; 8068 } 8069 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 8070 mSavedHintLayout = (BoringLayout) mHintLayout; 8071 } 8072 8073 mSavedMarqueeModeLayout = mLayout = mHintLayout = null; 8074 8075 mBoring = mHintBoring = null; 8076 8077 // Since it depends on the value of mLayout 8078 if (mEditor != null) mEditor.prepareCursorControllers(); 8079 } 8080 8081 /** 8082 * Make a new Layout based on the already-measured size of the view, 8083 * on the assumption that it was measured correctly at some point. 8084 */ 8085 private void assumeLayout() { 8086 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 8087 8088 if (width < 1) { 8089 width = 0; 8090 } 8091 8092 int physicalWidth = width; 8093 8094 if (mHorizontallyScrolling) { 8095 width = VERY_WIDE; 8096 } 8097 8098 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 8099 physicalWidth, false); 8100 } 8101 8102 private Layout.Alignment getLayoutAlignment() { 8103 Layout.Alignment alignment; 8104 switch (getTextAlignment()) { 8105 case TEXT_ALIGNMENT_GRAVITY: 8106 switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) { 8107 case Gravity.START: 8108 alignment = Layout.Alignment.ALIGN_NORMAL; 8109 break; 8110 case Gravity.END: 8111 alignment = Layout.Alignment.ALIGN_OPPOSITE; 8112 break; 8113 case Gravity.LEFT: 8114 alignment = Layout.Alignment.ALIGN_LEFT; 8115 break; 8116 case Gravity.RIGHT: 8117 alignment = Layout.Alignment.ALIGN_RIGHT; 8118 break; 8119 case Gravity.CENTER_HORIZONTAL: 8120 alignment = Layout.Alignment.ALIGN_CENTER; 8121 break; 8122 default: 8123 alignment = Layout.Alignment.ALIGN_NORMAL; 8124 break; 8125 } 8126 break; 8127 case TEXT_ALIGNMENT_TEXT_START: 8128 alignment = Layout.Alignment.ALIGN_NORMAL; 8129 break; 8130 case TEXT_ALIGNMENT_TEXT_END: 8131 alignment = Layout.Alignment.ALIGN_OPPOSITE; 8132 break; 8133 case TEXT_ALIGNMENT_CENTER: 8134 alignment = Layout.Alignment.ALIGN_CENTER; 8135 break; 8136 case TEXT_ALIGNMENT_VIEW_START: 8137 alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL) 8138 ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; 8139 break; 8140 case TEXT_ALIGNMENT_VIEW_END: 8141 alignment = (getLayoutDirection() == LAYOUT_DIRECTION_RTL) 8142 ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; 8143 break; 8144 case TEXT_ALIGNMENT_INHERIT: 8145 // This should never happen as we have already resolved the text alignment 8146 // but better safe than sorry so we just fall through 8147 default: 8148 alignment = Layout.Alignment.ALIGN_NORMAL; 8149 break; 8150 } 8151 return alignment; 8152 } 8153 8154 /** 8155 * The width passed in is now the desired layout width, 8156 * not the full view width with padding. 8157 * {@hide} 8158 */ 8159 protected void makeNewLayout(int wantWidth, int hintWidth, 8160 BoringLayout.Metrics boring, 8161 BoringLayout.Metrics hintBoring, 8162 int ellipsisWidth, boolean bringIntoView) { 8163 stopMarquee(); 8164 8165 // Update "old" cached values 8166 mOldMaximum = mMaximum; 8167 mOldMaxMode = mMaxMode; 8168 8169 mHighlightPathBogus = true; 8170 8171 if (wantWidth < 0) { 8172 wantWidth = 0; 8173 } 8174 if (hintWidth < 0) { 8175 hintWidth = 0; 8176 } 8177 8178 Layout.Alignment alignment = getLayoutAlignment(); 8179 final boolean testDirChange = mSingleLine && mLayout != null 8180 && (alignment == Layout.Alignment.ALIGN_NORMAL 8181 || alignment == Layout.Alignment.ALIGN_OPPOSITE); 8182 int oldDir = 0; 8183 if (testDirChange) oldDir = mLayout.getParagraphDirection(0); 8184 boolean shouldEllipsize = mEllipsize != null && getKeyListener() == null; 8185 final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE 8186 && mMarqueeFadeMode != MARQUEE_FADE_NORMAL; 8187 TruncateAt effectiveEllipsize = mEllipsize; 8188 if (mEllipsize == TruncateAt.MARQUEE 8189 && mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 8190 effectiveEllipsize = TruncateAt.END_SMALL; 8191 } 8192 8193 if (mTextDir == null) { 8194 mTextDir = getTextDirectionHeuristic(); 8195 } 8196 8197 mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, 8198 effectiveEllipsize, effectiveEllipsize == mEllipsize); 8199 if (switchEllipsize) { 8200 TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE 8201 ? TruncateAt.END : TruncateAt.MARQUEE; 8202 mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, 8203 shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize); 8204 } 8205 8206 shouldEllipsize = mEllipsize != null; 8207 mHintLayout = null; 8208 8209 if (mHint != null) { 8210 if (shouldEllipsize) hintWidth = wantWidth; 8211 8212 if (hintBoring == UNKNOWN_BORING) { 8213 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, 8214 mHintBoring); 8215 if (hintBoring != null) { 8216 mHintBoring = hintBoring; 8217 } 8218 } 8219 8220 if (hintBoring != null) { 8221 if (hintBoring.width <= hintWidth 8222 && (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 8223 if (mSavedHintLayout != null) { 8224 mHintLayout = mSavedHintLayout.replaceOrMake(mHint, mTextPaint, 8225 hintWidth, alignment, mSpacingMult, mSpacingAdd, 8226 hintBoring, mIncludePad); 8227 } else { 8228 mHintLayout = BoringLayout.make(mHint, mTextPaint, 8229 hintWidth, alignment, mSpacingMult, mSpacingAdd, 8230 hintBoring, mIncludePad); 8231 } 8232 8233 mSavedHintLayout = (BoringLayout) mHintLayout; 8234 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 8235 if (mSavedHintLayout != null) { 8236 mHintLayout = mSavedHintLayout.replaceOrMake(mHint, mTextPaint, 8237 hintWidth, alignment, mSpacingMult, mSpacingAdd, 8238 hintBoring, mIncludePad, mEllipsize, 8239 ellipsisWidth); 8240 } else { 8241 mHintLayout = BoringLayout.make(mHint, mTextPaint, 8242 hintWidth, alignment, mSpacingMult, mSpacingAdd, 8243 hintBoring, mIncludePad, mEllipsize, 8244 ellipsisWidth); 8245 } 8246 } 8247 } 8248 // TODO: code duplication with makeSingleLayout() 8249 if (mHintLayout == null) { 8250 StaticLayout.Builder builder = StaticLayout.Builder.obtain(mHint, 0, 8251 mHint.length(), mTextPaint, hintWidth) 8252 .setAlignment(alignment) 8253 .setTextDirection(mTextDir) 8254 .setLineSpacing(mSpacingAdd, mSpacingMult) 8255 .setIncludePad(mIncludePad) 8256 .setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing) 8257 .setBreakStrategy(mBreakStrategy) 8258 .setHyphenationFrequency(mHyphenationFrequency) 8259 .setJustificationMode(mJustificationMode) 8260 .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 8261 if (shouldEllipsize) { 8262 builder.setEllipsize(mEllipsize) 8263 .setEllipsizedWidth(ellipsisWidth); 8264 } 8265 mHintLayout = builder.build(); 8266 } 8267 } 8268 8269 if (bringIntoView || (testDirChange && oldDir != mLayout.getParagraphDirection(0))) { 8270 registerForPreDraw(); 8271 } 8272 8273 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 8274 if (!compressText(ellipsisWidth)) { 8275 final int height = mLayoutParams.height; 8276 // If the size of the view does not depend on the size of the text, try to 8277 // start the marquee immediately 8278 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 8279 startMarquee(); 8280 } else { 8281 // Defer the start of the marquee until we know our width (see setFrame()) 8282 mRestartMarquee = true; 8283 } 8284 } 8285 } 8286 8287 // CursorControllers need a non-null mLayout 8288 if (mEditor != null) mEditor.prepareCursorControllers(); 8289 } 8290 8291 /** 8292 * @hide 8293 */ 8294 protected Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth, 8295 Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize, 8296 boolean useSaved) { 8297 Layout result = null; 8298 if (mText instanceof Spannable) { 8299 final DynamicLayout.Builder builder = DynamicLayout.Builder.obtain(mText, mTextPaint, 8300 wantWidth) 8301 .setDisplayText(mTransformed) 8302 .setAlignment(alignment) 8303 .setTextDirection(mTextDir) 8304 .setLineSpacing(mSpacingAdd, mSpacingMult) 8305 .setIncludePad(mIncludePad) 8306 .setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing) 8307 .setBreakStrategy(mBreakStrategy) 8308 .setHyphenationFrequency(mHyphenationFrequency) 8309 .setJustificationMode(mJustificationMode) 8310 .setEllipsize(getKeyListener() == null ? effectiveEllipsize : null) 8311 .setEllipsizedWidth(ellipsisWidth); 8312 result = builder.build(); 8313 } else { 8314 if (boring == UNKNOWN_BORING) { 8315 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 8316 if (boring != null) { 8317 mBoring = boring; 8318 } 8319 } 8320 8321 if (boring != null) { 8322 if (boring.width <= wantWidth 8323 && (effectiveEllipsize == null || boring.width <= ellipsisWidth)) { 8324 if (useSaved && mSavedLayout != null) { 8325 result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, 8326 wantWidth, alignment, mSpacingMult, mSpacingAdd, 8327 boring, mIncludePad); 8328 } else { 8329 result = BoringLayout.make(mTransformed, mTextPaint, 8330 wantWidth, alignment, mSpacingMult, mSpacingAdd, 8331 boring, mIncludePad); 8332 } 8333 8334 if (useSaved) { 8335 mSavedLayout = (BoringLayout) result; 8336 } 8337 } else if (shouldEllipsize && boring.width <= wantWidth) { 8338 if (useSaved && mSavedLayout != null) { 8339 result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, 8340 wantWidth, alignment, mSpacingMult, mSpacingAdd, 8341 boring, mIncludePad, effectiveEllipsize, 8342 ellipsisWidth); 8343 } else { 8344 result = BoringLayout.make(mTransformed, mTextPaint, 8345 wantWidth, alignment, mSpacingMult, mSpacingAdd, 8346 boring, mIncludePad, effectiveEllipsize, 8347 ellipsisWidth); 8348 } 8349 } 8350 } 8351 } 8352 if (result == null) { 8353 StaticLayout.Builder builder = StaticLayout.Builder.obtain(mTransformed, 8354 0, mTransformed.length(), mTextPaint, wantWidth) 8355 .setAlignment(alignment) 8356 .setTextDirection(mTextDir) 8357 .setLineSpacing(mSpacingAdd, mSpacingMult) 8358 .setIncludePad(mIncludePad) 8359 .setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing) 8360 .setBreakStrategy(mBreakStrategy) 8361 .setHyphenationFrequency(mHyphenationFrequency) 8362 .setJustificationMode(mJustificationMode) 8363 .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 8364 if (shouldEllipsize) { 8365 builder.setEllipsize(effectiveEllipsize) 8366 .setEllipsizedWidth(ellipsisWidth); 8367 } 8368 result = builder.build(); 8369 } 8370 return result; 8371 } 8372 8373 private boolean compressText(float width) { 8374 if (isHardwareAccelerated()) return false; 8375 8376 // Only compress the text if it hasn't been compressed by the previous pass 8377 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX 8378 && mTextPaint.getTextScaleX() == 1.0f) { 8379 final float textWidth = mLayout.getLineWidth(0); 8380 final float overflow = (textWidth + 1.0f - width) / width; 8381 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 8382 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 8383 post(new Runnable() { 8384 public void run() { 8385 requestLayout(); 8386 } 8387 }); 8388 return true; 8389 } 8390 } 8391 8392 return false; 8393 } 8394 8395 private static int desired(Layout layout) { 8396 int n = layout.getLineCount(); 8397 CharSequence text = layout.getText(); 8398 float max = 0; 8399 8400 // if any line was wrapped, we can't use it. 8401 // but it's ok for the last line not to have a newline 8402 8403 for (int i = 0; i < n - 1; i++) { 8404 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') { 8405 return -1; 8406 } 8407 } 8408 8409 for (int i = 0; i < n; i++) { 8410 max = Math.max(max, layout.getLineWidth(i)); 8411 } 8412 8413 return (int) Math.ceil(max); 8414 } 8415 8416 /** 8417 * Set whether the TextView includes extra top and bottom padding to make 8418 * room for accents that go above the normal ascent and descent. 8419 * The default is true. 8420 * 8421 * @see #getIncludeFontPadding() 8422 * 8423 * @attr ref android.R.styleable#TextView_includeFontPadding 8424 */ 8425 public void setIncludeFontPadding(boolean includepad) { 8426 if (mIncludePad != includepad) { 8427 mIncludePad = includepad; 8428 8429 if (mLayout != null) { 8430 nullLayouts(); 8431 requestLayout(); 8432 invalidate(); 8433 } 8434 } 8435 } 8436 8437 /** 8438 * Gets whether the TextView includes extra top and bottom padding to make 8439 * room for accents that go above the normal ascent and descent. 8440 * 8441 * @see #setIncludeFontPadding(boolean) 8442 * 8443 * @attr ref android.R.styleable#TextView_includeFontPadding 8444 */ 8445 public boolean getIncludeFontPadding() { 8446 return mIncludePad; 8447 } 8448 8449 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 8450 8451 @Override 8452 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 8453 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 8454 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 8455 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 8456 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 8457 8458 int width; 8459 int height; 8460 8461 BoringLayout.Metrics boring = UNKNOWN_BORING; 8462 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 8463 8464 if (mTextDir == null) { 8465 mTextDir = getTextDirectionHeuristic(); 8466 } 8467 8468 int des = -1; 8469 boolean fromexisting = false; 8470 final float widthLimit = (widthMode == MeasureSpec.AT_MOST) 8471 ? (float) widthSize : Float.MAX_VALUE; 8472 8473 if (widthMode == MeasureSpec.EXACTLY) { 8474 // Parent has told us how big to be. So be it. 8475 width = widthSize; 8476 } else { 8477 if (mLayout != null && mEllipsize == null) { 8478 des = desired(mLayout); 8479 } 8480 8481 if (des < 0) { 8482 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 8483 if (boring != null) { 8484 mBoring = boring; 8485 } 8486 } else { 8487 fromexisting = true; 8488 } 8489 8490 if (boring == null || boring == UNKNOWN_BORING) { 8491 if (des < 0) { 8492 des = (int) Math.ceil(Layout.getDesiredWidthWithLimit(mTransformed, 0, 8493 mTransformed.length(), mTextPaint, mTextDir, widthLimit)); 8494 } 8495 width = des; 8496 } else { 8497 width = boring.width; 8498 } 8499 8500 final Drawables dr = mDrawables; 8501 if (dr != null) { 8502 width = Math.max(width, dr.mDrawableWidthTop); 8503 width = Math.max(width, dr.mDrawableWidthBottom); 8504 } 8505 8506 if (mHint != null) { 8507 int hintDes = -1; 8508 int hintWidth; 8509 8510 if (mHintLayout != null && mEllipsize == null) { 8511 hintDes = desired(mHintLayout); 8512 } 8513 8514 if (hintDes < 0) { 8515 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, mHintBoring); 8516 if (hintBoring != null) { 8517 mHintBoring = hintBoring; 8518 } 8519 } 8520 8521 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 8522 if (hintDes < 0) { 8523 hintDes = (int) Math.ceil(Layout.getDesiredWidthWithLimit(mHint, 0, 8524 mHint.length(), mTextPaint, mTextDir, widthLimit)); 8525 } 8526 hintWidth = hintDes; 8527 } else { 8528 hintWidth = hintBoring.width; 8529 } 8530 8531 if (hintWidth > width) { 8532 width = hintWidth; 8533 } 8534 } 8535 8536 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 8537 8538 if (mMaxWidthMode == EMS) { 8539 width = Math.min(width, mMaxWidth * getLineHeight()); 8540 } else { 8541 width = Math.min(width, mMaxWidth); 8542 } 8543 8544 if (mMinWidthMode == EMS) { 8545 width = Math.max(width, mMinWidth * getLineHeight()); 8546 } else { 8547 width = Math.max(width, mMinWidth); 8548 } 8549 8550 // Check against our minimum width 8551 width = Math.max(width, getSuggestedMinimumWidth()); 8552 8553 if (widthMode == MeasureSpec.AT_MOST) { 8554 width = Math.min(widthSize, width); 8555 } 8556 } 8557 8558 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 8559 int unpaddedWidth = want; 8560 8561 if (mHorizontallyScrolling) want = VERY_WIDE; 8562 8563 int hintWant = want; 8564 int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth(); 8565 8566 if (mLayout == null) { 8567 makeNewLayout(want, hintWant, boring, hintBoring, 8568 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 8569 } else { 8570 final boolean layoutChanged = (mLayout.getWidth() != want) || (hintWidth != hintWant) 8571 || (mLayout.getEllipsizedWidth() 8572 != width - getCompoundPaddingLeft() - getCompoundPaddingRight()); 8573 8574 final boolean widthChanged = (mHint == null) && (mEllipsize == null) 8575 && (want > mLayout.getWidth()) 8576 && (mLayout instanceof BoringLayout 8577 || (fromexisting && des >= 0 && des <= want)); 8578 8579 final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum); 8580 8581 if (layoutChanged || maximumChanged) { 8582 if (!maximumChanged && widthChanged) { 8583 mLayout.increaseWidthTo(want); 8584 } else { 8585 makeNewLayout(want, hintWant, boring, hintBoring, 8586 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 8587 } 8588 } else { 8589 // Nothing has changed 8590 } 8591 } 8592 8593 if (heightMode == MeasureSpec.EXACTLY) { 8594 // Parent has told us how big to be. So be it. 8595 height = heightSize; 8596 mDesiredHeightAtMeasure = -1; 8597 } else { 8598 int desired = getDesiredHeight(); 8599 8600 height = desired; 8601 mDesiredHeightAtMeasure = desired; 8602 8603 if (heightMode == MeasureSpec.AT_MOST) { 8604 height = Math.min(desired, heightSize); 8605 } 8606 } 8607 8608 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 8609 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 8610 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 8611 } 8612 8613 /* 8614 * We didn't let makeNewLayout() register to bring the cursor into view, 8615 * so do it here if there is any possibility that it is needed. 8616 */ 8617 if (mMovement != null 8618 || mLayout.getWidth() > unpaddedWidth 8619 || mLayout.getHeight() > unpaddedHeight) { 8620 registerForPreDraw(); 8621 } else { 8622 scrollTo(0, 0); 8623 } 8624 8625 setMeasuredDimension(width, height); 8626 } 8627 8628 /** 8629 * Automatically computes and sets the text size. 8630 */ 8631 private void autoSizeText() { 8632 if (!isAutoSizeEnabled()) { 8633 return; 8634 } 8635 8636 if (mNeedsAutoSizeText) { 8637 if (getMeasuredWidth() <= 0 || getMeasuredHeight() <= 0) { 8638 return; 8639 } 8640 8641 final int availableWidth = mHorizontallyScrolling 8642 ? VERY_WIDE 8643 : getMeasuredWidth() - getTotalPaddingLeft() - getTotalPaddingRight(); 8644 final int availableHeight = getMeasuredHeight() - getExtendedPaddingBottom() 8645 - getExtendedPaddingTop(); 8646 8647 if (availableWidth <= 0 || availableHeight <= 0) { 8648 return; 8649 } 8650 8651 synchronized (TEMP_RECTF) { 8652 TEMP_RECTF.setEmpty(); 8653 TEMP_RECTF.right = availableWidth; 8654 TEMP_RECTF.bottom = availableHeight; 8655 final float optimalTextSize = findLargestTextSizeWhichFits(TEMP_RECTF); 8656 8657 if (optimalTextSize != getTextSize()) { 8658 setTextSizeInternal(TypedValue.COMPLEX_UNIT_PX, optimalTextSize, 8659 false /* shouldRequestLayout */); 8660 8661 makeNewLayout(availableWidth, 0 /* hintWidth */, UNKNOWN_BORING, UNKNOWN_BORING, 8662 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 8663 false /* bringIntoView */); 8664 } 8665 } 8666 } 8667 // Always try to auto-size if enabled. Functions that do not want to trigger auto-sizing 8668 // after the next layout pass should set this to false. 8669 mNeedsAutoSizeText = true; 8670 } 8671 8672 /** 8673 * Performs a binary search to find the largest text size that will still fit within the size 8674 * available to this view. 8675 */ 8676 private int findLargestTextSizeWhichFits(RectF availableSpace) { 8677 final int sizesCount = mAutoSizeTextSizesInPx.length; 8678 if (sizesCount == 0) { 8679 throw new IllegalStateException("No available text sizes to choose from."); 8680 } 8681 8682 int bestSizeIndex = 0; 8683 int lowIndex = bestSizeIndex + 1; 8684 int highIndex = sizesCount - 1; 8685 int sizeToTryIndex; 8686 while (lowIndex <= highIndex) { 8687 sizeToTryIndex = (lowIndex + highIndex) / 2; 8688 if (suggestedSizeFitsInSpace(mAutoSizeTextSizesInPx[sizeToTryIndex], availableSpace)) { 8689 bestSizeIndex = lowIndex; 8690 lowIndex = sizeToTryIndex + 1; 8691 } else { 8692 highIndex = sizeToTryIndex - 1; 8693 bestSizeIndex = highIndex; 8694 } 8695 } 8696 8697 return mAutoSizeTextSizesInPx[bestSizeIndex]; 8698 } 8699 8700 private boolean suggestedSizeFitsInSpace(int suggestedSizeInPx, RectF availableSpace) { 8701 final CharSequence text = mTransformed != null 8702 ? mTransformed 8703 : getText(); 8704 final int maxLines = getMaxLines(); 8705 if (mTempTextPaint == null) { 8706 mTempTextPaint = new TextPaint(); 8707 } else { 8708 mTempTextPaint.reset(); 8709 } 8710 mTempTextPaint.set(getPaint()); 8711 mTempTextPaint.setTextSize(suggestedSizeInPx); 8712 8713 final StaticLayout.Builder layoutBuilder = StaticLayout.Builder.obtain( 8714 text, 0, text.length(), mTempTextPaint, Math.round(availableSpace.right)); 8715 8716 layoutBuilder.setAlignment(getLayoutAlignment()) 8717 .setLineSpacing(getLineSpacingExtra(), getLineSpacingMultiplier()) 8718 .setIncludePad(getIncludeFontPadding()) 8719 .setUseLineSpacingFromFallbacks(mUseFallbackLineSpacing) 8720 .setBreakStrategy(getBreakStrategy()) 8721 .setHyphenationFrequency(getHyphenationFrequency()) 8722 .setJustificationMode(getJustificationMode()) 8723 .setMaxLines(mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE) 8724 .setTextDirection(getTextDirectionHeuristic()); 8725 8726 final StaticLayout layout = layoutBuilder.build(); 8727 8728 // Lines overflow. 8729 if (maxLines != -1 && layout.getLineCount() > maxLines) { 8730 return false; 8731 } 8732 8733 // Height overflow. 8734 if (layout.getHeight() > availableSpace.bottom) { 8735 return false; 8736 } 8737 8738 return true; 8739 } 8740 8741 private int getDesiredHeight() { 8742 return Math.max( 8743 getDesiredHeight(mLayout, true), 8744 getDesiredHeight(mHintLayout, mEllipsize != null)); 8745 } 8746 8747 private int getDesiredHeight(Layout layout, boolean cap) { 8748 if (layout == null) { 8749 return 0; 8750 } 8751 8752 /* 8753 * Don't cap the hint to a certain number of lines. 8754 * (Do cap it, though, if we have a maximum pixel height.) 8755 */ 8756 int desired = layout.getHeight(cap); 8757 8758 final Drawables dr = mDrawables; 8759 if (dr != null) { 8760 desired = Math.max(desired, dr.mDrawableHeightLeft); 8761 desired = Math.max(desired, dr.mDrawableHeightRight); 8762 } 8763 8764 int linecount = layout.getLineCount(); 8765 final int padding = getCompoundPaddingTop() + getCompoundPaddingBottom(); 8766 desired += padding; 8767 8768 if (mMaxMode != LINES) { 8769 desired = Math.min(desired, mMaximum); 8770 } else if (cap && linecount > mMaximum && (layout instanceof DynamicLayout 8771 || layout instanceof BoringLayout)) { 8772 desired = layout.getLineTop(mMaximum); 8773 8774 if (dr != null) { 8775 desired = Math.max(desired, dr.mDrawableHeightLeft); 8776 desired = Math.max(desired, dr.mDrawableHeightRight); 8777 } 8778 8779 desired += padding; 8780 linecount = mMaximum; 8781 } 8782 8783 if (mMinMode == LINES) { 8784 if (linecount < mMinimum) { 8785 desired += getLineHeight() * (mMinimum - linecount); 8786 } 8787 } else { 8788 desired = Math.max(desired, mMinimum); 8789 } 8790 8791 // Check against our minimum height 8792 desired = Math.max(desired, getSuggestedMinimumHeight()); 8793 8794 return desired; 8795 } 8796 8797 /** 8798 * Check whether a change to the existing text layout requires a 8799 * new view layout. 8800 */ 8801 private void checkForResize() { 8802 boolean sizeChanged = false; 8803 8804 if (mLayout != null) { 8805 // Check if our width changed 8806 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 8807 sizeChanged = true; 8808 invalidate(); 8809 } 8810 8811 // Check if our height changed 8812 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 8813 int desiredHeight = getDesiredHeight(); 8814 8815 if (desiredHeight != this.getHeight()) { 8816 sizeChanged = true; 8817 } 8818 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 8819 if (mDesiredHeightAtMeasure >= 0) { 8820 int desiredHeight = getDesiredHeight(); 8821 8822 if (desiredHeight != mDesiredHeightAtMeasure) { 8823 sizeChanged = true; 8824 } 8825 } 8826 } 8827 } 8828 8829 if (sizeChanged) { 8830 requestLayout(); 8831 // caller will have already invalidated 8832 } 8833 } 8834 8835 /** 8836 * Check whether entirely new text requires a new view layout 8837 * or merely a new text layout. 8838 */ 8839 private void checkForRelayout() { 8840 // If we have a fixed width, we can just swap in a new text layout 8841 // if the text height stays the same or if the view height is fixed. 8842 8843 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT 8844 || (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) 8845 && (mHint == null || mHintLayout != null) 8846 && (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 8847 // Static width, so try making a new text layout. 8848 8849 int oldht = mLayout.getHeight(); 8850 int want = mLayout.getWidth(); 8851 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 8852 8853 /* 8854 * No need to bring the text into view, since the size is not 8855 * changing (unless we do the requestLayout(), in which case it 8856 * will happen at measure). 8857 */ 8858 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 8859 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 8860 false); 8861 8862 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 8863 // In a fixed-height view, so use our new text layout. 8864 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT 8865 && mLayoutParams.height != LayoutParams.MATCH_PARENT) { 8866 autoSizeText(); 8867 invalidate(); 8868 return; 8869 } 8870 8871 // Dynamic height, but height has stayed the same, 8872 // so use our new text layout. 8873 if (mLayout.getHeight() == oldht 8874 && (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 8875 autoSizeText(); 8876 invalidate(); 8877 return; 8878 } 8879 } 8880 8881 // We lose: the height has changed and we have a dynamic height. 8882 // Request a new view layout using our new text layout. 8883 requestLayout(); 8884 invalidate(); 8885 } else { 8886 // Dynamic width, so we have no choice but to request a new 8887 // view layout with a new text layout. 8888 nullLayouts(); 8889 requestLayout(); 8890 invalidate(); 8891 } 8892 } 8893 8894 @Override 8895 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 8896 super.onLayout(changed, left, top, right, bottom); 8897 if (mDeferScroll >= 0) { 8898 int curs = mDeferScroll; 8899 mDeferScroll = -1; 8900 bringPointIntoView(Math.min(curs, mText.length())); 8901 } 8902 // Call auto-size after the width and height have been calculated. 8903 autoSizeText(); 8904 } 8905 8906 private boolean isShowingHint() { 8907 return TextUtils.isEmpty(mText) && !TextUtils.isEmpty(mHint); 8908 } 8909 8910 /** 8911 * Returns true if anything changed. 8912 */ 8913 private boolean bringTextIntoView() { 8914 Layout layout = isShowingHint() ? mHintLayout : mLayout; 8915 int line = 0; 8916 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 8917 line = layout.getLineCount() - 1; 8918 } 8919 8920 Layout.Alignment a = layout.getParagraphAlignment(line); 8921 int dir = layout.getParagraphDirection(line); 8922 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 8923 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 8924 int ht = layout.getHeight(); 8925 8926 int scrollx, scrolly; 8927 8928 // Convert to left, center, or right alignment. 8929 if (a == Layout.Alignment.ALIGN_NORMAL) { 8930 a = dir == Layout.DIR_LEFT_TO_RIGHT 8931 ? Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; 8932 } else if (a == Layout.Alignment.ALIGN_OPPOSITE) { 8933 a = dir == Layout.DIR_LEFT_TO_RIGHT 8934 ? Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; 8935 } 8936 8937 if (a == Layout.Alignment.ALIGN_CENTER) { 8938 /* 8939 * Keep centered if possible, or, if it is too wide to fit, 8940 * keep leading edge in view. 8941 */ 8942 8943 int left = (int) Math.floor(layout.getLineLeft(line)); 8944 int right = (int) Math.ceil(layout.getLineRight(line)); 8945 8946 if (right - left < hspace) { 8947 scrollx = (right + left) / 2 - hspace / 2; 8948 } else { 8949 if (dir < 0) { 8950 scrollx = right - hspace; 8951 } else { 8952 scrollx = left; 8953 } 8954 } 8955 } else if (a == Layout.Alignment.ALIGN_RIGHT) { 8956 int right = (int) Math.ceil(layout.getLineRight(line)); 8957 scrollx = right - hspace; 8958 } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) 8959 scrollx = (int) Math.floor(layout.getLineLeft(line)); 8960 } 8961 8962 if (ht < vspace) { 8963 scrolly = 0; 8964 } else { 8965 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 8966 scrolly = ht - vspace; 8967 } else { 8968 scrolly = 0; 8969 } 8970 } 8971 8972 if (scrollx != mScrollX || scrolly != mScrollY) { 8973 scrollTo(scrollx, scrolly); 8974 return true; 8975 } else { 8976 return false; 8977 } 8978 } 8979 8980 /** 8981 * Move the point, specified by the offset, into the view if it is needed. 8982 * This has to be called after layout. Returns true if anything changed. 8983 */ 8984 public boolean bringPointIntoView(int offset) { 8985 if (isLayoutRequested()) { 8986 mDeferScroll = offset; 8987 return false; 8988 } 8989 boolean changed = false; 8990 8991 Layout layout = isShowingHint() ? mHintLayout : mLayout; 8992 8993 if (layout == null) return changed; 8994 8995 int line = layout.getLineForOffset(offset); 8996 8997 int grav; 8998 8999 switch (layout.getParagraphAlignment(line)) { 9000 case ALIGN_LEFT: 9001 grav = 1; 9002 break; 9003 case ALIGN_RIGHT: 9004 grav = -1; 9005 break; 9006 case ALIGN_NORMAL: 9007 grav = layout.getParagraphDirection(line); 9008 break; 9009 case ALIGN_OPPOSITE: 9010 grav = -layout.getParagraphDirection(line); 9011 break; 9012 case ALIGN_CENTER: 9013 default: 9014 grav = 0; 9015 break; 9016 } 9017 9018 // We only want to clamp the cursor to fit within the layout width 9019 // in left-to-right modes, because in a right to left alignment, 9020 // we want to scroll to keep the line-right on the screen, as other 9021 // lines are likely to have text flush with the right margin, which 9022 // we want to keep visible. 9023 // A better long-term solution would probably be to measure both 9024 // the full line and a blank-trimmed version, and, for example, use 9025 // the latter measurement for centering and right alignment, but for 9026 // the time being we only implement the cursor clamping in left to 9027 // right where it is most likely to be annoying. 9028 final boolean clamped = grav > 0; 9029 // FIXME: Is it okay to truncate this, or should we round? 9030 final int x = (int) layout.getPrimaryHorizontal(offset, clamped); 9031 final int top = layout.getLineTop(line); 9032 final int bottom = layout.getLineTop(line + 1); 9033 9034 int left = (int) Math.floor(layout.getLineLeft(line)); 9035 int right = (int) Math.ceil(layout.getLineRight(line)); 9036 int ht = layout.getHeight(); 9037 9038 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 9039 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 9040 if (!mHorizontallyScrolling && right - left > hspace && right > x) { 9041 // If cursor has been clamped, make sure we don't scroll. 9042 right = Math.max(x, left + hspace); 9043 } 9044 9045 int hslack = (bottom - top) / 2; 9046 int vslack = hslack; 9047 9048 if (vslack > vspace / 4) { 9049 vslack = vspace / 4; 9050 } 9051 if (hslack > hspace / 4) { 9052 hslack = hspace / 4; 9053 } 9054 9055 int hs = mScrollX; 9056 int vs = mScrollY; 9057 9058 if (top - vs < vslack) { 9059 vs = top - vslack; 9060 } 9061 if (bottom - vs > vspace - vslack) { 9062 vs = bottom - (vspace - vslack); 9063 } 9064 if (ht - vs < vspace) { 9065 vs = ht - vspace; 9066 } 9067 if (0 - vs > 0) { 9068 vs = 0; 9069 } 9070 9071 if (grav != 0) { 9072 if (x - hs < hslack) { 9073 hs = x - hslack; 9074 } 9075 if (x - hs > hspace - hslack) { 9076 hs = x - (hspace - hslack); 9077 } 9078 } 9079 9080 if (grav < 0) { 9081 if (left - hs > 0) { 9082 hs = left; 9083 } 9084 if (right - hs < hspace) { 9085 hs = right - hspace; 9086 } 9087 } else if (grav > 0) { 9088 if (right - hs < hspace) { 9089 hs = right - hspace; 9090 } 9091 if (left - hs > 0) { 9092 hs = left; 9093 } 9094 } else /* grav == 0 */ { 9095 if (right - left <= hspace) { 9096 /* 9097 * If the entire text fits, center it exactly. 9098 */ 9099 hs = left - (hspace - (right - left)) / 2; 9100 } else if (x > right - hslack) { 9101 /* 9102 * If we are near the right edge, keep the right edge 9103 * at the edge of the view. 9104 */ 9105 hs = right - hspace; 9106 } else if (x < left + hslack) { 9107 /* 9108 * If we are near the left edge, keep the left edge 9109 * at the edge of the view. 9110 */ 9111 hs = left; 9112 } else if (left > hs) { 9113 /* 9114 * Is there whitespace visible at the left? Fix it if so. 9115 */ 9116 hs = left; 9117 } else if (right < hs + hspace) { 9118 /* 9119 * Is there whitespace visible at the right? Fix it if so. 9120 */ 9121 hs = right - hspace; 9122 } else { 9123 /* 9124 * Otherwise, float as needed. 9125 */ 9126 if (x - hs < hslack) { 9127 hs = x - hslack; 9128 } 9129 if (x - hs > hspace - hslack) { 9130 hs = x - (hspace - hslack); 9131 } 9132 } 9133 } 9134 9135 if (hs != mScrollX || vs != mScrollY) { 9136 if (mScroller == null) { 9137 scrollTo(hs, vs); 9138 } else { 9139 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 9140 int dx = hs - mScrollX; 9141 int dy = vs - mScrollY; 9142 9143 if (duration > ANIMATED_SCROLL_GAP) { 9144 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 9145 awakenScrollBars(mScroller.getDuration()); 9146 invalidate(); 9147 } else { 9148 if (!mScroller.isFinished()) { 9149 mScroller.abortAnimation(); 9150 } 9151 9152 scrollBy(dx, dy); 9153 } 9154 9155 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 9156 } 9157 9158 changed = true; 9159 } 9160 9161 if (isFocused()) { 9162 // This offsets because getInterestingRect() is in terms of viewport coordinates, but 9163 // requestRectangleOnScreen() is in terms of content coordinates. 9164 9165 // The offsets here are to ensure the rectangle we are using is 9166 // within our view bounds, in case the cursor is on the far left 9167 // or right. If it isn't withing the bounds, then this request 9168 // will be ignored. 9169 if (mTempRect == null) mTempRect = new Rect(); 9170 mTempRect.set(x - 2, top, x + 2, bottom); 9171 getInterestingRect(mTempRect, line); 9172 mTempRect.offset(mScrollX, mScrollY); 9173 9174 if (requestRectangleOnScreen(mTempRect)) { 9175 changed = true; 9176 } 9177 } 9178 9179 return changed; 9180 } 9181 9182 /** 9183 * Move the cursor, if needed, so that it is at an offset that is visible 9184 * to the user. This will not move the cursor if it represents more than 9185 * one character (a selection range). This will only work if the 9186 * TextView contains spannable text; otherwise it will do nothing. 9187 * 9188 * @return True if the cursor was actually moved, false otherwise. 9189 */ 9190 public boolean moveCursorToVisibleOffset() { 9191 if (!(mText instanceof Spannable)) { 9192 return false; 9193 } 9194 int start = getSelectionStart(); 9195 int end = getSelectionEnd(); 9196 if (start != end) { 9197 return false; 9198 } 9199 9200 // First: make sure the line is visible on screen: 9201 9202 int line = mLayout.getLineForOffset(start); 9203 9204 final int top = mLayout.getLineTop(line); 9205 final int bottom = mLayout.getLineTop(line + 1); 9206 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 9207 int vslack = (bottom - top) / 2; 9208 if (vslack > vspace / 4) { 9209 vslack = vspace / 4; 9210 } 9211 final int vs = mScrollY; 9212 9213 if (top < (vs + vslack)) { 9214 line = mLayout.getLineForVertical(vs + vslack + (bottom - top)); 9215 } else if (bottom > (vspace + vs - vslack)) { 9216 line = mLayout.getLineForVertical(vspace + vs - vslack - (bottom - top)); 9217 } 9218 9219 // Next: make sure the character is visible on screen: 9220 9221 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 9222 final int hs = mScrollX; 9223 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 9224 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace + hs); 9225 9226 // line might contain bidirectional text 9227 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 9228 final int highChar = leftChar > rightChar ? leftChar : rightChar; 9229 9230 int newStart = start; 9231 if (newStart < lowChar) { 9232 newStart = lowChar; 9233 } else if (newStart > highChar) { 9234 newStart = highChar; 9235 } 9236 9237 if (newStart != start) { 9238 Selection.setSelection((Spannable) mText, newStart); 9239 return true; 9240 } 9241 9242 return false; 9243 } 9244 9245 @Override 9246 public void computeScroll() { 9247 if (mScroller != null) { 9248 if (mScroller.computeScrollOffset()) { 9249 mScrollX = mScroller.getCurrX(); 9250 mScrollY = mScroller.getCurrY(); 9251 invalidateParentCaches(); 9252 postInvalidate(); // So we draw again 9253 } 9254 } 9255 } 9256 9257 private void getInterestingRect(Rect r, int line) { 9258 convertFromViewportToContentCoordinates(r); 9259 9260 // Rectangle can can be expanded on first and last line to take 9261 // padding into account. 9262 // TODO Take left/right padding into account too? 9263 if (line == 0) r.top -= getExtendedPaddingTop(); 9264 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 9265 } 9266 9267 private void convertFromViewportToContentCoordinates(Rect r) { 9268 final int horizontalOffset = viewportToContentHorizontalOffset(); 9269 r.left += horizontalOffset; 9270 r.right += horizontalOffset; 9271 9272 final int verticalOffset = viewportToContentVerticalOffset(); 9273 r.top += verticalOffset; 9274 r.bottom += verticalOffset; 9275 } 9276 9277 int viewportToContentHorizontalOffset() { 9278 return getCompoundPaddingLeft() - mScrollX; 9279 } 9280 9281 int viewportToContentVerticalOffset() { 9282 int offset = getExtendedPaddingTop() - mScrollY; 9283 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 9284 offset += getVerticalOffset(false); 9285 } 9286 return offset; 9287 } 9288 9289 @Override 9290 public void debug(int depth) { 9291 super.debug(depth); 9292 9293 String output = debugIndent(depth); 9294 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 9295 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 9296 + "} "; 9297 9298 if (mText != null) { 9299 9300 output += "mText=\"" + mText + "\" "; 9301 if (mLayout != null) { 9302 output += "mLayout width=" + mLayout.getWidth() 9303 + " height=" + mLayout.getHeight(); 9304 } 9305 } else { 9306 output += "mText=NULL"; 9307 } 9308 Log.d(VIEW_LOG_TAG, output); 9309 } 9310 9311 /** 9312 * Convenience for {@link Selection#getSelectionStart}. 9313 */ 9314 @ViewDebug.ExportedProperty(category = "text") 9315 public int getSelectionStart() { 9316 return Selection.getSelectionStart(getText()); 9317 } 9318 9319 /** 9320 * Convenience for {@link Selection#getSelectionEnd}. 9321 */ 9322 @ViewDebug.ExportedProperty(category = "text") 9323 public int getSelectionEnd() { 9324 return Selection.getSelectionEnd(getText()); 9325 } 9326 9327 /** 9328 * Return true iff there is a selection inside this text view. 9329 */ 9330 public boolean hasSelection() { 9331 final int selectionStart = getSelectionStart(); 9332 final int selectionEnd = getSelectionEnd(); 9333 9334 return selectionStart >= 0 && selectionStart != selectionEnd; 9335 } 9336 9337 String getSelectedText() { 9338 if (!hasSelection()) { 9339 return null; 9340 } 9341 9342 final int start = getSelectionStart(); 9343 final int end = getSelectionEnd(); 9344 return String.valueOf( 9345 start > end ? mText.subSequence(end, start) : mText.subSequence(start, end)); 9346 } 9347 9348 /** 9349 * Sets the properties of this field (lines, horizontally scrolling, 9350 * transformation method) to be for a single-line input. 9351 * 9352 * @attr ref android.R.styleable#TextView_singleLine 9353 */ 9354 public void setSingleLine() { 9355 setSingleLine(true); 9356 } 9357 9358 /** 9359 * Sets the properties of this field to transform input to ALL CAPS 9360 * display. This may use a "small caps" formatting if available. 9361 * This setting will be ignored if this field is editable or selectable. 9362 * 9363 * This call replaces the current transformation method. Disabling this 9364 * will not necessarily restore the previous behavior from before this 9365 * was enabled. 9366 * 9367 * @see #setTransformationMethod(TransformationMethod) 9368 * @attr ref android.R.styleable#TextView_textAllCaps 9369 */ 9370 public void setAllCaps(boolean allCaps) { 9371 if (allCaps) { 9372 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 9373 } else { 9374 setTransformationMethod(null); 9375 } 9376 } 9377 9378 /** 9379 * 9380 * Checks whether the transformation method applied to this TextView is set to ALL CAPS. 9381 * @return Whether the current transformation method is for ALL CAPS. 9382 * 9383 * @see #setAllCaps(boolean) 9384 * @see #setTransformationMethod(TransformationMethod) 9385 */ 9386 public boolean isAllCaps() { 9387 final TransformationMethod method = getTransformationMethod(); 9388 return method != null && method instanceof AllCapsTransformationMethod; 9389 } 9390 9391 /** 9392 * If true, sets the properties of this field (number of lines, horizontally scrolling, 9393 * transformation method) to be for a single-line input; if false, restores these to the default 9394 * conditions. 9395 * 9396 * Note that the default conditions are not necessarily those that were in effect prior this 9397 * method, and you may want to reset these properties to your custom values. 9398 * 9399 * @attr ref android.R.styleable#TextView_singleLine 9400 */ 9401 @android.view.RemotableViewMethod 9402 public void setSingleLine(boolean singleLine) { 9403 // Could be used, but may break backward compatibility. 9404 // if (mSingleLine == singleLine) return; 9405 setInputTypeSingleLine(singleLine); 9406 applySingleLine(singleLine, true, true); 9407 } 9408 9409 /** 9410 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 9411 * @param singleLine 9412 */ 9413 private void setInputTypeSingleLine(boolean singleLine) { 9414 if (mEditor != null 9415 && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) 9416 == EditorInfo.TYPE_CLASS_TEXT) { 9417 if (singleLine) { 9418 mEditor.mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 9419 } else { 9420 mEditor.mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 9421 } 9422 } 9423 } 9424 9425 private void applySingleLine(boolean singleLine, boolean applyTransformation, 9426 boolean changeMaxLines) { 9427 mSingleLine = singleLine; 9428 if (singleLine) { 9429 setLines(1); 9430 setHorizontallyScrolling(true); 9431 if (applyTransformation) { 9432 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 9433 } 9434 } else { 9435 if (changeMaxLines) { 9436 setMaxLines(Integer.MAX_VALUE); 9437 } 9438 setHorizontallyScrolling(false); 9439 if (applyTransformation) { 9440 setTransformationMethod(null); 9441 } 9442 } 9443 } 9444 9445 /** 9446 * Causes words in the text that are longer than the view's width 9447 * to be ellipsized instead of broken in the middle. You may also 9448 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 9449 * to constrain the text to a single line. Use <code>null</code> 9450 * to turn off ellipsizing. 9451 * 9452 * If {@link #setMaxLines} has been used to set two or more lines, 9453 * only {@link android.text.TextUtils.TruncateAt#END} and 9454 * {@link android.text.TextUtils.TruncateAt#MARQUEE} are supported 9455 * (other ellipsizing types will not do anything). 9456 * 9457 * @attr ref android.R.styleable#TextView_ellipsize 9458 */ 9459 public void setEllipsize(TextUtils.TruncateAt where) { 9460 // TruncateAt is an enum. != comparison is ok between these singleton objects. 9461 if (mEllipsize != where) { 9462 mEllipsize = where; 9463 9464 if (mLayout != null) { 9465 nullLayouts(); 9466 requestLayout(); 9467 invalidate(); 9468 } 9469 } 9470 } 9471 9472 /** 9473 * Sets how many times to repeat the marquee animation. Only applied if the 9474 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 9475 * 9476 * @see #getMarqueeRepeatLimit() 9477 * 9478 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 9479 */ 9480 public void setMarqueeRepeatLimit(int marqueeLimit) { 9481 mMarqueeRepeatLimit = marqueeLimit; 9482 } 9483 9484 /** 9485 * Gets the number of times the marquee animation is repeated. Only meaningful if the 9486 * TextView has marquee enabled. 9487 * 9488 * @return the number of times the marquee animation is repeated. -1 if the animation 9489 * repeats indefinitely 9490 * 9491 * @see #setMarqueeRepeatLimit(int) 9492 * 9493 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 9494 */ 9495 public int getMarqueeRepeatLimit() { 9496 return mMarqueeRepeatLimit; 9497 } 9498 9499 /** 9500 * Returns where, if anywhere, words that are longer than the view 9501 * is wide should be ellipsized. 9502 */ 9503 @ViewDebug.ExportedProperty 9504 public TextUtils.TruncateAt getEllipsize() { 9505 return mEllipsize; 9506 } 9507 9508 /** 9509 * Set the TextView so that when it takes focus, all the text is 9510 * selected. 9511 * 9512 * @attr ref android.R.styleable#TextView_selectAllOnFocus 9513 */ 9514 @android.view.RemotableViewMethod 9515 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 9516 createEditorIfNeeded(); 9517 mEditor.mSelectAllOnFocus = selectAllOnFocus; 9518 9519 if (selectAllOnFocus && !(mText instanceof Spannable)) { 9520 setText(mText, BufferType.SPANNABLE); 9521 } 9522 } 9523 9524 /** 9525 * Set whether the cursor is visible. The default is true. Note that this property only 9526 * makes sense for editable TextView. 9527 * 9528 * @see #isCursorVisible() 9529 * 9530 * @attr ref android.R.styleable#TextView_cursorVisible 9531 */ 9532 @android.view.RemotableViewMethod 9533 public void setCursorVisible(boolean visible) { 9534 if (visible && mEditor == null) return; // visible is the default value with no edit data 9535 createEditorIfNeeded(); 9536 if (mEditor.mCursorVisible != visible) { 9537 mEditor.mCursorVisible = visible; 9538 invalidate(); 9539 9540 mEditor.makeBlink(); 9541 9542 // InsertionPointCursorController depends on mCursorVisible 9543 mEditor.prepareCursorControllers(); 9544 } 9545 } 9546 9547 /** 9548 * @return whether or not the cursor is visible (assuming this TextView is editable) 9549 * 9550 * @see #setCursorVisible(boolean) 9551 * 9552 * @attr ref android.R.styleable#TextView_cursorVisible 9553 */ 9554 public boolean isCursorVisible() { 9555 // true is the default value 9556 return mEditor == null ? true : mEditor.mCursorVisible; 9557 } 9558 9559 private boolean canMarquee() { 9560 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 9561 return width > 0 && (mLayout.getLineWidth(0) > width 9562 || (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null 9563 && mSavedMarqueeModeLayout.getLineWidth(0) > width)); 9564 } 9565 9566 private void startMarquee() { 9567 // Do not ellipsize EditText 9568 if (getKeyListener() != null) return; 9569 9570 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 9571 return; 9572 } 9573 9574 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) 9575 && getLineCount() == 1 && canMarquee()) { 9576 9577 if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 9578 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE; 9579 final Layout tmp = mLayout; 9580 mLayout = mSavedMarqueeModeLayout; 9581 mSavedMarqueeModeLayout = tmp; 9582 setHorizontalFadingEdgeEnabled(true); 9583 requestLayout(); 9584 invalidate(); 9585 } 9586 9587 if (mMarquee == null) mMarquee = new Marquee(this); 9588 mMarquee.start(mMarqueeRepeatLimit); 9589 } 9590 } 9591 9592 private void stopMarquee() { 9593 if (mMarquee != null && !mMarquee.isStopped()) { 9594 mMarquee.stop(); 9595 } 9596 9597 if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) { 9598 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 9599 final Layout tmp = mSavedMarqueeModeLayout; 9600 mSavedMarqueeModeLayout = mLayout; 9601 mLayout = tmp; 9602 setHorizontalFadingEdgeEnabled(false); 9603 requestLayout(); 9604 invalidate(); 9605 } 9606 } 9607 9608 private void startStopMarquee(boolean start) { 9609 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 9610 if (start) { 9611 startMarquee(); 9612 } else { 9613 stopMarquee(); 9614 } 9615 } 9616 } 9617 9618 /** 9619 * This method is called when the text is changed, in case any subclasses 9620 * would like to know. 9621 * 9622 * Within <code>text</code>, the <code>lengthAfter</code> characters 9623 * beginning at <code>start</code> have just replaced old text that had 9624 * length <code>lengthBefore</code>. It is an error to attempt to make 9625 * changes to <code>text</code> from this callback. 9626 * 9627 * @param text The text the TextView is displaying 9628 * @param start The offset of the start of the range of the text that was 9629 * modified 9630 * @param lengthBefore The length of the former text that has been replaced 9631 * @param lengthAfter The length of the replacement modified text 9632 */ 9633 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 9634 // intentionally empty, template pattern method can be overridden by subclasses 9635 } 9636 9637 /** 9638 * This method is called when the selection has changed, in case any 9639 * subclasses would like to know. 9640 * 9641 * @param selStart The new selection start location. 9642 * @param selEnd The new selection end location. 9643 */ 9644 protected void onSelectionChanged(int selStart, int selEnd) { 9645 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 9646 } 9647 9648 /** 9649 * Adds a TextWatcher to the list of those whose methods are called 9650 * whenever this TextView's text changes. 9651 * <p> 9652 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 9653 * not called after {@link #setText} calls. Now, doing {@link #setText} 9654 * if there are any text changed listeners forces the buffer type to 9655 * Editable if it would not otherwise be and does call this method. 9656 */ 9657 public void addTextChangedListener(TextWatcher watcher) { 9658 if (mListeners == null) { 9659 mListeners = new ArrayList<TextWatcher>(); 9660 } 9661 9662 mListeners.add(watcher); 9663 } 9664 9665 /** 9666 * Removes the specified TextWatcher from the list of those whose 9667 * methods are called 9668 * whenever this TextView's text changes. 9669 */ 9670 public void removeTextChangedListener(TextWatcher watcher) { 9671 if (mListeners != null) { 9672 int i = mListeners.indexOf(watcher); 9673 9674 if (i >= 0) { 9675 mListeners.remove(i); 9676 } 9677 } 9678 } 9679 9680 private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) { 9681 if (mListeners != null) { 9682 final ArrayList<TextWatcher> list = mListeners; 9683 final int count = list.size(); 9684 for (int i = 0; i < count; i++) { 9685 list.get(i).beforeTextChanged(text, start, before, after); 9686 } 9687 } 9688 9689 // The spans that are inside or intersect the modified region no longer make sense 9690 removeIntersectingNonAdjacentSpans(start, start + before, SpellCheckSpan.class); 9691 removeIntersectingNonAdjacentSpans(start, start + before, SuggestionSpan.class); 9692 } 9693 9694 // Removes all spans that are inside or actually overlap the start..end range 9695 private <T> void removeIntersectingNonAdjacentSpans(int start, int end, Class<T> type) { 9696 if (!(mText instanceof Editable)) return; 9697 Editable text = (Editable) mText; 9698 9699 T[] spans = text.getSpans(start, end, type); 9700 final int length = spans.length; 9701 for (int i = 0; i < length; i++) { 9702 final int spanStart = text.getSpanStart(spans[i]); 9703 final int spanEnd = text.getSpanEnd(spans[i]); 9704 if (spanEnd == start || spanStart == end) break; 9705 text.removeSpan(spans[i]); 9706 } 9707 } 9708 9709 void removeAdjacentSuggestionSpans(final int pos) { 9710 if (!(mText instanceof Editable)) return; 9711 final Editable text = (Editable) mText; 9712 9713 final SuggestionSpan[] spans = text.getSpans(pos, pos, SuggestionSpan.class); 9714 final int length = spans.length; 9715 for (int i = 0; i < length; i++) { 9716 final int spanStart = text.getSpanStart(spans[i]); 9717 final int spanEnd = text.getSpanEnd(spans[i]); 9718 if (spanEnd == pos || spanStart == pos) { 9719 if (SpellChecker.haveWordBoundariesChanged(text, pos, pos, spanStart, spanEnd)) { 9720 text.removeSpan(spans[i]); 9721 } 9722 } 9723 } 9724 } 9725 9726 /** 9727 * Not private so it can be called from an inner class without going 9728 * through a thunk. 9729 */ 9730 void sendOnTextChanged(CharSequence text, int start, int before, int after) { 9731 if (mListeners != null) { 9732 final ArrayList<TextWatcher> list = mListeners; 9733 final int count = list.size(); 9734 for (int i = 0; i < count; i++) { 9735 list.get(i).onTextChanged(text, start, before, after); 9736 } 9737 } 9738 9739 if (mEditor != null) mEditor.sendOnTextChanged(start, before, after); 9740 } 9741 9742 /** 9743 * Not private so it can be called from an inner class without going 9744 * through a thunk. 9745 */ 9746 void sendAfterTextChanged(Editable text) { 9747 if (mListeners != null) { 9748 final ArrayList<TextWatcher> list = mListeners; 9749 final int count = list.size(); 9750 for (int i = 0; i < count; i++) { 9751 list.get(i).afterTextChanged(text); 9752 } 9753 } 9754 9755 // Always notify AutoFillManager - it will return right away if autofill is disabled. 9756 notifyAutoFillManagerAfterTextChangedIfNeeded(); 9757 9758 hideErrorIfUnchanged(); 9759 } 9760 9761 private void notifyAutoFillManagerAfterTextChangedIfNeeded() { 9762 // It is important to not check whether the view is important for autofill 9763 // since the user can trigger autofill manually on not important views. 9764 if (!isAutofillable()) { 9765 return; 9766 } 9767 final AutofillManager afm = mContext.getSystemService(AutofillManager.class); 9768 if (afm == null) { 9769 return; 9770 } 9771 9772 if (mLastValueSentToAutofillManager == null 9773 || !mLastValueSentToAutofillManager.equals(mText)) { 9774 if (android.view.autofill.Helper.sVerbose) { 9775 Log.v(LOG_TAG, "notifying AFM after text changed"); 9776 } 9777 afm.notifyValueChanged(TextView.this); 9778 mLastValueSentToAutofillManager = mText; 9779 } else { 9780 if (android.view.autofill.Helper.sVerbose) { 9781 Log.v(LOG_TAG, "not notifying AFM on unchanged text"); 9782 } 9783 } 9784 } 9785 9786 private boolean isAutofillable() { 9787 // It is important to not check whether the view is important for autofill 9788 // since the user can trigger autofill manually on not important views. 9789 return getAutofillType() != AUTOFILL_TYPE_NONE; 9790 } 9791 9792 void updateAfterEdit() { 9793 invalidate(); 9794 int curs = getSelectionStart(); 9795 9796 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 9797 registerForPreDraw(); 9798 } 9799 9800 checkForResize(); 9801 9802 if (curs >= 0) { 9803 mHighlightPathBogus = true; 9804 if (mEditor != null) mEditor.makeBlink(); 9805 bringPointIntoView(curs); 9806 } 9807 } 9808 9809 /** 9810 * Not private so it can be called from an inner class without going 9811 * through a thunk. 9812 */ 9813 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 9814 sLastCutCopyOrTextChangedTime = 0; 9815 9816 final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState; 9817 if (ims == null || ims.mBatchEditNesting == 0) { 9818 updateAfterEdit(); 9819 } 9820 if (ims != null) { 9821 ims.mContentChanged = true; 9822 if (ims.mChangedStart < 0) { 9823 ims.mChangedStart = start; 9824 ims.mChangedEnd = start + before; 9825 } else { 9826 ims.mChangedStart = Math.min(ims.mChangedStart, start); 9827 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 9828 } 9829 ims.mChangedDelta += after - before; 9830 } 9831 resetErrorChangedFlag(); 9832 sendOnTextChanged(buffer, start, before, after); 9833 onTextChanged(buffer, start, before, after); 9834 } 9835 9836 /** 9837 * Not private so it can be called from an inner class without going 9838 * through a thunk. 9839 */ 9840 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 9841 // XXX Make the start and end move together if this ends up 9842 // spending too much time invalidating. 9843 9844 boolean selChanged = false; 9845 int newSelStart = -1, newSelEnd = -1; 9846 9847 final Editor.InputMethodState ims = mEditor == null ? null : mEditor.mInputMethodState; 9848 9849 if (what == Selection.SELECTION_END) { 9850 selChanged = true; 9851 newSelEnd = newStart; 9852 9853 if (oldStart >= 0 || newStart >= 0) { 9854 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 9855 checkForResize(); 9856 registerForPreDraw(); 9857 if (mEditor != null) mEditor.makeBlink(); 9858 } 9859 } 9860 9861 if (what == Selection.SELECTION_START) { 9862 selChanged = true; 9863 newSelStart = newStart; 9864 9865 if (oldStart >= 0 || newStart >= 0) { 9866 int end = Selection.getSelectionEnd(buf); 9867 invalidateCursor(end, oldStart, newStart); 9868 } 9869 } 9870 9871 if (selChanged) { 9872 mHighlightPathBogus = true; 9873 if (mEditor != null && !isFocused()) mEditor.mSelectionMoved = true; 9874 9875 if ((buf.getSpanFlags(what) & Spanned.SPAN_INTERMEDIATE) == 0) { 9876 if (newSelStart < 0) { 9877 newSelStart = Selection.getSelectionStart(buf); 9878 } 9879 if (newSelEnd < 0) { 9880 newSelEnd = Selection.getSelectionEnd(buf); 9881 } 9882 9883 if (mEditor != null) { 9884 mEditor.refreshTextActionMode(); 9885 if (!hasSelection() 9886 && mEditor.getTextActionMode() == null && hasTransientState()) { 9887 // User generated selection has been removed. 9888 setHasTransientState(false); 9889 } 9890 } 9891 onSelectionChanged(newSelStart, newSelEnd); 9892 } 9893 } 9894 9895 if (what instanceof UpdateAppearance || what instanceof ParagraphStyle 9896 || what instanceof CharacterStyle) { 9897 if (ims == null || ims.mBatchEditNesting == 0) { 9898 invalidate(); 9899 mHighlightPathBogus = true; 9900 checkForResize(); 9901 } else { 9902 ims.mContentChanged = true; 9903 } 9904 if (mEditor != null) { 9905 if (oldStart >= 0) mEditor.invalidateTextDisplayList(mLayout, oldStart, oldEnd); 9906 if (newStart >= 0) mEditor.invalidateTextDisplayList(mLayout, newStart, newEnd); 9907 mEditor.invalidateHandlesAndActionMode(); 9908 } 9909 } 9910 9911 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 9912 mHighlightPathBogus = true; 9913 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 9914 ims.mSelectionModeChanged = true; 9915 } 9916 9917 if (Selection.getSelectionStart(buf) >= 0) { 9918 if (ims == null || ims.mBatchEditNesting == 0) { 9919 invalidateCursor(); 9920 } else { 9921 ims.mCursorChanged = true; 9922 } 9923 } 9924 } 9925 9926 if (what instanceof ParcelableSpan) { 9927 // If this is a span that can be sent to a remote process, 9928 // the current extract editor would be interested in it. 9929 if (ims != null && ims.mExtractedTextRequest != null) { 9930 if (ims.mBatchEditNesting != 0) { 9931 if (oldStart >= 0) { 9932 if (ims.mChangedStart > oldStart) { 9933 ims.mChangedStart = oldStart; 9934 } 9935 if (ims.mChangedStart > oldEnd) { 9936 ims.mChangedStart = oldEnd; 9937 } 9938 } 9939 if (newStart >= 0) { 9940 if (ims.mChangedStart > newStart) { 9941 ims.mChangedStart = newStart; 9942 } 9943 if (ims.mChangedStart > newEnd) { 9944 ims.mChangedStart = newEnd; 9945 } 9946 } 9947 } else { 9948 if (DEBUG_EXTRACT) { 9949 Log.v(LOG_TAG, "Span change outside of batch: " 9950 + oldStart + "-" + oldEnd + "," 9951 + newStart + "-" + newEnd + " " + what); 9952 } 9953 ims.mContentChanged = true; 9954 } 9955 } 9956 } 9957 9958 if (mEditor != null && mEditor.mSpellChecker != null && newStart < 0 9959 && what instanceof SpellCheckSpan) { 9960 mEditor.mSpellChecker.onSpellCheckSpanRemoved((SpellCheckSpan) what); 9961 } 9962 } 9963 9964 @Override 9965 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 9966 if (isTemporarilyDetached()) { 9967 // If we are temporarily in the detach state, then do nothing. 9968 super.onFocusChanged(focused, direction, previouslyFocusedRect); 9969 return; 9970 } 9971 9972 if (mEditor != null) mEditor.onFocusChanged(focused, direction); 9973 9974 if (focused) { 9975 if (mText instanceof Spannable) { 9976 Spannable sp = (Spannable) mText; 9977 MetaKeyKeyListener.resetMetaState(sp); 9978 } 9979 } 9980 9981 startStopMarquee(focused); 9982 9983 if (mTransformation != null) { 9984 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 9985 } 9986 9987 super.onFocusChanged(focused, direction, previouslyFocusedRect); 9988 } 9989 9990 @Override 9991 public void onWindowFocusChanged(boolean hasWindowFocus) { 9992 super.onWindowFocusChanged(hasWindowFocus); 9993 9994 if (mEditor != null) mEditor.onWindowFocusChanged(hasWindowFocus); 9995 9996 startStopMarquee(hasWindowFocus); 9997 } 9998 9999 @Override 10000 protected void onVisibilityChanged(View changedView, int visibility) { 10001 super.onVisibilityChanged(changedView, visibility); 10002 if (mEditor != null && visibility != VISIBLE) { 10003 mEditor.hideCursorAndSpanControllers(); 10004 stopTextActionMode(); 10005 } 10006 } 10007 10008 /** 10009 * Use {@link BaseInputConnection#removeComposingSpans 10010 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 10011 * state from this text view. 10012 */ 10013 public void clearComposingText() { 10014 if (mText instanceof Spannable) { 10015 BaseInputConnection.removeComposingSpans((Spannable) mText); 10016 } 10017 } 10018 10019 @Override 10020 public void setSelected(boolean selected) { 10021 boolean wasSelected = isSelected(); 10022 10023 super.setSelected(selected); 10024 10025 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 10026 if (selected) { 10027 startMarquee(); 10028 } else { 10029 stopMarquee(); 10030 } 10031 } 10032 } 10033 10034 @Override 10035 public boolean onTouchEvent(MotionEvent event) { 10036 final int action = event.getActionMasked(); 10037 if (mEditor != null) { 10038 mEditor.onTouchEvent(event); 10039 10040 if (mEditor.mSelectionModifierCursorController != null 10041 && mEditor.mSelectionModifierCursorController.isDragAcceleratorActive()) { 10042 return true; 10043 } 10044 } 10045 10046 final boolean superResult = super.onTouchEvent(event); 10047 10048 /* 10049 * Don't handle the release after a long press, because it will move the selection away from 10050 * whatever the menu action was trying to affect. If the long press should have triggered an 10051 * insertion action mode, we can now actually show it. 10052 */ 10053 if (mEditor != null && mEditor.mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 10054 mEditor.mDiscardNextActionUp = false; 10055 10056 if (mEditor.mIsInsertionActionModeStartPending) { 10057 mEditor.startInsertionActionMode(); 10058 mEditor.mIsInsertionActionModeStartPending = false; 10059 } 10060 return superResult; 10061 } 10062 10063 final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) 10064 && (mEditor == null || !mEditor.mIgnoreActionUpEvent) && isFocused(); 10065 10066 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 10067 && mText instanceof Spannable && mLayout != null) { 10068 boolean handled = false; 10069 10070 if (mMovement != null) { 10071 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 10072 } 10073 10074 final boolean textIsSelectable = isTextSelectable(); 10075 if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && textIsSelectable) { 10076 // The LinkMovementMethod which should handle taps on links has not been installed 10077 // on non editable text that support text selection. 10078 // We reproduce its behavior here to open links for these. 10079 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 10080 getSelectionEnd(), ClickableSpan.class); 10081 10082 if (links.length > 0) { 10083 links[0].onClick(this); 10084 handled = true; 10085 } 10086 } 10087 10088 if (touchIsFinished && (isTextEditable() || textIsSelectable)) { 10089 // Show the IME, except when selecting in read-only text. 10090 final InputMethodManager imm = InputMethodManager.peekInstance(); 10091 viewClicked(imm); 10092 if (isTextEditable() && mEditor.mShowSoftInputOnFocus && imm != null) { 10093 imm.showSoftInput(this, 0); 10094 } 10095 10096 // The above condition ensures that the mEditor is not null 10097 mEditor.onTouchUpEvent(event); 10098 10099 handled = true; 10100 } 10101 10102 if (handled) { 10103 return true; 10104 } 10105 } 10106 10107 return superResult; 10108 } 10109 10110 @Override 10111 public boolean onGenericMotionEvent(MotionEvent event) { 10112 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 10113 try { 10114 if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { 10115 return true; 10116 } 10117 } catch (AbstractMethodError ex) { 10118 // onGenericMotionEvent was added to the MovementMethod interface in API 12. 10119 // Ignore its absence in case third party applications implemented the 10120 // interface directly. 10121 } 10122 } 10123 return super.onGenericMotionEvent(event); 10124 } 10125 10126 @Override 10127 protected void onCreateContextMenu(ContextMenu menu) { 10128 if (mEditor != null) { 10129 mEditor.onCreateContextMenu(menu); 10130 } 10131 } 10132 10133 @Override 10134 public boolean showContextMenu() { 10135 if (mEditor != null) { 10136 mEditor.setContextMenuAnchor(Float.NaN, Float.NaN); 10137 } 10138 return super.showContextMenu(); 10139 } 10140 10141 @Override 10142 public boolean showContextMenu(float x, float y) { 10143 if (mEditor != null) { 10144 mEditor.setContextMenuAnchor(x, y); 10145 } 10146 return super.showContextMenu(x, y); 10147 } 10148 10149 /** 10150 * @return True iff this TextView contains a text that can be edited, or if this is 10151 * a selectable TextView. 10152 */ 10153 boolean isTextEditable() { 10154 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 10155 } 10156 10157 /** 10158 * Returns true, only while processing a touch gesture, if the initial 10159 * touch down event caused focus to move to the text view and as a result 10160 * its selection changed. Only valid while processing the touch gesture 10161 * of interest, in an editable text view. 10162 */ 10163 public boolean didTouchFocusSelect() { 10164 return mEditor != null && mEditor.mTouchFocusSelected; 10165 } 10166 10167 @Override 10168 public void cancelLongPress() { 10169 super.cancelLongPress(); 10170 if (mEditor != null) mEditor.mIgnoreActionUpEvent = true; 10171 } 10172 10173 @Override 10174 public boolean onTrackballEvent(MotionEvent event) { 10175 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 10176 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 10177 return true; 10178 } 10179 } 10180 10181 return super.onTrackballEvent(event); 10182 } 10183 10184 /** 10185 * Sets the Scroller used for producing a scrolling animation 10186 * 10187 * @param s A Scroller instance 10188 */ 10189 public void setScroller(Scroller s) { 10190 mScroller = s; 10191 } 10192 10193 @Override 10194 protected float getLeftFadingEdgeStrength() { 10195 if (isMarqueeFadeEnabled() && mMarquee != null && !mMarquee.isStopped()) { 10196 final Marquee marquee = mMarquee; 10197 if (marquee.shouldDrawLeftFade()) { 10198 return getHorizontalFadingEdgeStrength(marquee.getScroll(), 0.0f); 10199 } else { 10200 return 0.0f; 10201 } 10202 } else if (getLineCount() == 1) { 10203 final float lineLeft = getLayout().getLineLeft(0); 10204 if (lineLeft > mScrollX) return 0.0f; 10205 return getHorizontalFadingEdgeStrength(mScrollX, lineLeft); 10206 } 10207 return super.getLeftFadingEdgeStrength(); 10208 } 10209 10210 @Override 10211 protected float getRightFadingEdgeStrength() { 10212 if (isMarqueeFadeEnabled() && mMarquee != null && !mMarquee.isStopped()) { 10213 final Marquee marquee = mMarquee; 10214 return getHorizontalFadingEdgeStrength(marquee.getMaxFadeScroll(), marquee.getScroll()); 10215 } else if (getLineCount() == 1) { 10216 final float rightEdge = mScrollX + 10217 (getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight()); 10218 final float lineRight = getLayout().getLineRight(0); 10219 if (lineRight < rightEdge) return 0.0f; 10220 return getHorizontalFadingEdgeStrength(rightEdge, lineRight); 10221 } 10222 return super.getRightFadingEdgeStrength(); 10223 } 10224 10225 /** 10226 * Calculates the fading edge strength as the ratio of the distance between two 10227 * horizontal positions to {@link View#getHorizontalFadingEdgeLength()}. Uses the absolute 10228 * value for the distance calculation. 10229 * 10230 * @param position1 A horizontal position. 10231 * @param position2 A horizontal position. 10232 * @return Fading edge strength between [0.0f, 1.0f]. 10233 */ 10234 @FloatRange(from = 0.0, to = 1.0) 10235 private float getHorizontalFadingEdgeStrength(float position1, float position2) { 10236 final int horizontalFadingEdgeLength = getHorizontalFadingEdgeLength(); 10237 if (horizontalFadingEdgeLength == 0) return 0.0f; 10238 final float diff = Math.abs(position1 - position2); 10239 if (diff > horizontalFadingEdgeLength) return 1.0f; 10240 return diff / horizontalFadingEdgeLength; 10241 } 10242 10243 private boolean isMarqueeFadeEnabled() { 10244 return mEllipsize == TextUtils.TruncateAt.MARQUEE 10245 && mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 10246 } 10247 10248 @Override 10249 protected int computeHorizontalScrollRange() { 10250 if (mLayout != null) { 10251 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT 10252 ? (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 10253 } 10254 10255 return super.computeHorizontalScrollRange(); 10256 } 10257 10258 @Override 10259 protected int computeVerticalScrollRange() { 10260 if (mLayout != null) { 10261 return mLayout.getHeight(); 10262 } 10263 return super.computeVerticalScrollRange(); 10264 } 10265 10266 @Override 10267 protected int computeVerticalScrollExtent() { 10268 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 10269 } 10270 10271 @Override 10272 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 10273 super.findViewsWithText(outViews, searched, flags); 10274 if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0 10275 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) { 10276 String searchedLowerCase = searched.toString().toLowerCase(); 10277 String textLowerCase = mText.toString().toLowerCase(); 10278 if (textLowerCase.contains(searchedLowerCase)) { 10279 outViews.add(this); 10280 } 10281 } 10282 } 10283 10284 /** 10285 * Type of the text buffer that defines the characteristics of the text such as static, 10286 * styleable, or editable. 10287 */ 10288 public enum BufferType { 10289 NORMAL, SPANNABLE, EDITABLE 10290 } 10291 10292 /** 10293 * Returns the TextView_textColor attribute from the TypedArray, if set, or 10294 * the TextAppearance_textColor from the TextView_textAppearance attribute, 10295 * if TextView_textColor was not set directly. 10296 * 10297 * @removed 10298 */ 10299 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 10300 if (attrs == null) { 10301 // Preserve behavior prior to removal of this API. 10302 throw new NullPointerException(); 10303 } 10304 10305 // It's not safe to use this method from apps. The parameter 'attrs' 10306 // must have been obtained using the TextView filter array which is not 10307 // available to the SDK. As such, we grab a default TypedArray with the 10308 // right filter instead here. 10309 final TypedArray a = context.obtainStyledAttributes(R.styleable.TextView); 10310 ColorStateList colors = a.getColorStateList(R.styleable.TextView_textColor); 10311 if (colors == null) { 10312 final int ap = a.getResourceId(R.styleable.TextView_textAppearance, 0); 10313 if (ap != 0) { 10314 final TypedArray appearance = context.obtainStyledAttributes( 10315 ap, R.styleable.TextAppearance); 10316 colors = appearance.getColorStateList(R.styleable.TextAppearance_textColor); 10317 appearance.recycle(); 10318 } 10319 } 10320 a.recycle(); 10321 10322 return colors; 10323 } 10324 10325 /** 10326 * Returns the default color from the TextView_textColor attribute from the 10327 * AttributeSet, if set, or the default color from the 10328 * TextAppearance_textColor from the TextView_textAppearance attribute, if 10329 * TextView_textColor was not set directly. 10330 * 10331 * @removed 10332 */ 10333 public static int getTextColor(Context context, TypedArray attrs, int def) { 10334 final ColorStateList colors = getTextColors(context, attrs); 10335 if (colors == null) { 10336 return def; 10337 } else { 10338 return colors.getDefaultColor(); 10339 } 10340 } 10341 10342 @Override 10343 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 10344 if (event.hasModifiers(KeyEvent.META_CTRL_ON)) { 10345 // Handle Ctrl-only shortcuts. 10346 switch (keyCode) { 10347 case KeyEvent.KEYCODE_A: 10348 if (canSelectText()) { 10349 return onTextContextMenuItem(ID_SELECT_ALL); 10350 } 10351 break; 10352 case KeyEvent.KEYCODE_Z: 10353 if (canUndo()) { 10354 return onTextContextMenuItem(ID_UNDO); 10355 } 10356 break; 10357 case KeyEvent.KEYCODE_X: 10358 if (canCut()) { 10359 return onTextContextMenuItem(ID_CUT); 10360 } 10361 break; 10362 case KeyEvent.KEYCODE_C: 10363 if (canCopy()) { 10364 return onTextContextMenuItem(ID_COPY); 10365 } 10366 break; 10367 case KeyEvent.KEYCODE_V: 10368 if (canPaste()) { 10369 return onTextContextMenuItem(ID_PASTE); 10370 } 10371 break; 10372 } 10373 } else if (event.hasModifiers(KeyEvent.META_CTRL_ON | KeyEvent.META_SHIFT_ON)) { 10374 // Handle Ctrl-Shift shortcuts. 10375 switch (keyCode) { 10376 case KeyEvent.KEYCODE_Z: 10377 if (canRedo()) { 10378 return onTextContextMenuItem(ID_REDO); 10379 } 10380 break; 10381 case KeyEvent.KEYCODE_V: 10382 if (canPaste()) { 10383 return onTextContextMenuItem(ID_PASTE_AS_PLAIN_TEXT); 10384 } 10385 } 10386 } 10387 return super.onKeyShortcut(keyCode, event); 10388 } 10389 10390 /** 10391 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 10392 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 10393 * a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not 10394 * sufficient. 10395 */ 10396 boolean canSelectText() { 10397 return mText.length() != 0 && mEditor != null && mEditor.hasSelectionController(); 10398 } 10399 10400 /** 10401 * Test based on the <i>intrinsic</i> charateristics of the TextView. 10402 * The text must be spannable and the movement method must allow for arbitary selection. 10403 * 10404 * See also {@link #canSelectText()}. 10405 */ 10406 boolean textCanBeSelected() { 10407 // prepareCursorController() relies on this method. 10408 // If you change this condition, make sure prepareCursorController is called anywhere 10409 // the value of this condition might be changed. 10410 if (mMovement == null || !mMovement.canSelectArbitrarily()) return false; 10411 return isTextEditable() 10412 || (isTextSelectable() && mText instanceof Spannable && isEnabled()); 10413 } 10414 10415 private Locale getTextServicesLocale(boolean allowNullLocale) { 10416 // Start fetching the text services locale asynchronously. 10417 updateTextServicesLocaleAsync(); 10418 // If !allowNullLocale and there is no cached text services locale, just return the default 10419 // locale. 10420 return (mCurrentSpellCheckerLocaleCache == null && !allowNullLocale) ? Locale.getDefault() 10421 : mCurrentSpellCheckerLocaleCache; 10422 } 10423 10424 /** 10425 * This is a temporary method. Future versions may support multi-locale text. 10426 * Caveat: This method may not return the latest text services locale, but this should be 10427 * acceptable and it's more important to make this method asynchronous. 10428 * 10429 * @return The locale that should be used for a word iterator 10430 * in this TextView, based on the current spell checker settings, 10431 * the current IME's locale, or the system default locale. 10432 * Please note that a word iterator in this TextView is different from another word iterator 10433 * used by SpellChecker.java of TextView. This method should be used for the former. 10434 * @hide 10435 */ 10436 // TODO: Support multi-locale 10437 // TODO: Update the text services locale immediately after the keyboard locale is switched 10438 // by catching intent of keyboard switch event 10439 public Locale getTextServicesLocale() { 10440 return getTextServicesLocale(false /* allowNullLocale */); 10441 } 10442 10443 /** 10444 * @return {@code true} if this TextView is specialized for showing and interacting with the 10445 * extracted text in a full-screen input method. 10446 * @hide 10447 */ 10448 public boolean isInExtractedMode() { 10449 return false; 10450 } 10451 10452 /** 10453 * @return {@code true} if this widget supports auto-sizing text and has been configured to 10454 * auto-size. 10455 */ 10456 private boolean isAutoSizeEnabled() { 10457 return supportsAutoSizeText() && mAutoSizeTextType != AUTO_SIZE_TEXT_TYPE_NONE; 10458 } 10459 10460 /** 10461 * @return {@code true} if this TextView supports auto-sizing text to fit within its container. 10462 * @hide 10463 */ 10464 protected boolean supportsAutoSizeText() { 10465 return true; 10466 } 10467 10468 /** 10469 * This is a temporary method. Future versions may support multi-locale text. 10470 * Caveat: This method may not return the latest spell checker locale, but this should be 10471 * acceptable and it's more important to make this method asynchronous. 10472 * 10473 * @return The locale that should be used for a spell checker in this TextView, 10474 * based on the current spell checker settings, the current IME's locale, or the system default 10475 * locale. 10476 * @hide 10477 */ 10478 public Locale getSpellCheckerLocale() { 10479 return getTextServicesLocale(true /* allowNullLocale */); 10480 } 10481 10482 private void updateTextServicesLocaleAsync() { 10483 // AsyncTask.execute() uses a serial executor which means we don't have 10484 // to lock around updateTextServicesLocaleLocked() to prevent it from 10485 // being executed n times in parallel. 10486 AsyncTask.execute(new Runnable() { 10487 @Override 10488 public void run() { 10489 updateTextServicesLocaleLocked(); 10490 } 10491 }); 10492 } 10493 10494 private void updateTextServicesLocaleLocked() { 10495 final TextServicesManager textServicesManager = (TextServicesManager) 10496 mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); 10497 final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true); 10498 final Locale locale; 10499 if (subtype != null) { 10500 locale = subtype.getLocaleObject(); 10501 } else { 10502 locale = null; 10503 } 10504 mCurrentSpellCheckerLocaleCache = locale; 10505 } 10506 10507 void onLocaleChanged() { 10508 mEditor.onLocaleChanged(); 10509 } 10510 10511 /** 10512 * This method is used by the ArrowKeyMovementMethod to jump from one word to the other. 10513 * Made available to achieve a consistent behavior. 10514 * @hide 10515 */ 10516 public WordIterator getWordIterator() { 10517 if (mEditor != null) { 10518 return mEditor.getWordIterator(); 10519 } else { 10520 return null; 10521 } 10522 } 10523 10524 /** @hide */ 10525 @Override 10526 public void onPopulateAccessibilityEventInternal(AccessibilityEvent event) { 10527 super.onPopulateAccessibilityEventInternal(event); 10528 10529 final CharSequence text = getTextForAccessibility(); 10530 if (!TextUtils.isEmpty(text)) { 10531 event.getText().add(text); 10532 } 10533 } 10534 10535 @Override 10536 public CharSequence getAccessibilityClassName() { 10537 return TextView.class.getName(); 10538 } 10539 10540 @Override 10541 public void onProvideStructure(ViewStructure structure) { 10542 super.onProvideStructure(structure); 10543 onProvideAutoStructureForAssistOrAutofill(structure, false); 10544 } 10545 10546 @Override 10547 public void onProvideAutofillStructure(ViewStructure structure, int flags) { 10548 super.onProvideAutofillStructure(structure, flags); 10549 onProvideAutoStructureForAssistOrAutofill(structure, true); 10550 } 10551 10552 private void onProvideAutoStructureForAssistOrAutofill(ViewStructure structure, 10553 boolean forAutofill) { 10554 final boolean isPassword = hasPasswordTransformationMethod() 10555 || isPasswordInputType(getInputType()); 10556 if (forAutofill) { 10557 structure.setDataIsSensitive(!mTextSetFromXmlOrResourceId); 10558 if (mTextId != ResourceId.ID_NULL) { 10559 try { 10560 structure.setTextIdEntry(getResources().getResourceEntryName(mTextId)); 10561 } catch (Resources.NotFoundException e) { 10562 if (android.view.autofill.Helper.sVerbose) { 10563 Log.v(LOG_TAG, "onProvideAutofillStructure(): cannot set name for text id " 10564 + mTextId + ": " + e.getMessage()); 10565 } 10566 } 10567 } 10568 } 10569 10570 if (!isPassword || forAutofill) { 10571 if (mLayout == null) { 10572 assumeLayout(); 10573 } 10574 Layout layout = mLayout; 10575 final int lineCount = layout.getLineCount(); 10576 if (lineCount <= 1) { 10577 // Simple case: this is a single line. 10578 final CharSequence text = getText(); 10579 if (forAutofill) { 10580 structure.setText(text); 10581 } else { 10582 structure.setText(text, getSelectionStart(), getSelectionEnd()); 10583 } 10584 } else { 10585 // Complex case: multi-line, could be scrolled or within a scroll container 10586 // so some lines are not visible. 10587 final int[] tmpCords = new int[2]; 10588 getLocationInWindow(tmpCords); 10589 final int topWindowLocation = tmpCords[1]; 10590 View root = this; 10591 ViewParent viewParent = getParent(); 10592 while (viewParent instanceof View) { 10593 root = (View) viewParent; 10594 viewParent = root.getParent(); 10595 } 10596 final int windowHeight = root.getHeight(); 10597 final int topLine; 10598 final int bottomLine; 10599 if (topWindowLocation >= 0) { 10600 // The top of the view is fully within its window; start text at line 0. 10601 topLine = getLineAtCoordinateUnclamped(0); 10602 bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1); 10603 } else { 10604 // The top of hte window has scrolled off the top of the window; figure out 10605 // the starting line for this. 10606 topLine = getLineAtCoordinateUnclamped(-topWindowLocation); 10607 bottomLine = getLineAtCoordinateUnclamped(windowHeight - 1 - topWindowLocation); 10608 } 10609 // We want to return some contextual lines above/below the lines that are 10610 // actually visible. 10611 int expandedTopLine = topLine - (bottomLine - topLine) / 2; 10612 if (expandedTopLine < 0) { 10613 expandedTopLine = 0; 10614 } 10615 int expandedBottomLine = bottomLine + (bottomLine - topLine) / 2; 10616 if (expandedBottomLine >= lineCount) { 10617 expandedBottomLine = lineCount - 1; 10618 } 10619 10620 // Convert lines into character offsets. 10621 int expandedTopChar = layout.getLineStart(expandedTopLine); 10622 int expandedBottomChar = layout.getLineEnd(expandedBottomLine); 10623 10624 // Take into account selection -- if there is a selection, we need to expand 10625 // the text we are returning to include that selection. 10626 final int selStart = getSelectionStart(); 10627 final int selEnd = getSelectionEnd(); 10628 if (selStart < selEnd) { 10629 if (selStart < expandedTopChar) { 10630 expandedTopChar = selStart; 10631 } 10632 if (selEnd > expandedBottomChar) { 10633 expandedBottomChar = selEnd; 10634 } 10635 } 10636 10637 // Get the text and trim it to the range we are reporting. 10638 CharSequence text = getText(); 10639 if (expandedTopChar > 0 || expandedBottomChar < text.length()) { 10640 text = text.subSequence(expandedTopChar, expandedBottomChar); 10641 } 10642 10643 if (forAutofill) { 10644 structure.setText(text); 10645 } else { 10646 structure.setText(text, selStart - expandedTopChar, selEnd - expandedTopChar); 10647 10648 final int[] lineOffsets = new int[bottomLine - topLine + 1]; 10649 final int[] lineBaselines = new int[bottomLine - topLine + 1]; 10650 final int baselineOffset = getBaselineOffset(); 10651 for (int i = topLine; i <= bottomLine; i++) { 10652 lineOffsets[i - topLine] = layout.getLineStart(i); 10653 lineBaselines[i - topLine] = layout.getLineBaseline(i) + baselineOffset; 10654 } 10655 structure.setTextLines(lineOffsets, lineBaselines); 10656 } 10657 } 10658 10659 if (!forAutofill) { 10660 // Extract style information that applies to the TextView as a whole. 10661 int style = 0; 10662 int typefaceStyle = getTypefaceStyle(); 10663 if ((typefaceStyle & Typeface.BOLD) != 0) { 10664 style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD; 10665 } 10666 if ((typefaceStyle & Typeface.ITALIC) != 0) { 10667 style |= AssistStructure.ViewNode.TEXT_STYLE_ITALIC; 10668 } 10669 10670 // Global styles can also be set via TextView.setPaintFlags(). 10671 int paintFlags = mTextPaint.getFlags(); 10672 if ((paintFlags & Paint.FAKE_BOLD_TEXT_FLAG) != 0) { 10673 style |= AssistStructure.ViewNode.TEXT_STYLE_BOLD; 10674 } 10675 if ((paintFlags & Paint.UNDERLINE_TEXT_FLAG) != 0) { 10676 style |= AssistStructure.ViewNode.TEXT_STYLE_UNDERLINE; 10677 } 10678 if ((paintFlags & Paint.STRIKE_THRU_TEXT_FLAG) != 0) { 10679 style |= AssistStructure.ViewNode.TEXT_STYLE_STRIKE_THRU; 10680 } 10681 10682 // TextView does not have its own text background color. A background is either part 10683 // of the View (and can be any drawable) or a BackgroundColorSpan inside the text. 10684 structure.setTextStyle(getTextSize(), getCurrentTextColor(), 10685 AssistStructure.ViewNode.TEXT_COLOR_UNDEFINED /* bgColor */, style); 10686 } else { 10687 structure.setMinTextEms(getMinEms()); 10688 structure.setMaxTextEms(getMaxEms()); 10689 int maxLength = -1; 10690 for (InputFilter filter: getFilters()) { 10691 if (filter instanceof InputFilter.LengthFilter) { 10692 maxLength = ((InputFilter.LengthFilter) filter).getMax(); 10693 break; 10694 } 10695 } 10696 structure.setMaxTextLength(maxLength); 10697 } 10698 } 10699 structure.setHint(getHint()); 10700 structure.setInputType(getInputType()); 10701 } 10702 10703 boolean canRequestAutofill() { 10704 if (!isAutofillable()) { 10705 return false; 10706 } 10707 final AutofillManager afm = mContext.getSystemService(AutofillManager.class); 10708 if (afm != null) { 10709 return afm.isEnabled(); 10710 } 10711 return false; 10712 } 10713 10714 private void requestAutofill() { 10715 final AutofillManager afm = mContext.getSystemService(AutofillManager.class); 10716 if (afm != null) { 10717 afm.requestAutofill(this); 10718 } 10719 } 10720 10721 @Override 10722 public void autofill(AutofillValue value) { 10723 if (!value.isText() || !isTextEditable()) { 10724 Log.w(LOG_TAG, value + " could not be autofilled into " + this); 10725 return; 10726 } 10727 10728 final CharSequence autofilledValue = value.getTextValue(); 10729 10730 // First autofill it... 10731 setText(autofilledValue, mBufferType, true, 0); 10732 10733 // ...then move cursor to the end. 10734 final CharSequence text = getText(); 10735 if ((text instanceof Spannable)) { 10736 Selection.setSelection((Spannable) text, text.length()); 10737 } 10738 } 10739 10740 @Override 10741 public @AutofillType int getAutofillType() { 10742 return isTextEditable() ? AUTOFILL_TYPE_TEXT : AUTOFILL_TYPE_NONE; 10743 } 10744 10745 /** 10746 * Gets the {@link TextView}'s current text for AutoFill. The value is trimmed to 100K 10747 * {@code char}s if longer. 10748 * 10749 * @return current text, {@code null} if the text is not editable 10750 * 10751 * @see View#getAutofillValue() 10752 */ 10753 @Override 10754 @Nullable 10755 public AutofillValue getAutofillValue() { 10756 if (isTextEditable()) { 10757 final CharSequence text = TextUtils.trimToParcelableSize(getText()); 10758 return AutofillValue.forText(text); 10759 } 10760 return null; 10761 } 10762 10763 /** @hide */ 10764 @Override 10765 public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 10766 super.onInitializeAccessibilityEventInternal(event); 10767 10768 final boolean isPassword = hasPasswordTransformationMethod(); 10769 event.setPassword(isPassword); 10770 10771 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { 10772 event.setFromIndex(Selection.getSelectionStart(mText)); 10773 event.setToIndex(Selection.getSelectionEnd(mText)); 10774 event.setItemCount(mText.length()); 10775 } 10776 } 10777 10778 /** @hide */ 10779 @Override 10780 public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 10781 super.onInitializeAccessibilityNodeInfoInternal(info); 10782 10783 final boolean isPassword = hasPasswordTransformationMethod(); 10784 info.setPassword(isPassword); 10785 info.setText(getTextForAccessibility()); 10786 info.setHintText(mHint); 10787 info.setShowingHintText(isShowingHint()); 10788 info.setHeading(mIsAccessibilityHeading); 10789 10790 if (mBufferType == BufferType.EDITABLE) { 10791 info.setEditable(true); 10792 if (isEnabled()) { 10793 info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_SET_TEXT); 10794 } 10795 } 10796 10797 if (mEditor != null) { 10798 info.setInputType(mEditor.mInputType); 10799 10800 if (mEditor.mError != null) { 10801 info.setContentInvalid(true); 10802 info.setError(mEditor.mError); 10803 } 10804 } 10805 10806 if (!TextUtils.isEmpty(mText)) { 10807 info.addAction(AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY); 10808 info.addAction(AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY); 10809 info.setMovementGranularities(AccessibilityNodeInfo.MOVEMENT_GRANULARITY_CHARACTER 10810 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_WORD 10811 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE 10812 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PARAGRAPH 10813 | AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE); 10814 info.addAction(AccessibilityNodeInfo.ACTION_SET_SELECTION); 10815 info.setAvailableExtraData( 10816 Arrays.asList(EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY)); 10817 } 10818 10819 if (isFocused()) { 10820 if (canCopy()) { 10821 info.addAction(AccessibilityNodeInfo.ACTION_COPY); 10822 } 10823 if (canPaste()) { 10824 info.addAction(AccessibilityNodeInfo.ACTION_PASTE); 10825 } 10826 if (canCut()) { 10827 info.addAction(AccessibilityNodeInfo.ACTION_CUT); 10828 } 10829 if (canShare()) { 10830 info.addAction(new AccessibilityNodeInfo.AccessibilityAction( 10831 ACCESSIBILITY_ACTION_SHARE, 10832 getResources().getString(com.android.internal.R.string.share))); 10833 } 10834 if (canProcessText()) { // also implies mEditor is not null. 10835 mEditor.mProcessTextIntentActionsHandler.onInitializeAccessibilityNodeInfo(info); 10836 } 10837 } 10838 10839 // Check for known input filter types. 10840 final int numFilters = mFilters.length; 10841 for (int i = 0; i < numFilters; i++) { 10842 final InputFilter filter = mFilters[i]; 10843 if (filter instanceof InputFilter.LengthFilter) { 10844 info.setMaxTextLength(((InputFilter.LengthFilter) filter).getMax()); 10845 } 10846 } 10847 10848 if (!isSingleLine()) { 10849 info.setMultiLine(true); 10850 } 10851 } 10852 10853 @Override 10854 public void addExtraDataToAccessibilityNodeInfo( 10855 AccessibilityNodeInfo info, String extraDataKey, Bundle arguments) { 10856 // The only extra data we support requires arguments. 10857 if (arguments == null) { 10858 return; 10859 } 10860 if (extraDataKey.equals(EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY)) { 10861 int positionInfoStartIndex = arguments.getInt( 10862 EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX, -1); 10863 int positionInfoLength = arguments.getInt( 10864 EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH, -1); 10865 if ((positionInfoLength <= 0) || (positionInfoStartIndex < 0) 10866 || (positionInfoStartIndex >= mText.length())) { 10867 Log.e(LOG_TAG, "Invalid arguments for accessibility character locations"); 10868 return; 10869 } 10870 RectF[] boundingRects = new RectF[positionInfoLength]; 10871 final CursorAnchorInfo.Builder builder = new CursorAnchorInfo.Builder(); 10872 populateCharacterBounds(builder, positionInfoStartIndex, 10873 positionInfoStartIndex + positionInfoLength, 10874 viewportToContentHorizontalOffset(), viewportToContentVerticalOffset()); 10875 CursorAnchorInfo cursorAnchorInfo = builder.setMatrix(null).build(); 10876 for (int i = 0; i < positionInfoLength; i++) { 10877 int flags = cursorAnchorInfo.getCharacterBoundsFlags(positionInfoStartIndex + i); 10878 if ((flags & FLAG_HAS_VISIBLE_REGION) == FLAG_HAS_VISIBLE_REGION) { 10879 RectF bounds = cursorAnchorInfo 10880 .getCharacterBounds(positionInfoStartIndex + i); 10881 if (bounds != null) { 10882 mapRectFromViewToScreenCoords(bounds, true); 10883 boundingRects[i] = bounds; 10884 } 10885 } 10886 } 10887 info.getExtras().putParcelableArray(extraDataKey, boundingRects); 10888 } 10889 } 10890 10891 /** 10892 * Populate requested character bounds in a {@link CursorAnchorInfo.Builder} 10893 * 10894 * @param builder The builder to populate 10895 * @param startIndex The starting character index to populate 10896 * @param endIndex The ending character index to populate 10897 * @param viewportToContentHorizontalOffset The horizontal offset from the viewport to the 10898 * content 10899 * @param viewportToContentVerticalOffset The vertical offset from the viewport to the content 10900 * @hide 10901 */ 10902 public void populateCharacterBounds(CursorAnchorInfo.Builder builder, 10903 int startIndex, int endIndex, float viewportToContentHorizontalOffset, 10904 float viewportToContentVerticalOffset) { 10905 final int minLine = mLayout.getLineForOffset(startIndex); 10906 final int maxLine = mLayout.getLineForOffset(endIndex - 1); 10907 for (int line = minLine; line <= maxLine; ++line) { 10908 final int lineStart = mLayout.getLineStart(line); 10909 final int lineEnd = mLayout.getLineEnd(line); 10910 final int offsetStart = Math.max(lineStart, startIndex); 10911 final int offsetEnd = Math.min(lineEnd, endIndex); 10912 final boolean ltrLine = 10913 mLayout.getParagraphDirection(line) == Layout.DIR_LEFT_TO_RIGHT; 10914 final float[] widths = new float[offsetEnd - offsetStart]; 10915 mLayout.getPaint().getTextWidths(mTransformed, offsetStart, offsetEnd, widths); 10916 final float top = mLayout.getLineTop(line); 10917 final float bottom = mLayout.getLineBottom(line); 10918 for (int offset = offsetStart; offset < offsetEnd; ++offset) { 10919 final float charWidth = widths[offset - offsetStart]; 10920 final boolean isRtl = mLayout.isRtlCharAt(offset); 10921 final float primary = mLayout.getPrimaryHorizontal(offset); 10922 final float secondary = mLayout.getSecondaryHorizontal(offset); 10923 // TODO: This doesn't work perfectly for text with custom styles and 10924 // TAB chars. 10925 final float left; 10926 final float right; 10927 if (ltrLine) { 10928 if (isRtl) { 10929 left = secondary - charWidth; 10930 right = secondary; 10931 } else { 10932 left = primary; 10933 right = primary + charWidth; 10934 } 10935 } else { 10936 if (!isRtl) { 10937 left = secondary; 10938 right = secondary + charWidth; 10939 } else { 10940 left = primary - charWidth; 10941 right = primary; 10942 } 10943 } 10944 // TODO: Check top-right and bottom-left as well. 10945 final float localLeft = left + viewportToContentHorizontalOffset; 10946 final float localRight = right + viewportToContentHorizontalOffset; 10947 final float localTop = top + viewportToContentVerticalOffset; 10948 final float localBottom = bottom + viewportToContentVerticalOffset; 10949 final boolean isTopLeftVisible = isPositionVisible(localLeft, localTop); 10950 final boolean isBottomRightVisible = 10951 isPositionVisible(localRight, localBottom); 10952 int characterBoundsFlags = 0; 10953 if (isTopLeftVisible || isBottomRightVisible) { 10954 characterBoundsFlags |= FLAG_HAS_VISIBLE_REGION; 10955 } 10956 if (!isTopLeftVisible || !isBottomRightVisible) { 10957 characterBoundsFlags |= CursorAnchorInfo.FLAG_HAS_INVISIBLE_REGION; 10958 } 10959 if (isRtl) { 10960 characterBoundsFlags |= CursorAnchorInfo.FLAG_IS_RTL; 10961 } 10962 // Here offset is the index in Java chars. 10963 builder.addCharacterBounds(offset, localLeft, localTop, localRight, 10964 localBottom, characterBoundsFlags); 10965 } 10966 } 10967 } 10968 10969 /** 10970 * @hide 10971 */ 10972 public boolean isPositionVisible(final float positionX, final float positionY) { 10973 synchronized (TEMP_POSITION) { 10974 final float[] position = TEMP_POSITION; 10975 position[0] = positionX; 10976 position[1] = positionY; 10977 View view = this; 10978 10979 while (view != null) { 10980 if (view != this) { 10981 // Local scroll is already taken into account in positionX/Y 10982 position[0] -= view.getScrollX(); 10983 position[1] -= view.getScrollY(); 10984 } 10985 10986 if (position[0] < 0 || position[1] < 0 || position[0] > view.getWidth() 10987 || position[1] > view.getHeight()) { 10988 return false; 10989 } 10990 10991 if (!view.getMatrix().isIdentity()) { 10992 view.getMatrix().mapPoints(position); 10993 } 10994 10995 position[0] += view.getLeft(); 10996 position[1] += view.getTop(); 10997 10998 final ViewParent parent = view.getParent(); 10999 if (parent instanceof View) { 11000 view = (View) parent; 11001 } else { 11002 // We've reached the ViewRoot, stop iterating 11003 view = null; 11004 } 11005 } 11006 } 11007 11008 // We've been able to walk up the view hierarchy and the position was never clipped 11009 return true; 11010 } 11011 11012 /** 11013 * Performs an accessibility action after it has been offered to the 11014 * delegate. 11015 * 11016 * @hide 11017 */ 11018 @Override 11019 public boolean performAccessibilityActionInternal(int action, Bundle arguments) { 11020 if (mEditor != null 11021 && mEditor.mProcessTextIntentActionsHandler.performAccessibilityAction(action)) { 11022 return true; 11023 } 11024 switch (action) { 11025 case AccessibilityNodeInfo.ACTION_CLICK: { 11026 return performAccessibilityActionClick(arguments); 11027 } 11028 case AccessibilityNodeInfo.ACTION_COPY: { 11029 if (isFocused() && canCopy()) { 11030 if (onTextContextMenuItem(ID_COPY)) { 11031 return true; 11032 } 11033 } 11034 } return false; 11035 case AccessibilityNodeInfo.ACTION_PASTE: { 11036 if (isFocused() && canPaste()) { 11037 if (onTextContextMenuItem(ID_PASTE)) { 11038 return true; 11039 } 11040 } 11041 } return false; 11042 case AccessibilityNodeInfo.ACTION_CUT: { 11043 if (isFocused() && canCut()) { 11044 if (onTextContextMenuItem(ID_CUT)) { 11045 return true; 11046 } 11047 } 11048 } return false; 11049 case AccessibilityNodeInfo.ACTION_SET_SELECTION: { 11050 ensureIterableTextForAccessibilitySelectable(); 11051 CharSequence text = getIterableTextForAccessibility(); 11052 if (text == null) { 11053 return false; 11054 } 11055 final int start = (arguments != null) ? arguments.getInt( 11056 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_START_INT, -1) : -1; 11057 final int end = (arguments != null) ? arguments.getInt( 11058 AccessibilityNodeInfo.ACTION_ARGUMENT_SELECTION_END_INT, -1) : -1; 11059 if ((getSelectionStart() != start || getSelectionEnd() != end)) { 11060 // No arguments clears the selection. 11061 if (start == end && end == -1) { 11062 Selection.removeSelection((Spannable) text); 11063 return true; 11064 } 11065 if (start >= 0 && start <= end && end <= text.length()) { 11066 Selection.setSelection((Spannable) text, start, end); 11067 // Make sure selection mode is engaged. 11068 if (mEditor != null) { 11069 mEditor.startSelectionActionModeAsync(false); 11070 } 11071 return true; 11072 } 11073 } 11074 } return false; 11075 case AccessibilityNodeInfo.ACTION_NEXT_AT_MOVEMENT_GRANULARITY: 11076 case AccessibilityNodeInfo.ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: { 11077 ensureIterableTextForAccessibilitySelectable(); 11078 return super.performAccessibilityActionInternal(action, arguments); 11079 } 11080 case ACCESSIBILITY_ACTION_SHARE: { 11081 if (isFocused() && canShare()) { 11082 if (onTextContextMenuItem(ID_SHARE)) { 11083 return true; 11084 } 11085 } 11086 } return false; 11087 case AccessibilityNodeInfo.ACTION_SET_TEXT: { 11088 if (!isEnabled() || (mBufferType != BufferType.EDITABLE)) { 11089 return false; 11090 } 11091 CharSequence text = (arguments != null) ? arguments.getCharSequence( 11092 AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE) : null; 11093 setText(text); 11094 if (mText != null) { 11095 int updatedTextLength = mText.length(); 11096 if (updatedTextLength > 0) { 11097 Selection.setSelection((Spannable) mText, updatedTextLength); 11098 } 11099 } 11100 } return true; 11101 default: { 11102 return super.performAccessibilityActionInternal(action, arguments); 11103 } 11104 } 11105 } 11106 11107 private boolean performAccessibilityActionClick(Bundle arguments) { 11108 boolean handled = false; 11109 11110 if (!isEnabled()) { 11111 return false; 11112 } 11113 11114 if (isClickable() || isLongClickable()) { 11115 // Simulate View.onTouchEvent for an ACTION_UP event 11116 if (isFocusable() && !isFocused()) { 11117 requestFocus(); 11118 } 11119 11120 performClick(); 11121 handled = true; 11122 } 11123 11124 // Show the IME, except when selecting in read-only text. 11125 if ((mMovement != null || onCheckIsTextEditor()) && hasSpannableText() && mLayout != null 11126 && (isTextEditable() || isTextSelectable()) && isFocused()) { 11127 final InputMethodManager imm = InputMethodManager.peekInstance(); 11128 viewClicked(imm); 11129 if (!isTextSelectable() && mEditor.mShowSoftInputOnFocus && imm != null) { 11130 handled |= imm.showSoftInput(this, 0); 11131 } 11132 } 11133 11134 return handled; 11135 } 11136 11137 private boolean hasSpannableText() { 11138 return mText != null && mText instanceof Spannable; 11139 } 11140 11141 /** @hide */ 11142 @Override 11143 public void sendAccessibilityEventInternal(int eventType) { 11144 if (eventType == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED && mEditor != null) { 11145 mEditor.mProcessTextIntentActionsHandler.initializeAccessibilityActions(); 11146 } 11147 11148 super.sendAccessibilityEventInternal(eventType); 11149 } 11150 11151 @Override 11152 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 11153 // Do not send scroll events since first they are not interesting for 11154 // accessibility and second such events a generated too frequently. 11155 // For details see the implementation of bringTextIntoView(). 11156 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) { 11157 return; 11158 } 11159 super.sendAccessibilityEventUnchecked(event); 11160 } 11161 11162 /** 11163 * Returns the text that should be exposed to accessibility services. 11164 * <p> 11165 * This approximates what is displayed visually. If the user has specified 11166 * that accessibility services should speak passwords, this method will 11167 * bypass any password transformation method and return unobscured text. 11168 * 11169 * @return the text that should be exposed to accessibility services, may 11170 * be {@code null} if no text is set 11171 */ 11172 @Nullable 11173 private CharSequence getTextForAccessibility() { 11174 // If the text is empty, we must be showing the hint text. 11175 if (TextUtils.isEmpty(mText)) { 11176 return mHint; 11177 } 11178 11179 // Otherwise, return whatever text is being displayed. 11180 return TextUtils.trimToParcelableSize(mTransformed); 11181 } 11182 11183 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 11184 int fromIndex, int removedCount, int addedCount) { 11185 AccessibilityEvent event = 11186 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 11187 event.setFromIndex(fromIndex); 11188 event.setRemovedCount(removedCount); 11189 event.setAddedCount(addedCount); 11190 event.setBeforeText(beforeText); 11191 sendAccessibilityEventUnchecked(event); 11192 } 11193 11194 /** 11195 * Returns whether this text view is a current input method target. The 11196 * default implementation just checks with {@link InputMethodManager}. 11197 * @return True if the TextView is a current input method target; false otherwise. 11198 */ 11199 public boolean isInputMethodTarget() { 11200 InputMethodManager imm = InputMethodManager.peekInstance(); 11201 return imm != null && imm.isActive(this); 11202 } 11203 11204 static final int ID_SELECT_ALL = android.R.id.selectAll; 11205 static final int ID_UNDO = android.R.id.undo; 11206 static final int ID_REDO = android.R.id.redo; 11207 static final int ID_CUT = android.R.id.cut; 11208 static final int ID_COPY = android.R.id.copy; 11209 static final int ID_PASTE = android.R.id.paste; 11210 static final int ID_SHARE = android.R.id.shareText; 11211 static final int ID_PASTE_AS_PLAIN_TEXT = android.R.id.pasteAsPlainText; 11212 static final int ID_REPLACE = android.R.id.replaceText; 11213 static final int ID_ASSIST = android.R.id.textAssist; 11214 static final int ID_AUTOFILL = android.R.id.autofill; 11215 11216 /** 11217 * Called when a context menu option for the text view is selected. Currently 11218 * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut}, 11219 * {@link android.R.id#copy}, {@link android.R.id#paste} or {@link android.R.id#shareText}. 11220 * 11221 * @return true if the context menu item action was performed. 11222 */ 11223 public boolean onTextContextMenuItem(int id) { 11224 int min = 0; 11225 int max = mText.length(); 11226 11227 if (isFocused()) { 11228 final int selStart = getSelectionStart(); 11229 final int selEnd = getSelectionEnd(); 11230 11231 min = Math.max(0, Math.min(selStart, selEnd)); 11232 max = Math.max(0, Math.max(selStart, selEnd)); 11233 } 11234 11235 switch (id) { 11236 case ID_SELECT_ALL: 11237 final boolean hadSelection = hasSelection(); 11238 selectAllText(); 11239 if (mEditor != null && hadSelection) { 11240 mEditor.invalidateActionModeAsync(); 11241 } 11242 return true; 11243 11244 case ID_UNDO: 11245 if (mEditor != null) { 11246 mEditor.undo(); 11247 } 11248 return true; // Returns true even if nothing was undone. 11249 11250 case ID_REDO: 11251 if (mEditor != null) { 11252 mEditor.redo(); 11253 } 11254 return true; // Returns true even if nothing was undone. 11255 11256 case ID_PASTE: 11257 paste(min, max, true /* withFormatting */); 11258 return true; 11259 11260 case ID_PASTE_AS_PLAIN_TEXT: 11261 paste(min, max, false /* withFormatting */); 11262 return true; 11263 11264 case ID_CUT: 11265 final ClipData cutData = ClipData.newPlainText(null, getTransformedText(min, max)); 11266 if (setPrimaryClip(cutData)) { 11267 deleteText_internal(min, max); 11268 } else { 11269 Toast.makeText(getContext(), 11270 com.android.internal.R.string.failed_to_copy_to_clipboard, 11271 Toast.LENGTH_SHORT).show(); 11272 } 11273 return true; 11274 11275 case ID_COPY: 11276 // For link action mode in a non-selectable/non-focusable TextView, 11277 // make sure that we set the appropriate min/max. 11278 final int selStart = getSelectionStart(); 11279 final int selEnd = getSelectionEnd(); 11280 min = Math.max(0, Math.min(selStart, selEnd)); 11281 max = Math.max(0, Math.max(selStart, selEnd)); 11282 final ClipData copyData = ClipData.newPlainText(null, getTransformedText(min, max)); 11283 if (setPrimaryClip(copyData)) { 11284 stopTextActionMode(); 11285 } else { 11286 Toast.makeText(getContext(), 11287 com.android.internal.R.string.failed_to_copy_to_clipboard, 11288 Toast.LENGTH_SHORT).show(); 11289 } 11290 return true; 11291 11292 case ID_REPLACE: 11293 if (mEditor != null) { 11294 mEditor.replace(); 11295 } 11296 return true; 11297 11298 case ID_SHARE: 11299 shareSelectedText(); 11300 return true; 11301 11302 case ID_AUTOFILL: 11303 requestAutofill(); 11304 stopTextActionMode(); 11305 return true; 11306 } 11307 return false; 11308 } 11309 11310 CharSequence getTransformedText(int start, int end) { 11311 return removeSuggestionSpans(mTransformed.subSequence(start, end)); 11312 } 11313 11314 @Override 11315 public boolean performLongClick() { 11316 boolean handled = false; 11317 boolean performedHapticFeedback = false; 11318 11319 if (mEditor != null) { 11320 mEditor.mIsBeingLongClicked = true; 11321 } 11322 11323 if (super.performLongClick()) { 11324 handled = true; 11325 performedHapticFeedback = true; 11326 } 11327 11328 if (mEditor != null) { 11329 handled |= mEditor.performLongClick(handled); 11330 mEditor.mIsBeingLongClicked = false; 11331 } 11332 11333 if (handled) { 11334 if (!performedHapticFeedback) { 11335 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 11336 } 11337 if (mEditor != null) mEditor.mDiscardNextActionUp = true; 11338 } else { 11339 MetricsLogger.action( 11340 mContext, 11341 MetricsEvent.TEXT_LONGPRESS, 11342 TextViewMetrics.SUBTYPE_LONG_PRESS_OTHER); 11343 } 11344 11345 return handled; 11346 } 11347 11348 @Override 11349 protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { 11350 super.onScrollChanged(horiz, vert, oldHoriz, oldVert); 11351 if (mEditor != null) { 11352 mEditor.onScrollChanged(); 11353 } 11354 } 11355 11356 /** 11357 * Return whether or not suggestions are enabled on this TextView. The suggestions are generated 11358 * by the IME or by the spell checker as the user types. This is done by adding 11359 * {@link SuggestionSpan}s to the text. 11360 * 11361 * When suggestions are enabled (default), this list of suggestions will be displayed when the 11362 * user asks for them on these parts of the text. This value depends on the inputType of this 11363 * TextView. 11364 * 11365 * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}. 11366 * 11367 * In addition, the type variation must be one of 11368 * {@link InputType#TYPE_TEXT_VARIATION_NORMAL}, 11369 * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, 11370 * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, 11371 * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or 11372 * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. 11373 * 11374 * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set. 11375 * 11376 * @return true if the suggestions popup window is enabled, based on the inputType. 11377 */ 11378 public boolean isSuggestionsEnabled() { 11379 if (mEditor == null) return false; 11380 if ((mEditor.mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) { 11381 return false; 11382 } 11383 if ((mEditor.mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false; 11384 11385 final int variation = mEditor.mInputType & EditorInfo.TYPE_MASK_VARIATION; 11386 return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL 11387 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT 11388 || variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE 11389 || variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE 11390 || variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT); 11391 } 11392 11393 /** 11394 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 11395 * selection is initiated in this View. 11396 * 11397 * <p>The standard implementation populates the menu with a subset of Select All, Cut, Copy, 11398 * Paste, Replace and Share actions, depending on what this View supports. 11399 * 11400 * <p>A custom implementation can add new entries in the default menu in its 11401 * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, android.view.Menu)} 11402 * method. The default actions can also be removed from the menu using 11403 * {@link android.view.Menu#removeItem(int)} and passing {@link android.R.id#selectAll}, 11404 * {@link android.R.id#cut}, {@link android.R.id#copy}, {@link android.R.id#paste}, 11405 * {@link android.R.id#replaceText} or {@link android.R.id#shareText} ids as parameters. 11406 * 11407 * <p>Returning false from 11408 * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, android.view.Menu)} 11409 * will prevent the action mode from being started. 11410 * 11411 * <p>Action click events should be handled by the custom implementation of 11412 * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, 11413 * android.view.MenuItem)}. 11414 * 11415 * <p>Note that text selection mode is not started when a TextView receives focus and the 11416 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 11417 * that case, to allow for quick replacement. 11418 */ 11419 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 11420 createEditorIfNeeded(); 11421 mEditor.mCustomSelectionActionModeCallback = actionModeCallback; 11422 } 11423 11424 /** 11425 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 11426 * 11427 * @return The current custom selection callback. 11428 */ 11429 public ActionMode.Callback getCustomSelectionActionModeCallback() { 11430 return mEditor == null ? null : mEditor.mCustomSelectionActionModeCallback; 11431 } 11432 11433 /** 11434 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 11435 * insertion is initiated in this View. 11436 * The standard implementation populates the menu with a subset of Select All, 11437 * Paste and Replace actions, depending on what this View supports. 11438 * 11439 * <p>A custom implementation can add new entries in the default menu in its 11440 * {@link android.view.ActionMode.Callback#onPrepareActionMode(android.view.ActionMode, 11441 * android.view.Menu)} method. The default actions can also be removed from the menu using 11442 * {@link android.view.Menu#removeItem(int)} and passing {@link android.R.id#selectAll}, 11443 * {@link android.R.id#paste} or {@link android.R.id#replaceText} ids as parameters.</p> 11444 * 11445 * <p>Returning false from 11446 * {@link android.view.ActionMode.Callback#onCreateActionMode(android.view.ActionMode, 11447 * android.view.Menu)} will prevent the action mode from being started.</p> 11448 * 11449 * <p>Action click events should be handled by the custom implementation of 11450 * {@link android.view.ActionMode.Callback#onActionItemClicked(android.view.ActionMode, 11451 * android.view.MenuItem)}.</p> 11452 * 11453 * <p>Note that text insertion mode is not started when a TextView receives focus and the 11454 * {@link android.R.attr#selectAllOnFocus} flag has been set.</p> 11455 */ 11456 public void setCustomInsertionActionModeCallback(ActionMode.Callback actionModeCallback) { 11457 createEditorIfNeeded(); 11458 mEditor.mCustomInsertionActionModeCallback = actionModeCallback; 11459 } 11460 11461 /** 11462 * Retrieves the value set in {@link #setCustomInsertionActionModeCallback}. Default is null. 11463 * 11464 * @return The current custom insertion callback. 11465 */ 11466 public ActionMode.Callback getCustomInsertionActionModeCallback() { 11467 return mEditor == null ? null : mEditor.mCustomInsertionActionModeCallback; 11468 } 11469 11470 /** 11471 * Sets the {@link TextClassifier} for this TextView. 11472 */ 11473 public void setTextClassifier(@Nullable TextClassifier textClassifier) { 11474 mTextClassifier = textClassifier; 11475 } 11476 11477 /** 11478 * Returns the {@link TextClassifier} used by this TextView. 11479 * If no TextClassifier has been set, this TextView uses the default set by the 11480 * {@link TextClassificationManager}. 11481 */ 11482 @NonNull 11483 public TextClassifier getTextClassifier() { 11484 if (mTextClassifier == null) { 11485 TextClassificationManager tcm = 11486 mContext.getSystemService(TextClassificationManager.class); 11487 if (tcm != null) { 11488 mTextClassifier = tcm.getTextClassifier(); 11489 } else { 11490 mTextClassifier = TextClassifier.NO_OP; 11491 } 11492 } 11493 return mTextClassifier; 11494 } 11495 11496 /** 11497 * Starts an ActionMode for the specified TextLink. 11498 * 11499 * @return Whether or not we're attempting to start the action mode. 11500 * @hide 11501 */ 11502 public boolean requestActionMode(@NonNull TextLinks.TextLink link) { 11503 Preconditions.checkNotNull(link); 11504 createEditorIfNeeded(); 11505 mEditor.startLinkActionModeAsync(link); 11506 return true; 11507 } 11508 /** 11509 * @hide 11510 */ 11511 protected void stopTextActionMode() { 11512 if (mEditor != null) { 11513 mEditor.stopTextActionMode(); 11514 } 11515 } 11516 11517 boolean canUndo() { 11518 return mEditor != null && mEditor.canUndo(); 11519 } 11520 11521 boolean canRedo() { 11522 return mEditor != null && mEditor.canRedo(); 11523 } 11524 11525 boolean canCut() { 11526 if (hasPasswordTransformationMethod()) { 11527 return false; 11528 } 11529 11530 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mEditor != null 11531 && mEditor.mKeyListener != null) { 11532 return true; 11533 } 11534 11535 return false; 11536 } 11537 11538 boolean canCopy() { 11539 if (hasPasswordTransformationMethod()) { 11540 return false; 11541 } 11542 11543 if (mText.length() > 0 && hasSelection() && mEditor != null) { 11544 return true; 11545 } 11546 11547 return false; 11548 } 11549 11550 boolean canShare() { 11551 if (!getContext().canStartActivityForResult() || !isDeviceProvisioned()) { 11552 return false; 11553 } 11554 return canCopy(); 11555 } 11556 11557 boolean isDeviceProvisioned() { 11558 if (mDeviceProvisionedState == DEVICE_PROVISIONED_UNKNOWN) { 11559 mDeviceProvisionedState = Settings.Global.getInt( 11560 mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 0 11561 ? DEVICE_PROVISIONED_YES 11562 : DEVICE_PROVISIONED_NO; 11563 } 11564 return mDeviceProvisionedState == DEVICE_PROVISIONED_YES; 11565 } 11566 11567 boolean canPaste() { 11568 return (mText instanceof Editable 11569 && mEditor != null && mEditor.mKeyListener != null 11570 && getSelectionStart() >= 0 11571 && getSelectionEnd() >= 0 11572 && ((ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE)) 11573 .hasPrimaryClip()); 11574 } 11575 11576 boolean canPasteAsPlainText() { 11577 if (!canPaste()) { 11578 return false; 11579 } 11580 11581 final ClipData clipData = 11582 ((ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE)) 11583 .getPrimaryClip(); 11584 final ClipDescription description = clipData.getDescription(); 11585 final boolean isPlainType = description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN); 11586 final CharSequence text = clipData.getItemAt(0).getText(); 11587 if (isPlainType && (text instanceof Spanned)) { 11588 Spanned spanned = (Spanned) text; 11589 if (TextUtils.hasStyleSpan(spanned)) { 11590 return true; 11591 } 11592 } 11593 return description.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML); 11594 } 11595 11596 boolean canProcessText() { 11597 if (getId() == View.NO_ID) { 11598 return false; 11599 } 11600 return canShare(); 11601 } 11602 11603 boolean canSelectAllText() { 11604 return canSelectText() && !hasPasswordTransformationMethod() 11605 && !(getSelectionStart() == 0 && getSelectionEnd() == mText.length()); 11606 } 11607 11608 boolean selectAllText() { 11609 if (mEditor != null) { 11610 // Hide the toolbar before changing the selection to avoid flickering. 11611 mEditor.hideFloatingToolbar(FLOATING_TOOLBAR_SELECT_ALL_REFRESH_DELAY); 11612 } 11613 final int length = mText.length(); 11614 Selection.setSelection((Spannable) mText, 0, length); 11615 return length > 0; 11616 } 11617 11618 void replaceSelectionWithText(CharSequence text) { 11619 ((Editable) mText).replace(getSelectionStart(), getSelectionEnd(), text); 11620 } 11621 11622 /** 11623 * Paste clipboard content between min and max positions. 11624 */ 11625 private void paste(int min, int max, boolean withFormatting) { 11626 ClipboardManager clipboard = 11627 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 11628 ClipData clip = clipboard.getPrimaryClip(); 11629 if (clip != null) { 11630 boolean didFirst = false; 11631 for (int i = 0; i < clip.getItemCount(); i++) { 11632 final CharSequence paste; 11633 if (withFormatting) { 11634 paste = clip.getItemAt(i).coerceToStyledText(getContext()); 11635 } else { 11636 // Get an item as text and remove all spans by toString(). 11637 final CharSequence text = clip.getItemAt(i).coerceToText(getContext()); 11638 paste = (text instanceof Spanned) ? text.toString() : text; 11639 } 11640 if (paste != null) { 11641 if (!didFirst) { 11642 Selection.setSelection((Spannable) mText, max); 11643 ((Editable) mText).replace(min, max, paste); 11644 didFirst = true; 11645 } else { 11646 ((Editable) mText).insert(getSelectionEnd(), "\n"); 11647 ((Editable) mText).insert(getSelectionEnd(), paste); 11648 } 11649 } 11650 } 11651 sLastCutCopyOrTextChangedTime = 0; 11652 } 11653 } 11654 11655 private void shareSelectedText() { 11656 String selectedText = getSelectedText(); 11657 if (selectedText != null && !selectedText.isEmpty()) { 11658 Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 11659 sharingIntent.setType("text/plain"); 11660 sharingIntent.removeExtra(android.content.Intent.EXTRA_TEXT); 11661 selectedText = TextUtils.trimToParcelableSize(selectedText); 11662 sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, selectedText); 11663 getContext().startActivity(Intent.createChooser(sharingIntent, null)); 11664 Selection.setSelection((Spannable) mText, getSelectionEnd()); 11665 } 11666 } 11667 11668 @CheckResult 11669 private boolean setPrimaryClip(ClipData clip) { 11670 ClipboardManager clipboard = 11671 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 11672 try { 11673 clipboard.setPrimaryClip(clip); 11674 } catch (Throwable t) { 11675 return false; 11676 } 11677 sLastCutCopyOrTextChangedTime = SystemClock.uptimeMillis(); 11678 return true; 11679 } 11680 11681 /** 11682 * Get the character offset closest to the specified absolute position. A typical use case is to 11683 * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. 11684 * 11685 * @param x The horizontal absolute position of a point on screen 11686 * @param y The vertical absolute position of a point on screen 11687 * @return the character offset for the character whose position is closest to the specified 11688 * position. Returns -1 if there is no layout. 11689 */ 11690 public int getOffsetForPosition(float x, float y) { 11691 if (getLayout() == null) return -1; 11692 final int line = getLineAtCoordinate(y); 11693 final int offset = getOffsetAtCoordinate(line, x); 11694 return offset; 11695 } 11696 11697 float convertToLocalHorizontalCoordinate(float x) { 11698 x -= getTotalPaddingLeft(); 11699 // Clamp the position to inside of the view. 11700 x = Math.max(0.0f, x); 11701 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 11702 x += getScrollX(); 11703 return x; 11704 } 11705 11706 int getLineAtCoordinate(float y) { 11707 y -= getTotalPaddingTop(); 11708 // Clamp the position to inside of the view. 11709 y = Math.max(0.0f, y); 11710 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 11711 y += getScrollY(); 11712 return getLayout().getLineForVertical((int) y); 11713 } 11714 11715 int getLineAtCoordinateUnclamped(float y) { 11716 y -= getTotalPaddingTop(); 11717 y += getScrollY(); 11718 return getLayout().getLineForVertical((int) y); 11719 } 11720 11721 int getOffsetAtCoordinate(int line, float x) { 11722 x = convertToLocalHorizontalCoordinate(x); 11723 return getLayout().getOffsetForHorizontal(line, x); 11724 } 11725 11726 @Override 11727 public boolean onDragEvent(DragEvent event) { 11728 switch (event.getAction()) { 11729 case DragEvent.ACTION_DRAG_STARTED: 11730 return mEditor != null && mEditor.hasInsertionController(); 11731 11732 case DragEvent.ACTION_DRAG_ENTERED: 11733 TextView.this.requestFocus(); 11734 return true; 11735 11736 case DragEvent.ACTION_DRAG_LOCATION: 11737 if (mText instanceof Spannable) { 11738 final int offset = getOffsetForPosition(event.getX(), event.getY()); 11739 Selection.setSelection((Spannable) mText, offset); 11740 } 11741 return true; 11742 11743 case DragEvent.ACTION_DROP: 11744 if (mEditor != null) mEditor.onDrop(event); 11745 return true; 11746 11747 case DragEvent.ACTION_DRAG_ENDED: 11748 case DragEvent.ACTION_DRAG_EXITED: 11749 default: 11750 return true; 11751 } 11752 } 11753 11754 boolean isInBatchEditMode() { 11755 if (mEditor == null) return false; 11756 final Editor.InputMethodState ims = mEditor.mInputMethodState; 11757 if (ims != null) { 11758 return ims.mBatchEditNesting > 0; 11759 } 11760 return mEditor.mInBatchEditControllers; 11761 } 11762 11763 @Override 11764 public void onRtlPropertiesChanged(int layoutDirection) { 11765 super.onRtlPropertiesChanged(layoutDirection); 11766 11767 final TextDirectionHeuristic newTextDir = getTextDirectionHeuristic(); 11768 if (mTextDir != newTextDir) { 11769 mTextDir = newTextDir; 11770 if (mLayout != null) { 11771 checkForRelayout(); 11772 } 11773 } 11774 } 11775 11776 /** 11777 * Returns the current {@link TextDirectionHeuristic}. 11778 * 11779 * @return the current {@link TextDirectionHeuristic}. 11780 * @hide 11781 */ 11782 protected TextDirectionHeuristic getTextDirectionHeuristic() { 11783 if (hasPasswordTransformationMethod()) { 11784 // passwords fields should be LTR 11785 return TextDirectionHeuristics.LTR; 11786 } 11787 11788 if (mEditor != null 11789 && (mEditor.mInputType & EditorInfo.TYPE_MASK_CLASS) 11790 == EditorInfo.TYPE_CLASS_PHONE) { 11791 // Phone numbers must be in the direction of the locale's digits. Most locales have LTR 11792 // digits, but some locales, such as those written in the Adlam or N'Ko scripts, have 11793 // RTL digits. 11794 final DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(getTextLocale()); 11795 final String zero = symbols.getDigitStrings()[0]; 11796 // In case the zero digit is multi-codepoint, just use the first codepoint to determine 11797 // direction. 11798 final int firstCodepoint = zero.codePointAt(0); 11799 final byte digitDirection = Character.getDirectionality(firstCodepoint); 11800 if (digitDirection == Character.DIRECTIONALITY_RIGHT_TO_LEFT 11801 || digitDirection == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC) { 11802 return TextDirectionHeuristics.RTL; 11803 } else { 11804 return TextDirectionHeuristics.LTR; 11805 } 11806 } 11807 11808 // Always need to resolve layout direction first 11809 final boolean defaultIsRtl = (getLayoutDirection() == LAYOUT_DIRECTION_RTL); 11810 11811 // Now, we can select the heuristic 11812 switch (getTextDirection()) { 11813 default: 11814 case TEXT_DIRECTION_FIRST_STRONG: 11815 return (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL : 11816 TextDirectionHeuristics.FIRSTSTRONG_LTR); 11817 case TEXT_DIRECTION_ANY_RTL: 11818 return TextDirectionHeuristics.ANYRTL_LTR; 11819 case TEXT_DIRECTION_LTR: 11820 return TextDirectionHeuristics.LTR; 11821 case TEXT_DIRECTION_RTL: 11822 return TextDirectionHeuristics.RTL; 11823 case TEXT_DIRECTION_LOCALE: 11824 return TextDirectionHeuristics.LOCALE; 11825 case TEXT_DIRECTION_FIRST_STRONG_LTR: 11826 return TextDirectionHeuristics.FIRSTSTRONG_LTR; 11827 case TEXT_DIRECTION_FIRST_STRONG_RTL: 11828 return TextDirectionHeuristics.FIRSTSTRONG_RTL; 11829 } 11830 } 11831 11832 /** 11833 * @hide 11834 */ 11835 @Override 11836 public void onResolveDrawables(int layoutDirection) { 11837 // No need to resolve twice 11838 if (mLastLayoutDirection == layoutDirection) { 11839 return; 11840 } 11841 mLastLayoutDirection = layoutDirection; 11842 11843 // Resolve drawables 11844 if (mDrawables != null) { 11845 if (mDrawables.resolveWithLayoutDirection(layoutDirection)) { 11846 prepareDrawableForDisplay(mDrawables.mShowing[Drawables.LEFT]); 11847 prepareDrawableForDisplay(mDrawables.mShowing[Drawables.RIGHT]); 11848 applyCompoundDrawableTint(); 11849 } 11850 } 11851 } 11852 11853 /** 11854 * Prepares a drawable for display by propagating layout direction and 11855 * drawable state. 11856 * 11857 * @param dr the drawable to prepare 11858 */ 11859 private void prepareDrawableForDisplay(@Nullable Drawable dr) { 11860 if (dr == null) { 11861 return; 11862 } 11863 11864 dr.setLayoutDirection(getLayoutDirection()); 11865 11866 if (dr.isStateful()) { 11867 dr.setState(getDrawableState()); 11868 dr.jumpToCurrentState(); 11869 } 11870 } 11871 11872 /** 11873 * @hide 11874 */ 11875 protected void resetResolvedDrawables() { 11876 super.resetResolvedDrawables(); 11877 mLastLayoutDirection = -1; 11878 } 11879 11880 /** 11881 * @hide 11882 */ 11883 protected void viewClicked(InputMethodManager imm) { 11884 if (imm != null) { 11885 imm.viewClicked(this); 11886 } 11887 } 11888 11889 /** 11890 * Deletes the range of text [start, end[. 11891 * @hide 11892 */ 11893 protected void deleteText_internal(int start, int end) { 11894 ((Editable) mText).delete(start, end); 11895 } 11896 11897 /** 11898 * Replaces the range of text [start, end[ by replacement text 11899 * @hide 11900 */ 11901 protected void replaceText_internal(int start, int end, CharSequence text) { 11902 ((Editable) mText).replace(start, end, text); 11903 } 11904 11905 /** 11906 * Sets a span on the specified range of text 11907 * @hide 11908 */ 11909 protected void setSpan_internal(Object span, int start, int end, int flags) { 11910 ((Editable) mText).setSpan(span, start, end, flags); 11911 } 11912 11913 /** 11914 * Moves the cursor to the specified offset position in text 11915 * @hide 11916 */ 11917 protected void setCursorPosition_internal(int start, int end) { 11918 Selection.setSelection(((Editable) mText), start, end); 11919 } 11920 11921 /** 11922 * An Editor should be created as soon as any of the editable-specific fields (grouped 11923 * inside the Editor object) is assigned to a non-default value. 11924 * This method will create the Editor if needed. 11925 * 11926 * A standard TextView (as well as buttons, checkboxes...) should not qualify and hence will 11927 * have a null Editor, unlike an EditText. Inconsistent in-between states will have an 11928 * Editor for backward compatibility, as soon as one of these fields is assigned. 11929 * 11930 * Also note that for performance reasons, the mEditor is created when needed, but not 11931 * reset when no more edit-specific fields are needed. 11932 */ 11933 private void createEditorIfNeeded() { 11934 if (mEditor == null) { 11935 mEditor = new Editor(this); 11936 } 11937 } 11938 11939 /** 11940 * @hide 11941 */ 11942 @Override 11943 public CharSequence getIterableTextForAccessibility() { 11944 return mText; 11945 } 11946 11947 private void ensureIterableTextForAccessibilitySelectable() { 11948 if (!(mText instanceof Spannable)) { 11949 setText(mText, BufferType.SPANNABLE); 11950 } 11951 } 11952 11953 /** 11954 * @hide 11955 */ 11956 @Override 11957 public TextSegmentIterator getIteratorForGranularity(int granularity) { 11958 switch (granularity) { 11959 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_LINE: { 11960 Spannable text = (Spannable) getIterableTextForAccessibility(); 11961 if (!TextUtils.isEmpty(text) && getLayout() != null) { 11962 AccessibilityIterators.LineTextSegmentIterator iterator = 11963 AccessibilityIterators.LineTextSegmentIterator.getInstance(); 11964 iterator.initialize(text, getLayout()); 11965 return iterator; 11966 } 11967 } break; 11968 case AccessibilityNodeInfo.MOVEMENT_GRANULARITY_PAGE: { 11969 Spannable text = (Spannable) getIterableTextForAccessibility(); 11970 if (!TextUtils.isEmpty(text) && getLayout() != null) { 11971 AccessibilityIterators.PageTextSegmentIterator iterator = 11972 AccessibilityIterators.PageTextSegmentIterator.getInstance(); 11973 iterator.initialize(this); 11974 return iterator; 11975 } 11976 } break; 11977 } 11978 return super.getIteratorForGranularity(granularity); 11979 } 11980 11981 /** 11982 * @hide 11983 */ 11984 @Override 11985 public int getAccessibilitySelectionStart() { 11986 return getSelectionStart(); 11987 } 11988 11989 /** 11990 * @hide 11991 */ 11992 public boolean isAccessibilitySelectionExtendable() { 11993 return true; 11994 } 11995 11996 /** 11997 * @hide 11998 */ 11999 @Override 12000 public int getAccessibilitySelectionEnd() { 12001 return getSelectionEnd(); 12002 } 12003 12004 /** 12005 * @hide 12006 */ 12007 @Override 12008 public void setAccessibilitySelection(int start, int end) { 12009 if (getAccessibilitySelectionStart() == start 12010 && getAccessibilitySelectionEnd() == end) { 12011 return; 12012 } 12013 CharSequence text = getIterableTextForAccessibility(); 12014 if (Math.min(start, end) >= 0 && Math.max(start, end) <= text.length()) { 12015 Selection.setSelection((Spannable) text, start, end); 12016 } else { 12017 Selection.removeSelection((Spannable) text); 12018 } 12019 // Hide all selection controllers used for adjusting selection 12020 // since we are doing so explicitlty by other means and these 12021 // controllers interact with how selection behaves. 12022 if (mEditor != null) { 12023 mEditor.hideCursorAndSpanControllers(); 12024 mEditor.stopTextActionMode(); 12025 } 12026 } 12027 12028 /** @hide */ 12029 @Override 12030 protected void encodeProperties(@NonNull ViewHierarchyEncoder stream) { 12031 super.encodeProperties(stream); 12032 12033 TruncateAt ellipsize = getEllipsize(); 12034 stream.addProperty("text:ellipsize", ellipsize == null ? null : ellipsize.name()); 12035 stream.addProperty("text:textSize", getTextSize()); 12036 stream.addProperty("text:scaledTextSize", getScaledTextSize()); 12037 stream.addProperty("text:typefaceStyle", getTypefaceStyle()); 12038 stream.addProperty("text:selectionStart", getSelectionStart()); 12039 stream.addProperty("text:selectionEnd", getSelectionEnd()); 12040 stream.addProperty("text:curTextColor", mCurTextColor); 12041 stream.addProperty("text:text", mText == null ? null : mText.toString()); 12042 stream.addProperty("text:gravity", mGravity); 12043 } 12044 12045 /** 12046 * User interface state that is stored by TextView for implementing 12047 * {@link View#onSaveInstanceState}. 12048 */ 12049 public static class SavedState extends BaseSavedState { 12050 int selStart = -1; 12051 int selEnd = -1; 12052 CharSequence text; 12053 boolean frozenWithFocus; 12054 CharSequence error; 12055 ParcelableParcel editorState; // Optional state from Editor. 12056 12057 SavedState(Parcelable superState) { 12058 super(superState); 12059 } 12060 12061 @Override 12062 public void writeToParcel(Parcel out, int flags) { 12063 super.writeToParcel(out, flags); 12064 out.writeInt(selStart); 12065 out.writeInt(selEnd); 12066 out.writeInt(frozenWithFocus ? 1 : 0); 12067 TextUtils.writeToParcel(text, out, flags); 12068 12069 if (error == null) { 12070 out.writeInt(0); 12071 } else { 12072 out.writeInt(1); 12073 TextUtils.writeToParcel(error, out, flags); 12074 } 12075 12076 if (editorState == null) { 12077 out.writeInt(0); 12078 } else { 12079 out.writeInt(1); 12080 editorState.writeToParcel(out, flags); 12081 } 12082 } 12083 12084 @Override 12085 public String toString() { 12086 String str = "TextView.SavedState{" 12087 + Integer.toHexString(System.identityHashCode(this)) 12088 + " start=" + selStart + " end=" + selEnd; 12089 if (text != null) { 12090 str += " text=" + text; 12091 } 12092 return str + "}"; 12093 } 12094 12095 @SuppressWarnings("hiding") 12096 public static final Parcelable.Creator<SavedState> CREATOR = 12097 new Parcelable.Creator<SavedState>() { 12098 public SavedState createFromParcel(Parcel in) { 12099 return new SavedState(in); 12100 } 12101 12102 public SavedState[] newArray(int size) { 12103 return new SavedState[size]; 12104 } 12105 }; 12106 12107 private SavedState(Parcel in) { 12108 super(in); 12109 selStart = in.readInt(); 12110 selEnd = in.readInt(); 12111 frozenWithFocus = (in.readInt() != 0); 12112 text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 12113 12114 if (in.readInt() != 0) { 12115 error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 12116 } 12117 12118 if (in.readInt() != 0) { 12119 editorState = ParcelableParcel.CREATOR.createFromParcel(in); 12120 } 12121 } 12122 } 12123 12124 private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations { 12125 private char[] mChars; 12126 private int mStart, mLength; 12127 12128 public CharWrapper(char[] chars, int start, int len) { 12129 mChars = chars; 12130 mStart = start; 12131 mLength = len; 12132 } 12133 12134 /* package */ void set(char[] chars, int start, int len) { 12135 mChars = chars; 12136 mStart = start; 12137 mLength = len; 12138 } 12139 12140 public int length() { 12141 return mLength; 12142 } 12143 12144 public char charAt(int off) { 12145 return mChars[off + mStart]; 12146 } 12147 12148 @Override 12149 public String toString() { 12150 return new String(mChars, mStart, mLength); 12151 } 12152 12153 public CharSequence subSequence(int start, int end) { 12154 if (start < 0 || end < 0 || start > mLength || end > mLength) { 12155 throw new IndexOutOfBoundsException(start + ", " + end); 12156 } 12157 12158 return new String(mChars, start + mStart, end - start); 12159 } 12160 12161 public void getChars(int start, int end, char[] buf, int off) { 12162 if (start < 0 || end < 0 || start > mLength || end > mLength) { 12163 throw new IndexOutOfBoundsException(start + ", " + end); 12164 } 12165 12166 System.arraycopy(mChars, start + mStart, buf, off, end - start); 12167 } 12168 12169 @Override 12170 public void drawText(BaseCanvas c, int start, int end, 12171 float x, float y, Paint p) { 12172 c.drawText(mChars, start + mStart, end - start, x, y, p); 12173 } 12174 12175 @Override 12176 public void drawTextRun(BaseCanvas c, int start, int end, 12177 int contextStart, int contextEnd, float x, float y, boolean isRtl, Paint p) { 12178 int count = end - start; 12179 int contextCount = contextEnd - contextStart; 12180 c.drawTextRun(mChars, start + mStart, count, contextStart + mStart, 12181 contextCount, x, y, isRtl, p); 12182 } 12183 12184 public float measureText(int start, int end, Paint p) { 12185 return p.measureText(mChars, start + mStart, end - start); 12186 } 12187 12188 public int getTextWidths(int start, int end, float[] widths, Paint p) { 12189 return p.getTextWidths(mChars, start + mStart, end - start, widths); 12190 } 12191 12192 public float getTextRunAdvances(int start, int end, int contextStart, 12193 int contextEnd, boolean isRtl, float[] advances, int advancesIndex, 12194 Paint p) { 12195 int count = end - start; 12196 int contextCount = contextEnd - contextStart; 12197 return p.getTextRunAdvances(mChars, start + mStart, count, 12198 contextStart + mStart, contextCount, isRtl, advances, 12199 advancesIndex); 12200 } 12201 12202 public int getTextRunCursor(int contextStart, int contextEnd, int dir, 12203 int offset, int cursorOpt, Paint p) { 12204 int contextCount = contextEnd - contextStart; 12205 return p.getTextRunCursor(mChars, contextStart + mStart, 12206 contextCount, dir, offset + mStart, cursorOpt); 12207 } 12208 } 12209 12210 private static final class Marquee { 12211 // TODO: Add an option to configure this 12212 private static final float MARQUEE_DELTA_MAX = 0.07f; 12213 private static final int MARQUEE_DELAY = 1200; 12214 private static final int MARQUEE_DP_PER_SECOND = 30; 12215 12216 private static final byte MARQUEE_STOPPED = 0x0; 12217 private static final byte MARQUEE_STARTING = 0x1; 12218 private static final byte MARQUEE_RUNNING = 0x2; 12219 12220 private final WeakReference<TextView> mView; 12221 private final Choreographer mChoreographer; 12222 12223 private byte mStatus = MARQUEE_STOPPED; 12224 private final float mPixelsPerMs; 12225 private float mMaxScroll; 12226 private float mMaxFadeScroll; 12227 private float mGhostStart; 12228 private float mGhostOffset; 12229 private float mFadeStop; 12230 private int mRepeatLimit; 12231 12232 private float mScroll; 12233 private long mLastAnimationMs; 12234 12235 Marquee(TextView v) { 12236 final float density = v.getContext().getResources().getDisplayMetrics().density; 12237 mPixelsPerMs = MARQUEE_DP_PER_SECOND * density / 1000f; 12238 mView = new WeakReference<TextView>(v); 12239 mChoreographer = Choreographer.getInstance(); 12240 } 12241 12242 private Choreographer.FrameCallback mTickCallback = new Choreographer.FrameCallback() { 12243 @Override 12244 public void doFrame(long frameTimeNanos) { 12245 tick(); 12246 } 12247 }; 12248 12249 private Choreographer.FrameCallback mStartCallback = new Choreographer.FrameCallback() { 12250 @Override 12251 public void doFrame(long frameTimeNanos) { 12252 mStatus = MARQUEE_RUNNING; 12253 mLastAnimationMs = mChoreographer.getFrameTime(); 12254 tick(); 12255 } 12256 }; 12257 12258 private Choreographer.FrameCallback mRestartCallback = new Choreographer.FrameCallback() { 12259 @Override 12260 public void doFrame(long frameTimeNanos) { 12261 if (mStatus == MARQUEE_RUNNING) { 12262 if (mRepeatLimit >= 0) { 12263 mRepeatLimit--; 12264 } 12265 start(mRepeatLimit); 12266 } 12267 } 12268 }; 12269 12270 void tick() { 12271 if (mStatus != MARQUEE_RUNNING) { 12272 return; 12273 } 12274 12275 mChoreographer.removeFrameCallback(mTickCallback); 12276 12277 final TextView textView = mView.get(); 12278 if (textView != null && (textView.isFocused() || textView.isSelected())) { 12279 long currentMs = mChoreographer.getFrameTime(); 12280 long deltaMs = currentMs - mLastAnimationMs; 12281 mLastAnimationMs = currentMs; 12282 float deltaPx = deltaMs * mPixelsPerMs; 12283 mScroll += deltaPx; 12284 if (mScroll > mMaxScroll) { 12285 mScroll = mMaxScroll; 12286 mChoreographer.postFrameCallbackDelayed(mRestartCallback, MARQUEE_DELAY); 12287 } else { 12288 mChoreographer.postFrameCallback(mTickCallback); 12289 } 12290 textView.invalidate(); 12291 } 12292 } 12293 12294 void stop() { 12295 mStatus = MARQUEE_STOPPED; 12296 mChoreographer.removeFrameCallback(mStartCallback); 12297 mChoreographer.removeFrameCallback(mRestartCallback); 12298 mChoreographer.removeFrameCallback(mTickCallback); 12299 resetScroll(); 12300 } 12301 12302 private void resetScroll() { 12303 mScroll = 0.0f; 12304 final TextView textView = mView.get(); 12305 if (textView != null) textView.invalidate(); 12306 } 12307 12308 void start(int repeatLimit) { 12309 if (repeatLimit == 0) { 12310 stop(); 12311 return; 12312 } 12313 mRepeatLimit = repeatLimit; 12314 final TextView textView = mView.get(); 12315 if (textView != null && textView.mLayout != null) { 12316 mStatus = MARQUEE_STARTING; 12317 mScroll = 0.0f; 12318 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() 12319 - textView.getCompoundPaddingRight(); 12320 final float lineWidth = textView.mLayout.getLineWidth(0); 12321 final float gap = textWidth / 3.0f; 12322 mGhostStart = lineWidth - textWidth + gap; 12323 mMaxScroll = mGhostStart + textWidth; 12324 mGhostOffset = lineWidth + gap; 12325 mFadeStop = lineWidth + textWidth / 6.0f; 12326 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 12327 12328 textView.invalidate(); 12329 mChoreographer.postFrameCallback(mStartCallback); 12330 } 12331 } 12332 12333 float getGhostOffset() { 12334 return mGhostOffset; 12335 } 12336 12337 float getScroll() { 12338 return mScroll; 12339 } 12340 12341 float getMaxFadeScroll() { 12342 return mMaxFadeScroll; 12343 } 12344 12345 boolean shouldDrawLeftFade() { 12346 return mScroll <= mFadeStop; 12347 } 12348 12349 boolean shouldDrawGhost() { 12350 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 12351 } 12352 12353 boolean isRunning() { 12354 return mStatus == MARQUEE_RUNNING; 12355 } 12356 12357 boolean isStopped() { 12358 return mStatus == MARQUEE_STOPPED; 12359 } 12360 } 12361 12362 private class ChangeWatcher implements TextWatcher, SpanWatcher { 12363 12364 private CharSequence mBeforeText; 12365 12366 public void beforeTextChanged(CharSequence buffer, int start, 12367 int before, int after) { 12368 if (DEBUG_EXTRACT) { 12369 Log.v(LOG_TAG, "beforeTextChanged start=" + start 12370 + " before=" + before + " after=" + after + ": " + buffer); 12371 } 12372 12373 if (AccessibilityManager.getInstance(mContext).isEnabled() 12374 && !isPasswordInputType(getInputType()) && !hasPasswordTransformationMethod()) { 12375 mBeforeText = buffer.toString(); 12376 } 12377 12378 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 12379 } 12380 12381 public void onTextChanged(CharSequence buffer, int start, int before, int after) { 12382 if (DEBUG_EXTRACT) { 12383 Log.v(LOG_TAG, "onTextChanged start=" + start 12384 + " before=" + before + " after=" + after + ": " + buffer); 12385 } 12386 TextView.this.handleTextChanged(buffer, start, before, after); 12387 12388 if (AccessibilityManager.getInstance(mContext).isEnabled() 12389 && (isFocused() || isSelected() && isShown())) { 12390 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 12391 mBeforeText = null; 12392 } 12393 } 12394 12395 public void afterTextChanged(Editable buffer) { 12396 if (DEBUG_EXTRACT) { 12397 Log.v(LOG_TAG, "afterTextChanged: " + buffer); 12398 } 12399 TextView.this.sendAfterTextChanged(buffer); 12400 12401 if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { 12402 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 12403 } 12404 } 12405 12406 public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) { 12407 if (DEBUG_EXTRACT) { 12408 Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 12409 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 12410 } 12411 TextView.this.spanChange(buf, what, s, st, e, en); 12412 } 12413 12414 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 12415 if (DEBUG_EXTRACT) { 12416 Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e + " what=" + what + ": " + buf); 12417 } 12418 TextView.this.spanChange(buf, what, -1, s, -1, e); 12419 } 12420 12421 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 12422 if (DEBUG_EXTRACT) { 12423 Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e + " what=" + what + ": " + buf); 12424 } 12425 TextView.this.spanChange(buf, what, s, -1, e, -1); 12426 } 12427 } 12428} 12429