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