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