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