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