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