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