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