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