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