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