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