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