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