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