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