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