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