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