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