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