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