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