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