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