TextView.java revision 322044abe4affc29999398663007c57f664bc4fa
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.ClipData.Item; 22import android.content.ClipboardManager; 23import android.content.Context; 24import android.content.Intent; 25import android.content.pm.PackageManager; 26import android.content.res.ColorStateList; 27import android.content.res.CompatibilityInfo; 28import android.content.res.Resources; 29import android.content.res.TypedArray; 30import android.content.res.XmlResourceParser; 31import android.graphics.Canvas; 32import android.graphics.Color; 33import android.graphics.Paint; 34import android.graphics.Path; 35import android.graphics.Rect; 36import android.graphics.RectF; 37import android.graphics.Typeface; 38import android.graphics.drawable.Drawable; 39import android.inputmethodservice.ExtractEditText; 40import android.os.Bundle; 41import android.os.Handler; 42import android.os.Message; 43import android.os.Parcel; 44import android.os.Parcelable; 45import android.os.SystemClock; 46import android.provider.Settings; 47import android.text.BoringLayout; 48import android.text.DynamicLayout; 49import android.text.Editable; 50import android.text.GetChars; 51import android.text.GraphicsOperations; 52import android.text.InputFilter; 53import android.text.InputType; 54import android.text.Layout; 55import android.text.ParcelableSpan; 56import android.text.Selection; 57import android.text.SpanWatcher; 58import android.text.Spannable; 59import android.text.SpannableString; 60import android.text.SpannableStringBuilder; 61import android.text.Spanned; 62import android.text.SpannedString; 63import android.text.StaticLayout; 64import android.text.TextDirectionHeuristic; 65import android.text.TextDirectionHeuristics; 66import android.text.TextPaint; 67import android.text.TextUtils; 68import android.text.TextUtils.TruncateAt; 69import android.text.TextWatcher; 70import android.text.method.AllCapsTransformationMethod; 71import android.text.method.ArrowKeyMovementMethod; 72import android.text.method.DateKeyListener; 73import android.text.method.DateTimeKeyListener; 74import android.text.method.DialerKeyListener; 75import android.text.method.DigitsKeyListener; 76import android.text.method.KeyListener; 77import android.text.method.LinkMovementMethod; 78import android.text.method.MetaKeyKeyListener; 79import android.text.method.MovementMethod; 80import android.text.method.PasswordTransformationMethod; 81import android.text.method.SingleLineTransformationMethod; 82import android.text.method.TextKeyListener; 83import android.text.method.TimeKeyListener; 84import android.text.method.TransformationMethod; 85import android.text.method.TransformationMethod2; 86import android.text.method.WordIterator; 87import android.text.style.CharacterStyle; 88import android.text.style.ClickableSpan; 89import android.text.style.EasyEditSpan; 90import android.text.style.ParagraphStyle; 91import android.text.style.SpellCheckSpan; 92import android.text.style.SuggestionRangeSpan; 93import android.text.style.SuggestionSpan; 94import android.text.style.TextAppearanceSpan; 95import android.text.style.URLSpan; 96import android.text.style.UpdateAppearance; 97import android.text.util.Linkify; 98import android.util.AttributeSet; 99import android.util.DisplayMetrics; 100import android.util.FloatMath; 101import android.util.Log; 102import android.util.TypedValue; 103import android.view.ActionMode; 104import android.view.ActionMode.Callback; 105import android.view.DisplayList; 106import android.view.DragEvent; 107import android.view.Gravity; 108import android.view.HapticFeedbackConstants; 109import android.view.HardwareCanvas; 110import android.view.KeyCharacterMap; 111import android.view.KeyEvent; 112import android.view.LayoutInflater; 113import android.view.Menu; 114import android.view.MenuItem; 115import android.view.MotionEvent; 116import android.view.View; 117import android.view.ViewConfiguration; 118import android.view.ViewDebug; 119import android.view.ViewGroup; 120import android.view.ViewGroup.LayoutParams; 121import android.view.ViewParent; 122import android.view.ViewRootImpl; 123import android.view.ViewTreeObserver; 124import android.view.WindowManager; 125import android.view.accessibility.AccessibilityEvent; 126import android.view.accessibility.AccessibilityManager; 127import android.view.accessibility.AccessibilityNodeInfo; 128import android.view.animation.AnimationUtils; 129import android.view.inputmethod.BaseInputConnection; 130import android.view.inputmethod.CompletionInfo; 131import android.view.inputmethod.CorrectionInfo; 132import android.view.inputmethod.EditorInfo; 133import android.view.inputmethod.ExtractedText; 134import android.view.inputmethod.ExtractedTextRequest; 135import android.view.inputmethod.InputConnection; 136import android.view.inputmethod.InputMethodManager; 137import android.view.textservice.SpellCheckerSubtype; 138import android.view.textservice.TextServicesManager; 139import android.widget.AdapterView.OnItemClickListener; 140import android.widget.RemoteViews.RemoteView; 141 142import com.android.internal.util.FastMath; 143import com.android.internal.widget.EditableInputConnection; 144 145import org.xmlpull.v1.XmlPullParserException; 146 147import java.io.IOException; 148import java.lang.ref.WeakReference; 149import java.text.BreakIterator; 150import java.util.ArrayList; 151import java.util.Arrays; 152import java.util.Comparator; 153import java.util.HashMap; 154import java.util.Locale; 155 156/** 157 * Displays text to the user and optionally allows them to edit it. A TextView 158 * is a complete text editor, however the basic class is configured to not 159 * allow editing; see {@link EditText} for a subclass that configures the text 160 * view for editing. 161 * 162 * <p> 163 * <b>XML attributes</b> 164 * <p> 165 * See {@link android.R.styleable#TextView TextView Attributes}, 166 * {@link android.R.styleable#View View Attributes} 167 * 168 * @attr ref android.R.styleable#TextView_text 169 * @attr ref android.R.styleable#TextView_bufferType 170 * @attr ref android.R.styleable#TextView_hint 171 * @attr ref android.R.styleable#TextView_textColor 172 * @attr ref android.R.styleable#TextView_textColorHighlight 173 * @attr ref android.R.styleable#TextView_textColorHint 174 * @attr ref android.R.styleable#TextView_textAppearance 175 * @attr ref android.R.styleable#TextView_textColorLink 176 * @attr ref android.R.styleable#TextView_textSize 177 * @attr ref android.R.styleable#TextView_textScaleX 178 * @attr ref android.R.styleable#TextView_typeface 179 * @attr ref android.R.styleable#TextView_textStyle 180 * @attr ref android.R.styleable#TextView_cursorVisible 181 * @attr ref android.R.styleable#TextView_maxLines 182 * @attr ref android.R.styleable#TextView_maxHeight 183 * @attr ref android.R.styleable#TextView_lines 184 * @attr ref android.R.styleable#TextView_height 185 * @attr ref android.R.styleable#TextView_minLines 186 * @attr ref android.R.styleable#TextView_minHeight 187 * @attr ref android.R.styleable#TextView_maxEms 188 * @attr ref android.R.styleable#TextView_maxWidth 189 * @attr ref android.R.styleable#TextView_ems 190 * @attr ref android.R.styleable#TextView_width 191 * @attr ref android.R.styleable#TextView_minEms 192 * @attr ref android.R.styleable#TextView_minWidth 193 * @attr ref android.R.styleable#TextView_gravity 194 * @attr ref android.R.styleable#TextView_scrollHorizontally 195 * @attr ref android.R.styleable#TextView_password 196 * @attr ref android.R.styleable#TextView_singleLine 197 * @attr ref android.R.styleable#TextView_selectAllOnFocus 198 * @attr ref android.R.styleable#TextView_includeFontPadding 199 * @attr ref android.R.styleable#TextView_maxLength 200 * @attr ref android.R.styleable#TextView_shadowColor 201 * @attr ref android.R.styleable#TextView_shadowDx 202 * @attr ref android.R.styleable#TextView_shadowDy 203 * @attr ref android.R.styleable#TextView_shadowRadius 204 * @attr ref android.R.styleable#TextView_autoLink 205 * @attr ref android.R.styleable#TextView_linksClickable 206 * @attr ref android.R.styleable#TextView_numeric 207 * @attr ref android.R.styleable#TextView_digits 208 * @attr ref android.R.styleable#TextView_phoneNumber 209 * @attr ref android.R.styleable#TextView_inputMethod 210 * @attr ref android.R.styleable#TextView_capitalize 211 * @attr ref android.R.styleable#TextView_autoText 212 * @attr ref android.R.styleable#TextView_editable 213 * @attr ref android.R.styleable#TextView_freezesText 214 * @attr ref android.R.styleable#TextView_ellipsize 215 * @attr ref android.R.styleable#TextView_drawableTop 216 * @attr ref android.R.styleable#TextView_drawableBottom 217 * @attr ref android.R.styleable#TextView_drawableRight 218 * @attr ref android.R.styleable#TextView_drawableLeft 219 * @attr ref android.R.styleable#TextView_drawablePadding 220 * @attr ref android.R.styleable#TextView_lineSpacingExtra 221 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 222 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 223 * @attr ref android.R.styleable#TextView_inputType 224 * @attr ref android.R.styleable#TextView_imeOptions 225 * @attr ref android.R.styleable#TextView_privateImeOptions 226 * @attr ref android.R.styleable#TextView_imeActionLabel 227 * @attr ref android.R.styleable#TextView_imeActionId 228 * @attr ref android.R.styleable#TextView_editorExtras 229 */ 230@RemoteView 231public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { 232 static final String LOG_TAG = "TextView"; 233 static final boolean DEBUG_EXTRACT = false; 234 235 private static final int PRIORITY = 100; 236 private int mCurrentAlpha = 255; 237 238 final int[] mTempCoords = new int[2]; 239 Rect mTempRect; 240 241 private ColorStateList mTextColor; 242 private int mCurTextColor; 243 private ColorStateList mHintTextColor; 244 private ColorStateList mLinkTextColor; 245 private int mCurHintTextColor; 246 private boolean mFreezesText; 247 private boolean mFrozenWithFocus; 248 private boolean mTemporaryDetach; 249 private boolean mDispatchTemporaryDetach; 250 251 private boolean mDiscardNextActionUp = false; 252 private boolean mIgnoreActionUpEvent = false; 253 254 private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); 255 private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); 256 257 private float mShadowRadius, mShadowDx, mShadowDy; 258 259 private boolean mPreDrawRegistered; 260 261 private TextUtils.TruncateAt mEllipsize = null; 262 263 // Enum for the "typeface" XML parameter. 264 // TODO: How can we get this from the XML instead of hardcoding it here? 265 private static final int SANS = 1; 266 private static final int SERIF = 2; 267 private static final int MONOSPACE = 3; 268 269 // Bitfield for the "numeric" XML parameter. 270 // TODO: How can we get this from the XML instead of hardcoding it here? 271 private static final int SIGNED = 2; 272 private static final int DECIMAL = 4; 273 274 static class Drawables { 275 final Rect mCompoundRect = new Rect(); 276 Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight, 277 mDrawableStart, mDrawableEnd; 278 int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight, 279 mDrawableSizeStart, mDrawableSizeEnd; 280 int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight, 281 mDrawableHeightStart, mDrawableHeightEnd; 282 int mDrawablePadding; 283 } 284 private Drawables mDrawables; 285 286 private DisplayList mTextDisplayList; 287 private boolean mTextDisplayListIsValid; 288 289 private CharSequence mError; 290 private boolean mErrorWasChanged; 291 private ErrorPopup mPopup; 292 /** 293 * This flag is set if the TextView tries to display an error before it 294 * is attached to the window (so its position is still unknown). 295 * It causes the error to be shown later, when onAttachedToWindow() 296 * is called. 297 */ 298 private boolean mShowErrorAfterAttach; 299 300 private CharWrapper mCharWrapper = null; 301 302 private boolean mSelectionMoved = false; 303 private boolean mTouchFocusSelected = false; 304 305 private Marquee mMarquee; 306 private boolean mRestartMarquee; 307 308 private int mMarqueeRepeatLimit = 3; 309 310 static class InputContentType { 311 int imeOptions = EditorInfo.IME_NULL; 312 String privateImeOptions; 313 CharSequence imeActionLabel; 314 int imeActionId; 315 Bundle extras; 316 OnEditorActionListener onEditorActionListener; 317 boolean enterDown; 318 } 319 InputContentType mInputContentType; 320 321 static class InputMethodState { 322 Rect mCursorRectInWindow = new Rect(); 323 RectF mTmpRectF = new RectF(); 324 float[] mTmpOffset = new float[2]; 325 ExtractedTextRequest mExtracting; 326 final ExtractedText mTmpExtracted = new ExtractedText(); 327 int mBatchEditNesting; 328 boolean mCursorChanged; 329 boolean mSelectionModeChanged; 330 boolean mContentChanged; 331 int mChangedStart, mChangedEnd, mChangedDelta; 332 } 333 InputMethodState mInputMethodState; 334 335 private int mTextSelectHandleLeftRes; 336 private int mTextSelectHandleRightRes; 337 private int mTextSelectHandleRes; 338 339 private int mTextEditSuggestionItemLayout; 340 private SuggestionsPopupWindow mSuggestionsPopupWindow; 341 private SuggestionRangeSpan mSuggestionRangeSpan; 342 private Runnable mShowSuggestionRunnable; 343 344 private int mCursorDrawableRes; 345 private final Drawable[] mCursorDrawable = new Drawable[2]; 346 private int mCursorCount; // Actual current number of used mCursorDrawable: 0, 1 or 2 (split) 347 348 private Drawable mSelectHandleLeft; 349 private Drawable mSelectHandleRight; 350 private Drawable mSelectHandleCenter; 351 352 // Global listener that detects changes in the global position of the TextView 353 private PositionListener mPositionListener; 354 355 private float mLastDownPositionX, mLastDownPositionY; 356 private Callback mCustomSelectionActionModeCallback; 357 358 // Set when this TextView gained focus with some text selected. Will start selection mode. 359 private boolean mCreatedWithASelection = false; 360 361 private WordIterator mWordIterator; 362 363 private SpellChecker mSpellChecker; 364 365 // The alignment to pass to Layout, or null if not resolved. 366 private Layout.Alignment mLayoutAlignment; 367 368 // The default value for mTextAlign. 369 private TextAlign mTextAlign = TextAlign.INHERIT; 370 371 private static enum TextAlign { 372 INHERIT, GRAVITY, TEXT_START, TEXT_END, CENTER, VIEW_START, VIEW_END; 373 } 374 375 private boolean mResolvedDrawables = false; 376 377 /** 378 * On some devices the fading edges add a performance penalty if used 379 * extensively in the same layout. This mode indicates how the marquee 380 * is currently being shown, if applicable. (mEllipsize will == MARQUEE) 381 */ 382 private int mMarqueeFadeMode = MARQUEE_FADE_NORMAL; 383 384 /** 385 * When mMarqueeFadeMode is not MARQUEE_FADE_NORMAL, this stores 386 * the layout that should be used when the mode switches. 387 */ 388 private Layout mSavedMarqueeModeLayout; 389 390 /** 391 * Draw marquee text with fading edges as usual 392 */ 393 private static final int MARQUEE_FADE_NORMAL = 0; 394 395 /** 396 * Draw marquee text as ellipsize end while inactive instead of with the fade. 397 * (Useful for devices where the fade can be expensive if overdone) 398 */ 399 private static final int MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS = 1; 400 401 /** 402 * Draw marquee text with fading edges because it is currently active/animating. 403 */ 404 private static final int MARQUEE_FADE_SWITCH_SHOW_FADE = 2; 405 406 /* 407 * Kick-start the font cache for the zygote process (to pay the cost of 408 * initializing freetype for our default font only once). 409 */ 410 static { 411 Paint p = new Paint(); 412 p.setAntiAlias(true); 413 // We don't care about the result, just the side-effect of measuring. 414 p.measureText("H"); 415 } 416 417 /** 418 * Interface definition for a callback to be invoked when an action is 419 * performed on the editor. 420 */ 421 public interface OnEditorActionListener { 422 /** 423 * Called when an action is being performed. 424 * 425 * @param v The view that was clicked. 426 * @param actionId Identifier of the action. This will be either the 427 * identifier you supplied, or {@link EditorInfo#IME_NULL 428 * EditorInfo.IME_NULL} if being called due to the enter key 429 * being pressed. 430 * @param event If triggered by an enter key, this is the event; 431 * otherwise, this is null. 432 * @return Return true if you have consumed the action, else false. 433 */ 434 boolean onEditorAction(TextView v, int actionId, KeyEvent event); 435 } 436 437 public TextView(Context context) { 438 this(context, null); 439 } 440 441 public TextView(Context context, AttributeSet attrs) { 442 this(context, attrs, com.android.internal.R.attr.textViewStyle); 443 } 444 445 @SuppressWarnings("deprecation") 446 public TextView(Context context, AttributeSet attrs, int defStyle) { 447 super(context, attrs, defStyle); 448 mText = ""; 449 450 final Resources res = getResources(); 451 final CompatibilityInfo compat = res.getCompatibilityInfo(); 452 453 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 454 mTextPaint.density = res.getDisplayMetrics().density; 455 mTextPaint.setCompatibilityScaling(compat.applicationScale); 456 457 // If we get the paint from the skin, we should set it to left, since 458 // the layout always wants it to be left. 459 // mTextPaint.setTextAlign(Paint.Align.LEFT); 460 461 mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 462 mHighlightPaint.setCompatibilityScaling(compat.applicationScale); 463 464 mMovement = getDefaultMovementMethod(); 465 mTransformation = null; 466 467 int textColorHighlight = 0; 468 ColorStateList textColor = null; 469 ColorStateList textColorHint = null; 470 ColorStateList textColorLink = null; 471 int textSize = 15; 472 int typefaceIndex = -1; 473 int styleIndex = -1; 474 boolean allCaps = false; 475 476 final Resources.Theme theme = context.getTheme(); 477 478 /* 479 * Look the appearance up without checking first if it exists because 480 * almost every TextView has one and it greatly simplifies the logic 481 * to be able to parse the appearance first and then let specific tags 482 * for this View override it. 483 */ 484 TypedArray a = theme.obtainStyledAttributes( 485 attrs, com.android.internal.R.styleable.TextViewAppearance, defStyle, 0); 486 TypedArray appearance = null; 487 int ap = a.getResourceId( 488 com.android.internal.R.styleable.TextViewAppearance_textAppearance, -1); 489 a.recycle(); 490 if (ap != -1) { 491 appearance = theme.obtainStyledAttributes( 492 ap, com.android.internal.R.styleable.TextAppearance); 493 } 494 if (appearance != null) { 495 int n = appearance.getIndexCount(); 496 for (int i = 0; i < n; i++) { 497 int attr = appearance.getIndex(i); 498 499 switch (attr) { 500 case com.android.internal.R.styleable.TextAppearance_textColorHighlight: 501 textColorHighlight = appearance.getColor(attr, textColorHighlight); 502 break; 503 504 case com.android.internal.R.styleable.TextAppearance_textColor: 505 textColor = appearance.getColorStateList(attr); 506 break; 507 508 case com.android.internal.R.styleable.TextAppearance_textColorHint: 509 textColorHint = appearance.getColorStateList(attr); 510 break; 511 512 case com.android.internal.R.styleable.TextAppearance_textColorLink: 513 textColorLink = appearance.getColorStateList(attr); 514 break; 515 516 case com.android.internal.R.styleable.TextAppearance_textSize: 517 textSize = appearance.getDimensionPixelSize(attr, textSize); 518 break; 519 520 case com.android.internal.R.styleable.TextAppearance_typeface: 521 typefaceIndex = appearance.getInt(attr, -1); 522 break; 523 524 case com.android.internal.R.styleable.TextAppearance_textStyle: 525 styleIndex = appearance.getInt(attr, -1); 526 break; 527 528 case com.android.internal.R.styleable.TextAppearance_textAllCaps: 529 allCaps = appearance.getBoolean(attr, false); 530 break; 531 } 532 } 533 534 appearance.recycle(); 535 } 536 537 boolean editable = getDefaultEditable(); 538 CharSequence inputMethod = null; 539 int numeric = 0; 540 CharSequence digits = null; 541 boolean phone = false; 542 boolean autotext = false; 543 int autocap = -1; 544 int buffertype = 0; 545 boolean selectallonfocus = false; 546 Drawable drawableLeft = null, drawableTop = null, drawableRight = null, 547 drawableBottom = null, drawableStart = null, drawableEnd = null; 548 int drawablePadding = 0; 549 int ellipsize = -1; 550 boolean singleLine = false; 551 int maxlength = -1; 552 CharSequence text = ""; 553 CharSequence hint = null; 554 int shadowcolor = 0; 555 float dx = 0, dy = 0, r = 0; 556 boolean password = false; 557 int inputType = EditorInfo.TYPE_NULL; 558 559 a = theme.obtainStyledAttributes( 560 attrs, com.android.internal.R.styleable.TextView, defStyle, 0); 561 562 int n = a.getIndexCount(); 563 for (int i = 0; i < n; i++) { 564 int attr = a.getIndex(i); 565 566 switch (attr) { 567 case com.android.internal.R.styleable.TextView_editable: 568 editable = a.getBoolean(attr, editable); 569 break; 570 571 case com.android.internal.R.styleable.TextView_inputMethod: 572 inputMethod = a.getText(attr); 573 break; 574 575 case com.android.internal.R.styleable.TextView_numeric: 576 numeric = a.getInt(attr, numeric); 577 break; 578 579 case com.android.internal.R.styleable.TextView_digits: 580 digits = a.getText(attr); 581 break; 582 583 case com.android.internal.R.styleable.TextView_phoneNumber: 584 phone = a.getBoolean(attr, phone); 585 break; 586 587 case com.android.internal.R.styleable.TextView_autoText: 588 autotext = a.getBoolean(attr, autotext); 589 break; 590 591 case com.android.internal.R.styleable.TextView_capitalize: 592 autocap = a.getInt(attr, autocap); 593 break; 594 595 case com.android.internal.R.styleable.TextView_bufferType: 596 buffertype = a.getInt(attr, buffertype); 597 break; 598 599 case com.android.internal.R.styleable.TextView_selectAllOnFocus: 600 selectallonfocus = a.getBoolean(attr, selectallonfocus); 601 break; 602 603 case com.android.internal.R.styleable.TextView_autoLink: 604 mAutoLinkMask = a.getInt(attr, 0); 605 break; 606 607 case com.android.internal.R.styleable.TextView_linksClickable: 608 mLinksClickable = a.getBoolean(attr, true); 609 break; 610 611// TODO uncomment when this attribute is made public in the next release 612// also add TextView_showSoftInputOnFocus to the list of attributes above 613// case com.android.internal.R.styleable.TextView_showSoftInputOnFocus: 614// setShowSoftInputOnFocus(a.getBoolean(attr, true)); 615// break; 616 617 case com.android.internal.R.styleable.TextView_drawableLeft: 618 drawableLeft = a.getDrawable(attr); 619 break; 620 621 case com.android.internal.R.styleable.TextView_drawableTop: 622 drawableTop = a.getDrawable(attr); 623 break; 624 625 case com.android.internal.R.styleable.TextView_drawableRight: 626 drawableRight = a.getDrawable(attr); 627 break; 628 629 case com.android.internal.R.styleable.TextView_drawableBottom: 630 drawableBottom = a.getDrawable(attr); 631 break; 632 633 case com.android.internal.R.styleable.TextView_drawableStart: 634 drawableStart = a.getDrawable(attr); 635 break; 636 637 case com.android.internal.R.styleable.TextView_drawableEnd: 638 drawableEnd = a.getDrawable(attr); 639 break; 640 641 case com.android.internal.R.styleable.TextView_drawablePadding: 642 drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); 643 break; 644 645 case com.android.internal.R.styleable.TextView_maxLines: 646 setMaxLines(a.getInt(attr, -1)); 647 break; 648 649 case com.android.internal.R.styleable.TextView_maxHeight: 650 setMaxHeight(a.getDimensionPixelSize(attr, -1)); 651 break; 652 653 case com.android.internal.R.styleable.TextView_lines: 654 setLines(a.getInt(attr, -1)); 655 break; 656 657 case com.android.internal.R.styleable.TextView_height: 658 setHeight(a.getDimensionPixelSize(attr, -1)); 659 break; 660 661 case com.android.internal.R.styleable.TextView_minLines: 662 setMinLines(a.getInt(attr, -1)); 663 break; 664 665 case com.android.internal.R.styleable.TextView_minHeight: 666 setMinHeight(a.getDimensionPixelSize(attr, -1)); 667 break; 668 669 case com.android.internal.R.styleable.TextView_maxEms: 670 setMaxEms(a.getInt(attr, -1)); 671 break; 672 673 case com.android.internal.R.styleable.TextView_maxWidth: 674 setMaxWidth(a.getDimensionPixelSize(attr, -1)); 675 break; 676 677 case com.android.internal.R.styleable.TextView_ems: 678 setEms(a.getInt(attr, -1)); 679 break; 680 681 case com.android.internal.R.styleable.TextView_width: 682 setWidth(a.getDimensionPixelSize(attr, -1)); 683 break; 684 685 case com.android.internal.R.styleable.TextView_minEms: 686 setMinEms(a.getInt(attr, -1)); 687 break; 688 689 case com.android.internal.R.styleable.TextView_minWidth: 690 setMinWidth(a.getDimensionPixelSize(attr, -1)); 691 break; 692 693 case com.android.internal.R.styleable.TextView_gravity: 694 setGravity(a.getInt(attr, -1)); 695 break; 696 697 case com.android.internal.R.styleable.TextView_hint: 698 hint = a.getText(attr); 699 break; 700 701 case com.android.internal.R.styleable.TextView_text: 702 text = a.getText(attr); 703 break; 704 705 case com.android.internal.R.styleable.TextView_scrollHorizontally: 706 if (a.getBoolean(attr, false)) { 707 setHorizontallyScrolling(true); 708 } 709 break; 710 711 case com.android.internal.R.styleable.TextView_singleLine: 712 singleLine = a.getBoolean(attr, singleLine); 713 break; 714 715 case com.android.internal.R.styleable.TextView_ellipsize: 716 ellipsize = a.getInt(attr, ellipsize); 717 break; 718 719 case com.android.internal.R.styleable.TextView_marqueeRepeatLimit: 720 setMarqueeRepeatLimit(a.getInt(attr, mMarqueeRepeatLimit)); 721 break; 722 723 case com.android.internal.R.styleable.TextView_includeFontPadding: 724 if (!a.getBoolean(attr, true)) { 725 setIncludeFontPadding(false); 726 } 727 break; 728 729 case com.android.internal.R.styleable.TextView_cursorVisible: 730 if (!a.getBoolean(attr, true)) { 731 setCursorVisible(false); 732 } 733 break; 734 735 case com.android.internal.R.styleable.TextView_maxLength: 736 maxlength = a.getInt(attr, -1); 737 break; 738 739 case com.android.internal.R.styleable.TextView_textScaleX: 740 setTextScaleX(a.getFloat(attr, 1.0f)); 741 break; 742 743 case com.android.internal.R.styleable.TextView_freezesText: 744 mFreezesText = a.getBoolean(attr, false); 745 break; 746 747 case com.android.internal.R.styleable.TextView_shadowColor: 748 shadowcolor = a.getInt(attr, 0); 749 break; 750 751 case com.android.internal.R.styleable.TextView_shadowDx: 752 dx = a.getFloat(attr, 0); 753 break; 754 755 case com.android.internal.R.styleable.TextView_shadowDy: 756 dy = a.getFloat(attr, 0); 757 break; 758 759 case com.android.internal.R.styleable.TextView_shadowRadius: 760 r = a.getFloat(attr, 0); 761 break; 762 763 case com.android.internal.R.styleable.TextView_enabled: 764 setEnabled(a.getBoolean(attr, isEnabled())); 765 break; 766 767 case com.android.internal.R.styleable.TextView_textColorHighlight: 768 textColorHighlight = a.getColor(attr, textColorHighlight); 769 break; 770 771 case com.android.internal.R.styleable.TextView_textColor: 772 textColor = a.getColorStateList(attr); 773 break; 774 775 case com.android.internal.R.styleable.TextView_textColorHint: 776 textColorHint = a.getColorStateList(attr); 777 break; 778 779 case com.android.internal.R.styleable.TextView_textColorLink: 780 textColorLink = a.getColorStateList(attr); 781 break; 782 783 case com.android.internal.R.styleable.TextView_textSize: 784 textSize = a.getDimensionPixelSize(attr, textSize); 785 break; 786 787 case com.android.internal.R.styleable.TextView_typeface: 788 typefaceIndex = a.getInt(attr, typefaceIndex); 789 break; 790 791 case com.android.internal.R.styleable.TextView_textStyle: 792 styleIndex = a.getInt(attr, styleIndex); 793 break; 794 795 case com.android.internal.R.styleable.TextView_password: 796 password = a.getBoolean(attr, password); 797 break; 798 799 case com.android.internal.R.styleable.TextView_lineSpacingExtra: 800 mSpacingAdd = a.getDimensionPixelSize(attr, (int) mSpacingAdd); 801 break; 802 803 case com.android.internal.R.styleable.TextView_lineSpacingMultiplier: 804 mSpacingMult = a.getFloat(attr, mSpacingMult); 805 break; 806 807 case com.android.internal.R.styleable.TextView_inputType: 808 inputType = a.getInt(attr, mInputType); 809 break; 810 811 case com.android.internal.R.styleable.TextView_imeOptions: 812 if (mInputContentType == null) { 813 mInputContentType = new InputContentType(); 814 } 815 mInputContentType.imeOptions = a.getInt(attr, 816 mInputContentType.imeOptions); 817 break; 818 819 case com.android.internal.R.styleable.TextView_imeActionLabel: 820 if (mInputContentType == null) { 821 mInputContentType = new InputContentType(); 822 } 823 mInputContentType.imeActionLabel = a.getText(attr); 824 break; 825 826 case com.android.internal.R.styleable.TextView_imeActionId: 827 if (mInputContentType == null) { 828 mInputContentType = new InputContentType(); 829 } 830 mInputContentType.imeActionId = a.getInt(attr, 831 mInputContentType.imeActionId); 832 break; 833 834 case com.android.internal.R.styleable.TextView_privateImeOptions: 835 setPrivateImeOptions(a.getString(attr)); 836 break; 837 838 case com.android.internal.R.styleable.TextView_editorExtras: 839 try { 840 setInputExtras(a.getResourceId(attr, 0)); 841 } catch (XmlPullParserException e) { 842 Log.w(LOG_TAG, "Failure reading input extras", e); 843 } catch (IOException e) { 844 Log.w(LOG_TAG, "Failure reading input extras", e); 845 } 846 break; 847 848 case com.android.internal.R.styleable.TextView_textCursorDrawable: 849 mCursorDrawableRes = a.getResourceId(attr, 0); 850 break; 851 852 case com.android.internal.R.styleable.TextView_textSelectHandleLeft: 853 mTextSelectHandleLeftRes = a.getResourceId(attr, 0); 854 break; 855 856 case com.android.internal.R.styleable.TextView_textSelectHandleRight: 857 mTextSelectHandleRightRes = a.getResourceId(attr, 0); 858 break; 859 860 case com.android.internal.R.styleable.TextView_textSelectHandle: 861 mTextSelectHandleRes = a.getResourceId(attr, 0); 862 break; 863 864 case com.android.internal.R.styleable.TextView_textEditSuggestionItemLayout: 865 mTextEditSuggestionItemLayout = a.getResourceId(attr, 0); 866 break; 867 868 case com.android.internal.R.styleable.TextView_textIsSelectable: 869 mTextIsSelectable = a.getBoolean(attr, false); 870 break; 871 872 case com.android.internal.R.styleable.TextView_textAllCaps: 873 allCaps = a.getBoolean(attr, false); 874 break; 875 } 876 } 877 a.recycle(); 878 879 BufferType bufferType = BufferType.EDITABLE; 880 881 final int variation = 882 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 883 final boolean passwordInputType = variation 884 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); 885 final boolean webPasswordInputType = variation 886 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD); 887 final boolean numberPasswordInputType = variation 888 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 889 890 if (inputMethod != null) { 891 Class<?> c; 892 893 try { 894 c = Class.forName(inputMethod.toString()); 895 } catch (ClassNotFoundException ex) { 896 throw new RuntimeException(ex); 897 } 898 899 try { 900 mInput = (KeyListener) c.newInstance(); 901 } catch (InstantiationException ex) { 902 throw new RuntimeException(ex); 903 } catch (IllegalAccessException ex) { 904 throw new RuntimeException(ex); 905 } 906 try { 907 mInputType = inputType != EditorInfo.TYPE_NULL 908 ? inputType 909 : mInput.getInputType(); 910 } catch (IncompatibleClassChangeError e) { 911 mInputType = EditorInfo.TYPE_CLASS_TEXT; 912 } 913 } else if (digits != null) { 914 mInput = 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 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 mInput = DialerKeyListener.getInstance(); 926 mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE; 927 } else if (numeric != 0) { 928 mInput = DigitsKeyListener.getInstance((numeric & SIGNED) != 0, 929 (numeric & DECIMAL) != 0); 930 inputType = EditorInfo.TYPE_CLASS_NUMBER; 931 if ((numeric & SIGNED) != 0) { 932 inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; 933 } 934 if ((numeric & DECIMAL) != 0) { 935 inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; 936 } 937 mInputType = inputType; 938 } else if (autotext || autocap != -1) { 939 TextKeyListener.Capitalize cap; 940 941 inputType = EditorInfo.TYPE_CLASS_TEXT; 942 943 switch (autocap) { 944 case 1: 945 cap = TextKeyListener.Capitalize.SENTENCES; 946 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; 947 break; 948 949 case 2: 950 cap = TextKeyListener.Capitalize.WORDS; 951 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; 952 break; 953 954 case 3: 955 cap = TextKeyListener.Capitalize.CHARACTERS; 956 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; 957 break; 958 959 default: 960 cap = TextKeyListener.Capitalize.NONE; 961 break; 962 } 963 964 mInput = TextKeyListener.getInstance(autotext, cap); 965 mInputType = inputType; 966 } else if (mTextIsSelectable) { 967 // Prevent text changes from keyboard. 968 mInputType = EditorInfo.TYPE_NULL; 969 mInput = null; 970 bufferType = BufferType.SPANNABLE; 971 // Required to request focus while in touch mode. 972 setFocusableInTouchMode(true); 973 // So that selection can be changed using arrow keys and touch is handled. 974 setMovementMethod(ArrowKeyMovementMethod.getInstance()); 975 } else if (editable) { 976 mInput = TextKeyListener.getInstance(); 977 mInputType = EditorInfo.TYPE_CLASS_TEXT; 978 } else { 979 mInput = null; 980 981 switch (buffertype) { 982 case 0: 983 bufferType = BufferType.NORMAL; 984 break; 985 case 1: 986 bufferType = BufferType.SPANNABLE; 987 break; 988 case 2: 989 bufferType = BufferType.EDITABLE; 990 break; 991 } 992 } 993 994 // mInputType has been set from inputType, possibly modified by mInputMethod. 995 // Specialize mInputType to [web]password if we have a text class and the original input 996 // type was a password. 997 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 998 if (password || passwordInputType) { 999 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 1000 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 1001 } 1002 if (webPasswordInputType) { 1003 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 1004 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD; 1005 } 1006 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) { 1007 if (numberPasswordInputType) { 1008 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 1009 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD; 1010 } 1011 } 1012 1013 if (selectallonfocus) { 1014 mSelectAllOnFocus = true; 1015 1016 if (bufferType == BufferType.NORMAL) 1017 bufferType = BufferType.SPANNABLE; 1018 } 1019 1020 setCompoundDrawablesWithIntrinsicBounds( 1021 drawableLeft, drawableTop, drawableRight, drawableBottom); 1022 setRelativeDrawablesIfNeeded(drawableStart, drawableEnd); 1023 setCompoundDrawablePadding(drawablePadding); 1024 1025 // Same as setSingleLine(), but make sure the transformation method and the maximum number 1026 // of lines of height are unchanged for multi-line TextViews. 1027 setInputTypeSingleLine(singleLine); 1028 applySingleLine(singleLine, singleLine, singleLine); 1029 1030 if (singleLine && mInput == null && ellipsize < 0) { 1031 ellipsize = 3; // END 1032 } 1033 1034 switch (ellipsize) { 1035 case 1: 1036 setEllipsize(TextUtils.TruncateAt.START); 1037 break; 1038 case 2: 1039 setEllipsize(TextUtils.TruncateAt.MIDDLE); 1040 break; 1041 case 3: 1042 setEllipsize(TextUtils.TruncateAt.END); 1043 break; 1044 case 4: 1045 if (ViewConfiguration.get(context).isFadingMarqueeEnabled()) { 1046 setHorizontalFadingEdgeEnabled(true); 1047 mMarqueeFadeMode = MARQUEE_FADE_NORMAL; 1048 } else { 1049 setHorizontalFadingEdgeEnabled(false); 1050 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 1051 } 1052 setEllipsize(TextUtils.TruncateAt.MARQUEE); 1053 break; 1054 } 1055 1056 setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000)); 1057 setHintTextColor(textColorHint); 1058 setLinkTextColor(textColorLink); 1059 if (textColorHighlight != 0) { 1060 setHighlightColor(textColorHighlight); 1061 } 1062 setRawTextSize(textSize); 1063 1064 if (allCaps) { 1065 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 1066 } 1067 1068 if (password || passwordInputType || webPasswordInputType || numberPasswordInputType) { 1069 setTransformationMethod(PasswordTransformationMethod.getInstance()); 1070 typefaceIndex = MONOSPACE; 1071 } else if ((mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION)) 1072 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { 1073 typefaceIndex = MONOSPACE; 1074 } 1075 1076 setTypefaceByIndex(typefaceIndex, styleIndex); 1077 1078 if (shadowcolor != 0) { 1079 setShadowLayer(r, dx, dy, shadowcolor); 1080 } 1081 1082 if (maxlength >= 0) { 1083 setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) }); 1084 } else { 1085 setFilters(NO_FILTERS); 1086 } 1087 1088 setText(text, bufferType); 1089 if (hint != null) setHint(hint); 1090 1091 /* 1092 * Views are not normally focusable unless specified to be. 1093 * However, TextViews that have input or movement methods *are* 1094 * focusable by default. 1095 */ 1096 a = context.obtainStyledAttributes(attrs, 1097 com.android.internal.R.styleable.View, 1098 defStyle, 0); 1099 1100 boolean focusable = mMovement != null || mInput != null; 1101 boolean clickable = focusable; 1102 boolean longClickable = focusable; 1103 1104 n = a.getIndexCount(); 1105 for (int i = 0; i < n; i++) { 1106 int attr = a.getIndex(i); 1107 1108 switch (attr) { 1109 case com.android.internal.R.styleable.View_focusable: 1110 focusable = a.getBoolean(attr, focusable); 1111 break; 1112 1113 case com.android.internal.R.styleable.View_clickable: 1114 clickable = a.getBoolean(attr, clickable); 1115 break; 1116 1117 case com.android.internal.R.styleable.View_longClickable: 1118 longClickable = a.getBoolean(attr, longClickable); 1119 break; 1120 } 1121 } 1122 a.recycle(); 1123 1124 setFocusable(focusable); 1125 setClickable(clickable); 1126 setLongClickable(longClickable); 1127 1128 prepareCursorControllers(); 1129 } 1130 1131 private void setTypefaceByIndex(int typefaceIndex, int styleIndex) { 1132 Typeface tf = null; 1133 switch (typefaceIndex) { 1134 case SANS: 1135 tf = Typeface.SANS_SERIF; 1136 break; 1137 1138 case SERIF: 1139 tf = Typeface.SERIF; 1140 break; 1141 1142 case MONOSPACE: 1143 tf = Typeface.MONOSPACE; 1144 break; 1145 } 1146 1147 setTypeface(tf, styleIndex); 1148 } 1149 1150 private void setRelativeDrawablesIfNeeded(Drawable start, Drawable end) { 1151 boolean hasRelativeDrawables = (start != null) || (end != null); 1152 if (hasRelativeDrawables) { 1153 Drawables dr = mDrawables; 1154 if (dr == null) { 1155 mDrawables = dr = new Drawables(); 1156 } 1157 final Rect compoundRect = dr.mCompoundRect; 1158 int[] state = getDrawableState(); 1159 if (start != null) { 1160 start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); 1161 start.setState(state); 1162 start.copyBounds(compoundRect); 1163 start.setCallback(this); 1164 1165 dr.mDrawableStart = start; 1166 dr.mDrawableSizeStart = compoundRect.width(); 1167 dr.mDrawableHeightStart = compoundRect.height(); 1168 } else { 1169 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 1170 } 1171 if (end != null) { 1172 end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); 1173 end.setState(state); 1174 end.copyBounds(compoundRect); 1175 end.setCallback(this); 1176 1177 dr.mDrawableEnd = end; 1178 dr.mDrawableSizeEnd = compoundRect.width(); 1179 dr.mDrawableHeightEnd = compoundRect.height(); 1180 } else { 1181 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 1182 } 1183 } 1184 } 1185 1186 @Override 1187 public void setEnabled(boolean enabled) { 1188 if (enabled == isEnabled()) { 1189 return; 1190 } 1191 1192 if (!enabled) { 1193 // Hide the soft input if the currently active TextView is disabled 1194 InputMethodManager imm = InputMethodManager.peekInstance(); 1195 if (imm != null && imm.isActive(this)) { 1196 imm.hideSoftInputFromWindow(getWindowToken(), 0); 1197 } 1198 } 1199 1200 super.setEnabled(enabled); 1201 1202 if (enabled) { 1203 // Make sure IME is updated with current editor info. 1204 InputMethodManager imm = InputMethodManager.peekInstance(); 1205 if (imm != null) imm.restartInput(this); 1206 } 1207 1208 mTextDisplayListIsValid = false; 1209 prepareCursorControllers(); 1210 1211 // start or stop the cursor blinking as appropriate 1212 makeBlink(); 1213 } 1214 1215 /** 1216 * Sets the typeface and style in which the text should be displayed, 1217 * and turns on the fake bold and italic bits in the Paint if the 1218 * Typeface that you provided does not have all the bits in the 1219 * style that you specified. 1220 * 1221 * @attr ref android.R.styleable#TextView_typeface 1222 * @attr ref android.R.styleable#TextView_textStyle 1223 */ 1224 public void setTypeface(Typeface tf, int style) { 1225 if (style > 0) { 1226 if (tf == null) { 1227 tf = Typeface.defaultFromStyle(style); 1228 } else { 1229 tf = Typeface.create(tf, style); 1230 } 1231 1232 setTypeface(tf); 1233 // now compute what (if any) algorithmic styling is needed 1234 int typefaceStyle = tf != null ? tf.getStyle() : 0; 1235 int need = style & ~typefaceStyle; 1236 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); 1237 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); 1238 } else { 1239 mTextPaint.setFakeBoldText(false); 1240 mTextPaint.setTextSkewX(0); 1241 setTypeface(tf); 1242 } 1243 } 1244 1245 /** 1246 * Subclasses override this to specify that they have a KeyListener 1247 * by default even if not specifically called for in the XML options. 1248 */ 1249 protected boolean getDefaultEditable() { 1250 return false; 1251 } 1252 1253 /** 1254 * Subclasses override this to specify a default movement method. 1255 */ 1256 protected MovementMethod getDefaultMovementMethod() { 1257 return null; 1258 } 1259 1260 /** 1261 * Return the text the TextView is displaying. If setText() was called with 1262 * an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast 1263 * the return value from this method to Spannable or Editable, respectively. 1264 * 1265 * Note: The content of the return value should not be modified. If you want 1266 * a modifiable one, you should make your own copy first. 1267 */ 1268 @ViewDebug.CapturedViewProperty 1269 public CharSequence getText() { 1270 return mText; 1271 } 1272 1273 /** 1274 * Returns the length, in characters, of the text managed by this TextView 1275 */ 1276 public int length() { 1277 return mText.length(); 1278 } 1279 1280 /** 1281 * Return the text the TextView is displaying as an Editable object. If 1282 * the text is not editable, null is returned. 1283 * 1284 * @see #getText 1285 */ 1286 public Editable getEditableText() { 1287 return (mText instanceof Editable) ? (Editable)mText : null; 1288 } 1289 1290 /** 1291 * @return the height of one standard line in pixels. Note that markup 1292 * within the text can cause individual lines to be taller or shorter 1293 * than this height, and the layout may contain additional first- 1294 * or last-line padding. 1295 */ 1296 public int getLineHeight() { 1297 return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd); 1298 } 1299 1300 /** 1301 * @return the Layout that is currently being used to display the text. 1302 * This can be null if the text or width has recently changes. 1303 */ 1304 public final Layout getLayout() { 1305 return mLayout; 1306 } 1307 1308 /** 1309 * @return the current key listener for this TextView. 1310 * This will frequently be null for non-EditText TextViews. 1311 */ 1312 public final KeyListener getKeyListener() { 1313 return mInput; 1314 } 1315 1316 /** 1317 * Sets the key listener to be used with this TextView. This can be null 1318 * to disallow user input. Note that this method has significant and 1319 * subtle interactions with soft keyboards and other input method: 1320 * see {@link KeyListener#getInputType() KeyListener.getContentType()} 1321 * for important details. Calling this method will replace the current 1322 * content type of the text view with the content type returned by the 1323 * key listener. 1324 * <p> 1325 * Be warned that if you want a TextView with a key listener or movement 1326 * method not to be focusable, or if you want a TextView without a 1327 * key listener or movement method to be focusable, you must call 1328 * {@link #setFocusable} again after calling this to get the focusability 1329 * back the way you want it. 1330 * 1331 * @attr ref android.R.styleable#TextView_numeric 1332 * @attr ref android.R.styleable#TextView_digits 1333 * @attr ref android.R.styleable#TextView_phoneNumber 1334 * @attr ref android.R.styleable#TextView_inputMethod 1335 * @attr ref android.R.styleable#TextView_capitalize 1336 * @attr ref android.R.styleable#TextView_autoText 1337 */ 1338 public void setKeyListener(KeyListener input) { 1339 setKeyListenerOnly(input); 1340 fixFocusableAndClickableSettings(); 1341 1342 if (input != null) { 1343 try { 1344 mInputType = mInput.getInputType(); 1345 } catch (IncompatibleClassChangeError e) { 1346 mInputType = EditorInfo.TYPE_CLASS_TEXT; 1347 } 1348 // Change inputType, without affecting transformation. 1349 // No need to applySingleLine since mSingleLine is unchanged. 1350 setInputTypeSingleLine(mSingleLine); 1351 } else { 1352 mInputType = EditorInfo.TYPE_NULL; 1353 } 1354 1355 InputMethodManager imm = InputMethodManager.peekInstance(); 1356 if (imm != null) imm.restartInput(this); 1357 } 1358 1359 private void setKeyListenerOnly(KeyListener input) { 1360 mInput = input; 1361 if (mInput != null && !(mText instanceof Editable)) 1362 setText(mText); 1363 1364 setFilters((Editable) mText, mFilters); 1365 } 1366 1367 /** 1368 * @return the movement method being used for this TextView. 1369 * This will frequently be null for non-EditText TextViews. 1370 */ 1371 public final MovementMethod getMovementMethod() { 1372 return mMovement; 1373 } 1374 1375 /** 1376 * Sets the movement method (arrow key handler) to be used for 1377 * this TextView. This can be null to disallow using the arrow keys 1378 * to move the cursor or scroll the view. 1379 * <p> 1380 * Be warned that if you want a TextView with a key listener or movement 1381 * method not to be focusable, or if you want a TextView without a 1382 * key listener or movement method to be focusable, you must call 1383 * {@link #setFocusable} again after calling this to get the focusability 1384 * back the way you want it. 1385 */ 1386 public final void setMovementMethod(MovementMethod movement) { 1387 mMovement = movement; 1388 1389 if (mMovement != null && !(mText instanceof Spannable)) 1390 setText(mText); 1391 1392 fixFocusableAndClickableSettings(); 1393 1394 // SelectionModifierCursorController depends on textCanBeSelected, which depends on mMovement 1395 prepareCursorControllers(); 1396 } 1397 1398 private void fixFocusableAndClickableSettings() { 1399 if ((mMovement != null) || mInput != null) { 1400 setFocusable(true); 1401 setClickable(true); 1402 setLongClickable(true); 1403 } else { 1404 setFocusable(false); 1405 setClickable(false); 1406 setLongClickable(false); 1407 } 1408 } 1409 1410 /** 1411 * @return the current transformation method for this TextView. 1412 * This will frequently be null except for single-line and password 1413 * fields. 1414 */ 1415 public final TransformationMethod getTransformationMethod() { 1416 return mTransformation; 1417 } 1418 1419 /** 1420 * Sets the transformation that is applied to the text that this 1421 * TextView is displaying. 1422 * 1423 * @attr ref android.R.styleable#TextView_password 1424 * @attr ref android.R.styleable#TextView_singleLine 1425 */ 1426 public final void setTransformationMethod(TransformationMethod method) { 1427 if (method == mTransformation) { 1428 // Avoid the setText() below if the transformation is 1429 // the same. 1430 return; 1431 } 1432 if (mTransformation != null) { 1433 if (mText instanceof Spannable) { 1434 ((Spannable) mText).removeSpan(mTransformation); 1435 } 1436 } 1437 1438 mTransformation = method; 1439 1440 if (method instanceof TransformationMethod2) { 1441 TransformationMethod2 method2 = (TransformationMethod2) method; 1442 mAllowTransformationLengthChange = !mTextIsSelectable && !(mText instanceof Editable); 1443 method2.setLengthChangesAllowed(mAllowTransformationLengthChange); 1444 } else { 1445 mAllowTransformationLengthChange = false; 1446 } 1447 1448 setText(mText); 1449 } 1450 1451 /** 1452 * Returns the top padding of the view, plus space for the top 1453 * Drawable if any. 1454 */ 1455 public int getCompoundPaddingTop() { 1456 final Drawables dr = mDrawables; 1457 if (dr == null || dr.mDrawableTop == null) { 1458 return mPaddingTop; 1459 } else { 1460 return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop; 1461 } 1462 } 1463 1464 /** 1465 * Returns the bottom padding of the view, plus space for the bottom 1466 * Drawable if any. 1467 */ 1468 public int getCompoundPaddingBottom() { 1469 final Drawables dr = mDrawables; 1470 if (dr == null || dr.mDrawableBottom == null) { 1471 return mPaddingBottom; 1472 } else { 1473 return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom; 1474 } 1475 } 1476 1477 /** 1478 * Returns the left padding of the view, plus space for the left 1479 * Drawable if any. 1480 */ 1481 public int getCompoundPaddingLeft() { 1482 final Drawables dr = mDrawables; 1483 if (dr == null || dr.mDrawableLeft == null) { 1484 return mPaddingLeft; 1485 } else { 1486 return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft; 1487 } 1488 } 1489 1490 /** 1491 * Returns the right padding of the view, plus space for the right 1492 * Drawable if any. 1493 */ 1494 public int getCompoundPaddingRight() { 1495 final Drawables dr = mDrawables; 1496 if (dr == null || dr.mDrawableRight == null) { 1497 return mPaddingRight; 1498 } else { 1499 return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight; 1500 } 1501 } 1502 1503 /** 1504 * Returns the start padding of the view, plus space for the start 1505 * Drawable if any. 1506 * 1507 * @hide 1508 */ 1509 public int getCompoundPaddingStart() { 1510 resolveDrawables(); 1511 switch(getResolvedLayoutDirection()) { 1512 default: 1513 case LAYOUT_DIRECTION_LTR: 1514 return getCompoundPaddingLeft(); 1515 case LAYOUT_DIRECTION_RTL: 1516 return getCompoundPaddingRight(); 1517 } 1518 } 1519 1520 /** 1521 * Returns the end padding of the view, plus space for the end 1522 * Drawable if any. 1523 * 1524 * @hide 1525 */ 1526 public int getCompoundPaddingEnd() { 1527 resolveDrawables(); 1528 switch(getResolvedLayoutDirection()) { 1529 default: 1530 case LAYOUT_DIRECTION_LTR: 1531 return getCompoundPaddingRight(); 1532 case LAYOUT_DIRECTION_RTL: 1533 return getCompoundPaddingLeft(); 1534 } 1535 } 1536 1537 /** 1538 * Returns the extended top padding of the view, including both the 1539 * top Drawable if any and any extra space to keep more than maxLines 1540 * of text from showing. It is only valid to call this after measuring. 1541 */ 1542 public int getExtendedPaddingTop() { 1543 if (mMaxMode != LINES) { 1544 return getCompoundPaddingTop(); 1545 } 1546 1547 if (mLayout.getLineCount() <= mMaximum) { 1548 return getCompoundPaddingTop(); 1549 } 1550 1551 int top = getCompoundPaddingTop(); 1552 int bottom = getCompoundPaddingBottom(); 1553 int viewht = getHeight() - top - bottom; 1554 int layoutht = mLayout.getLineTop(mMaximum); 1555 1556 if (layoutht >= viewht) { 1557 return top; 1558 } 1559 1560 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1561 if (gravity == Gravity.TOP) { 1562 return top; 1563 } else if (gravity == Gravity.BOTTOM) { 1564 return top + viewht - layoutht; 1565 } else { // (gravity == Gravity.CENTER_VERTICAL) 1566 return top + (viewht - layoutht) / 2; 1567 } 1568 } 1569 1570 /** 1571 * Returns the extended bottom padding of the view, including both the 1572 * bottom Drawable if any and any extra space to keep more than maxLines 1573 * of text from showing. It is only valid to call this after measuring. 1574 */ 1575 public int getExtendedPaddingBottom() { 1576 if (mMaxMode != LINES) { 1577 return getCompoundPaddingBottom(); 1578 } 1579 1580 if (mLayout.getLineCount() <= mMaximum) { 1581 return getCompoundPaddingBottom(); 1582 } 1583 1584 int top = getCompoundPaddingTop(); 1585 int bottom = getCompoundPaddingBottom(); 1586 int viewht = getHeight() - top - bottom; 1587 int layoutht = mLayout.getLineTop(mMaximum); 1588 1589 if (layoutht >= viewht) { 1590 return bottom; 1591 } 1592 1593 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1594 if (gravity == Gravity.TOP) { 1595 return bottom + viewht - layoutht; 1596 } else if (gravity == Gravity.BOTTOM) { 1597 return bottom; 1598 } else { // (gravity == Gravity.CENTER_VERTICAL) 1599 return bottom + (viewht - layoutht) / 2; 1600 } 1601 } 1602 1603 /** 1604 * Returns the total left padding of the view, including the left 1605 * Drawable if any. 1606 */ 1607 public int getTotalPaddingLeft() { 1608 return getCompoundPaddingLeft(); 1609 } 1610 1611 /** 1612 * Returns the total right padding of the view, including the right 1613 * Drawable if any. 1614 */ 1615 public int getTotalPaddingRight() { 1616 return getCompoundPaddingRight(); 1617 } 1618 1619 /** 1620 * Returns the total start padding of the view, including the start 1621 * Drawable if any. 1622 * 1623 * @hide 1624 */ 1625 public int getTotalPaddingStart() { 1626 return getCompoundPaddingStart(); 1627 } 1628 1629 /** 1630 * Returns the total end padding of the view, including the end 1631 * Drawable if any. 1632 * 1633 * @hide 1634 */ 1635 public int getTotalPaddingEnd() { 1636 return getCompoundPaddingEnd(); 1637 } 1638 1639 /** 1640 * Returns the total top padding of the view, including the top 1641 * Drawable if any, the extra space to keep more than maxLines 1642 * from showing, and the vertical offset for gravity, if any. 1643 */ 1644 public int getTotalPaddingTop() { 1645 return getExtendedPaddingTop() + getVerticalOffset(true); 1646 } 1647 1648 /** 1649 * Returns the total bottom padding of the view, including the bottom 1650 * Drawable if any, the extra space to keep more than maxLines 1651 * from showing, and the vertical offset for gravity, if any. 1652 */ 1653 public int getTotalPaddingBottom() { 1654 return getExtendedPaddingBottom() + getBottomVerticalOffset(true); 1655 } 1656 1657 /** 1658 * Sets the Drawables (if any) to appear to the left of, above, 1659 * to the right of, and below the text. Use null if you do not 1660 * want a Drawable there. The Drawables must already have had 1661 * {@link Drawable#setBounds} called. 1662 * 1663 * @attr ref android.R.styleable#TextView_drawableLeft 1664 * @attr ref android.R.styleable#TextView_drawableTop 1665 * @attr ref android.R.styleable#TextView_drawableRight 1666 * @attr ref android.R.styleable#TextView_drawableBottom 1667 */ 1668 public void setCompoundDrawables(Drawable left, Drawable top, 1669 Drawable right, Drawable bottom) { 1670 Drawables dr = mDrawables; 1671 1672 final boolean drawables = left != null || top != null 1673 || right != null || bottom != null; 1674 1675 if (!drawables) { 1676 // Clearing drawables... can we free the data structure? 1677 if (dr != null) { 1678 if (dr.mDrawablePadding == 0) { 1679 mDrawables = null; 1680 } else { 1681 // We need to retain the last set padding, so just clear 1682 // out all of the fields in the existing structure. 1683 if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null); 1684 dr.mDrawableLeft = null; 1685 if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null); 1686 dr.mDrawableTop = null; 1687 if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null); 1688 dr.mDrawableRight = null; 1689 if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null); 1690 dr.mDrawableBottom = null; 1691 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 1692 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 1693 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1694 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1695 } 1696 } 1697 } else { 1698 if (dr == null) { 1699 mDrawables = dr = new Drawables(); 1700 } 1701 1702 if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) { 1703 dr.mDrawableLeft.setCallback(null); 1704 } 1705 dr.mDrawableLeft = left; 1706 1707 if (dr.mDrawableTop != top && dr.mDrawableTop != null) { 1708 dr.mDrawableTop.setCallback(null); 1709 } 1710 dr.mDrawableTop = top; 1711 1712 if (dr.mDrawableRight != right && dr.mDrawableRight != null) { 1713 dr.mDrawableRight.setCallback(null); 1714 } 1715 dr.mDrawableRight = right; 1716 1717 if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { 1718 dr.mDrawableBottom.setCallback(null); 1719 } 1720 dr.mDrawableBottom = bottom; 1721 1722 final Rect compoundRect = dr.mCompoundRect; 1723 int[] state; 1724 1725 state = getDrawableState(); 1726 1727 if (left != null) { 1728 left.setState(state); 1729 left.copyBounds(compoundRect); 1730 left.setCallback(this); 1731 dr.mDrawableSizeLeft = compoundRect.width(); 1732 dr.mDrawableHeightLeft = compoundRect.height(); 1733 } else { 1734 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 1735 } 1736 1737 if (right != null) { 1738 right.setState(state); 1739 right.copyBounds(compoundRect); 1740 right.setCallback(this); 1741 dr.mDrawableSizeRight = compoundRect.width(); 1742 dr.mDrawableHeightRight = compoundRect.height(); 1743 } else { 1744 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 1745 } 1746 1747 if (top != null) { 1748 top.setState(state); 1749 top.copyBounds(compoundRect); 1750 top.setCallback(this); 1751 dr.mDrawableSizeTop = compoundRect.height(); 1752 dr.mDrawableWidthTop = compoundRect.width(); 1753 } else { 1754 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1755 } 1756 1757 if (bottom != null) { 1758 bottom.setState(state); 1759 bottom.copyBounds(compoundRect); 1760 bottom.setCallback(this); 1761 dr.mDrawableSizeBottom = compoundRect.height(); 1762 dr.mDrawableWidthBottom = compoundRect.width(); 1763 } else { 1764 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1765 } 1766 } 1767 1768 invalidate(); 1769 requestLayout(); 1770 } 1771 1772 /** 1773 * Sets the Drawables (if any) to appear to the left of, above, 1774 * to the right of, and below the text. Use 0 if you do not 1775 * want a Drawable there. The Drawables' bounds will be set to 1776 * their intrinsic bounds. 1777 * 1778 * @param left Resource identifier of the left Drawable. 1779 * @param top Resource identifier of the top Drawable. 1780 * @param right Resource identifier of the right Drawable. 1781 * @param bottom Resource identifier of the bottom Drawable. 1782 * 1783 * @attr ref android.R.styleable#TextView_drawableLeft 1784 * @attr ref android.R.styleable#TextView_drawableTop 1785 * @attr ref android.R.styleable#TextView_drawableRight 1786 * @attr ref android.R.styleable#TextView_drawableBottom 1787 */ 1788 public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) { 1789 final Resources resources = getContext().getResources(); 1790 setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null, 1791 top != 0 ? resources.getDrawable(top) : null, 1792 right != 0 ? resources.getDrawable(right) : null, 1793 bottom != 0 ? resources.getDrawable(bottom) : null); 1794 } 1795 1796 /** 1797 * Sets the Drawables (if any) to appear to the left of, above, 1798 * to the right of, and below the text. Use null if you do not 1799 * want a Drawable there. The Drawables' bounds will be set to 1800 * their intrinsic bounds. 1801 * 1802 * @attr ref android.R.styleable#TextView_drawableLeft 1803 * @attr ref android.R.styleable#TextView_drawableTop 1804 * @attr ref android.R.styleable#TextView_drawableRight 1805 * @attr ref android.R.styleable#TextView_drawableBottom 1806 */ 1807 public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, 1808 Drawable right, Drawable bottom) { 1809 1810 if (left != null) { 1811 left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight()); 1812 } 1813 if (right != null) { 1814 right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight()); 1815 } 1816 if (top != null) { 1817 top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); 1818 } 1819 if (bottom != null) { 1820 bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); 1821 } 1822 setCompoundDrawables(left, top, right, bottom); 1823 } 1824 1825 /** 1826 * Sets the Drawables (if any) to appear to the start of, above, 1827 * to the end of, and below the text. Use null if you do not 1828 * want a Drawable there. The Drawables must already have had 1829 * {@link Drawable#setBounds} called. 1830 * 1831 * @attr ref android.R.styleable#TextView_drawableStart 1832 * @attr ref android.R.styleable#TextView_drawableTop 1833 * @attr ref android.R.styleable#TextView_drawableEnd 1834 * @attr ref android.R.styleable#TextView_drawableBottom 1835 * 1836 * @hide 1837 */ 1838 public void setCompoundDrawablesRelative(Drawable start, Drawable top, 1839 Drawable end, Drawable bottom) { 1840 Drawables dr = mDrawables; 1841 1842 final boolean drawables = start != null || top != null 1843 || end != null || bottom != null; 1844 1845 if (!drawables) { 1846 // Clearing drawables... can we free the data structure? 1847 if (dr != null) { 1848 if (dr.mDrawablePadding == 0) { 1849 mDrawables = null; 1850 } else { 1851 // We need to retain the last set padding, so just clear 1852 // out all of the fields in the existing structure. 1853 if (dr.mDrawableStart != null) dr.mDrawableStart.setCallback(null); 1854 dr.mDrawableStart = null; 1855 if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null); 1856 dr.mDrawableTop = null; 1857 if (dr.mDrawableEnd != null) dr.mDrawableEnd.setCallback(null); 1858 dr.mDrawableEnd = null; 1859 if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null); 1860 dr.mDrawableBottom = null; 1861 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 1862 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 1863 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1864 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1865 } 1866 } 1867 } else { 1868 if (dr == null) { 1869 mDrawables = dr = new Drawables(); 1870 } 1871 1872 if (dr.mDrawableStart != start && dr.mDrawableStart != null) { 1873 dr.mDrawableStart.setCallback(null); 1874 } 1875 dr.mDrawableStart = start; 1876 1877 if (dr.mDrawableTop != top && dr.mDrawableTop != null) { 1878 dr.mDrawableTop.setCallback(null); 1879 } 1880 dr.mDrawableTop = top; 1881 1882 if (dr.mDrawableEnd != end && dr.mDrawableEnd != null) { 1883 dr.mDrawableEnd.setCallback(null); 1884 } 1885 dr.mDrawableEnd = end; 1886 1887 if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { 1888 dr.mDrawableBottom.setCallback(null); 1889 } 1890 dr.mDrawableBottom = bottom; 1891 1892 final Rect compoundRect = dr.mCompoundRect; 1893 int[] state; 1894 1895 state = getDrawableState(); 1896 1897 if (start != null) { 1898 start.setState(state); 1899 start.copyBounds(compoundRect); 1900 start.setCallback(this); 1901 dr.mDrawableSizeStart = compoundRect.width(); 1902 dr.mDrawableHeightStart = compoundRect.height(); 1903 } else { 1904 dr.mDrawableSizeStart = dr.mDrawableHeightStart = 0; 1905 } 1906 1907 if (end != null) { 1908 end.setState(state); 1909 end.copyBounds(compoundRect); 1910 end.setCallback(this); 1911 dr.mDrawableSizeEnd = compoundRect.width(); 1912 dr.mDrawableHeightEnd = compoundRect.height(); 1913 } else { 1914 dr.mDrawableSizeEnd = dr.mDrawableHeightEnd = 0; 1915 } 1916 1917 if (top != null) { 1918 top.setState(state); 1919 top.copyBounds(compoundRect); 1920 top.setCallback(this); 1921 dr.mDrawableSizeTop = compoundRect.height(); 1922 dr.mDrawableWidthTop = compoundRect.width(); 1923 } else { 1924 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1925 } 1926 1927 if (bottom != null) { 1928 bottom.setState(state); 1929 bottom.copyBounds(compoundRect); 1930 bottom.setCallback(this); 1931 dr.mDrawableSizeBottom = compoundRect.height(); 1932 dr.mDrawableWidthBottom = compoundRect.width(); 1933 } else { 1934 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1935 } 1936 } 1937 1938 resolveDrawables(); 1939 invalidate(); 1940 requestLayout(); 1941 } 1942 1943 /** 1944 * Sets the Drawables (if any) to appear to the start of, above, 1945 * to the end of, and below the text. Use 0 if you do not 1946 * want a Drawable there. The Drawables' bounds will be set to 1947 * their intrinsic bounds. 1948 * 1949 * @param start Resource identifier of the start Drawable. 1950 * @param top Resource identifier of the top Drawable. 1951 * @param end Resource identifier of the end Drawable. 1952 * @param bottom Resource identifier of the bottom Drawable. 1953 * 1954 * @attr ref android.R.styleable#TextView_drawableStart 1955 * @attr ref android.R.styleable#TextView_drawableTop 1956 * @attr ref android.R.styleable#TextView_drawableEnd 1957 * @attr ref android.R.styleable#TextView_drawableBottom 1958 * 1959 * @hide 1960 */ 1961 public void setCompoundDrawablesRelativeWithIntrinsicBounds(int start, int top, int end, 1962 int bottom) { 1963 resetResolvedDrawables(); 1964 final Resources resources = getContext().getResources(); 1965 setCompoundDrawablesRelativeWithIntrinsicBounds( 1966 start != 0 ? resources.getDrawable(start) : null, 1967 top != 0 ? resources.getDrawable(top) : null, 1968 end != 0 ? resources.getDrawable(end) : null, 1969 bottom != 0 ? resources.getDrawable(bottom) : null); 1970 } 1971 1972 /** 1973 * Sets the Drawables (if any) to appear to the start of, above, 1974 * to the end of, and below the text. Use null if you do not 1975 * want a Drawable there. The Drawables' bounds will be set to 1976 * their intrinsic bounds. 1977 * 1978 * @attr ref android.R.styleable#TextView_drawableStart 1979 * @attr ref android.R.styleable#TextView_drawableTop 1980 * @attr ref android.R.styleable#TextView_drawableEnd 1981 * @attr ref android.R.styleable#TextView_drawableBottom 1982 * 1983 * @hide 1984 */ 1985 public void setCompoundDrawablesRelativeWithIntrinsicBounds(Drawable start, Drawable top, 1986 Drawable end, Drawable bottom) { 1987 1988 resetResolvedDrawables(); 1989 if (start != null) { 1990 start.setBounds(0, 0, start.getIntrinsicWidth(), start.getIntrinsicHeight()); 1991 } 1992 if (end != null) { 1993 end.setBounds(0, 0, end.getIntrinsicWidth(), end.getIntrinsicHeight()); 1994 } 1995 if (top != null) { 1996 top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); 1997 } 1998 if (bottom != null) { 1999 bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); 2000 } 2001 setCompoundDrawablesRelative(start, top, end, bottom); 2002 } 2003 2004 /** 2005 * Returns drawables for the left, top, right, and bottom borders. 2006 */ 2007 public Drawable[] getCompoundDrawables() { 2008 final Drawables dr = mDrawables; 2009 if (dr != null) { 2010 return new Drawable[] { 2011 dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom 2012 }; 2013 } else { 2014 return new Drawable[] { null, null, null, null }; 2015 } 2016 } 2017 2018 /** 2019 * Returns drawables for the start, top, end, and bottom borders. 2020 * 2021 * @hide 2022 */ 2023 public Drawable[] getCompoundDrawablesRelative() { 2024 final Drawables dr = mDrawables; 2025 if (dr != null) { 2026 return new Drawable[] { 2027 dr.mDrawableStart, dr.mDrawableTop, dr.mDrawableEnd, dr.mDrawableBottom 2028 }; 2029 } else { 2030 return new Drawable[] { null, null, null, null }; 2031 } 2032 } 2033 2034 /** 2035 * Sets the size of the padding between the compound drawables and 2036 * the text. 2037 * 2038 * @attr ref android.R.styleable#TextView_drawablePadding 2039 */ 2040 public void setCompoundDrawablePadding(int pad) { 2041 Drawables dr = mDrawables; 2042 if (pad == 0) { 2043 if (dr != null) { 2044 dr.mDrawablePadding = pad; 2045 } 2046 } else { 2047 if (dr == null) { 2048 mDrawables = dr = new Drawables(); 2049 } 2050 dr.mDrawablePadding = pad; 2051 } 2052 2053 invalidate(); 2054 requestLayout(); 2055 } 2056 2057 /** 2058 * Returns the padding between the compound drawables and the text. 2059 */ 2060 public int getCompoundDrawablePadding() { 2061 final Drawables dr = mDrawables; 2062 return dr != null ? dr.mDrawablePadding : 0; 2063 } 2064 2065 @Override 2066 public void setPadding(int left, int top, int right, int bottom) { 2067 if (left != mPaddingLeft || 2068 right != mPaddingRight || 2069 top != mPaddingTop || 2070 bottom != mPaddingBottom) { 2071 nullLayouts(); 2072 } 2073 2074 // the super call will requestLayout() 2075 super.setPadding(left, top, right, bottom); 2076 invalidate(); 2077 } 2078 2079 /** 2080 * Gets the autolink mask of the text. See {@link 2081 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 2082 * possible values. 2083 * 2084 * @attr ref android.R.styleable#TextView_autoLink 2085 */ 2086 public final int getAutoLinkMask() { 2087 return mAutoLinkMask; 2088 } 2089 2090 /** 2091 * Sets the text color, size, style, hint color, and highlight color 2092 * from the specified TextAppearance resource. 2093 */ 2094 public void setTextAppearance(Context context, int resid) { 2095 TypedArray appearance = 2096 context.obtainStyledAttributes(resid, 2097 com.android.internal.R.styleable.TextAppearance); 2098 2099 int color; 2100 ColorStateList colors; 2101 int ts; 2102 2103 color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0); 2104 if (color != 0) { 2105 setHighlightColor(color); 2106 } 2107 2108 colors = appearance.getColorStateList(com.android.internal.R.styleable. 2109 TextAppearance_textColor); 2110 if (colors != null) { 2111 setTextColor(colors); 2112 } 2113 2114 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable. 2115 TextAppearance_textSize, 0); 2116 if (ts != 0) { 2117 setRawTextSize(ts); 2118 } 2119 2120 colors = appearance.getColorStateList(com.android.internal.R.styleable. 2121 TextAppearance_textColorHint); 2122 if (colors != null) { 2123 setHintTextColor(colors); 2124 } 2125 2126 colors = appearance.getColorStateList(com.android.internal.R.styleable. 2127 TextAppearance_textColorLink); 2128 if (colors != null) { 2129 setLinkTextColor(colors); 2130 } 2131 2132 int typefaceIndex, styleIndex; 2133 2134 typefaceIndex = appearance.getInt(com.android.internal.R.styleable. 2135 TextAppearance_typeface, -1); 2136 styleIndex = appearance.getInt(com.android.internal.R.styleable. 2137 TextAppearance_textStyle, -1); 2138 2139 setTypefaceByIndex(typefaceIndex, styleIndex); 2140 2141 if (appearance.getBoolean(com.android.internal.R.styleable.TextAppearance_textAllCaps, 2142 false)) { 2143 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 2144 } 2145 2146 appearance.recycle(); 2147 } 2148 2149 /** 2150 * @return the size (in pixels) of the default text size in this TextView. 2151 */ 2152 public float getTextSize() { 2153 return mTextPaint.getTextSize(); 2154 } 2155 2156 /** 2157 * Set the default text size to the given value, interpreted as "scaled 2158 * pixel" units. This size is adjusted based on the current density and 2159 * user font size preference. 2160 * 2161 * @param size The scaled pixel size. 2162 * 2163 * @attr ref android.R.styleable#TextView_textSize 2164 */ 2165 @android.view.RemotableViewMethod 2166 public void setTextSize(float size) { 2167 setTextSize(TypedValue.COMPLEX_UNIT_SP, size); 2168 } 2169 2170 /** 2171 * Set the default text size to a given unit and value. See {@link 2172 * TypedValue} for the possible dimension units. 2173 * 2174 * @param unit The desired dimension unit. 2175 * @param size The desired size in the given units. 2176 * 2177 * @attr ref android.R.styleable#TextView_textSize 2178 */ 2179 public void setTextSize(int unit, float size) { 2180 Context c = getContext(); 2181 Resources r; 2182 2183 if (c == null) 2184 r = Resources.getSystem(); 2185 else 2186 r = c.getResources(); 2187 2188 setRawTextSize(TypedValue.applyDimension( 2189 unit, size, r.getDisplayMetrics())); 2190 } 2191 2192 private void setRawTextSize(float size) { 2193 if (size != mTextPaint.getTextSize()) { 2194 mTextPaint.setTextSize(size); 2195 2196 if (mLayout != null) { 2197 nullLayouts(); 2198 requestLayout(); 2199 invalidate(); 2200 } 2201 } 2202 } 2203 2204 /** 2205 * @return the extent by which text is currently being stretched 2206 * horizontally. This will usually be 1. 2207 */ 2208 public float getTextScaleX() { 2209 return mTextPaint.getTextScaleX(); 2210 } 2211 2212 /** 2213 * Sets the extent by which text should be stretched horizontally. 2214 * 2215 * @attr ref android.R.styleable#TextView_textScaleX 2216 */ 2217 @android.view.RemotableViewMethod 2218 public void setTextScaleX(float size) { 2219 if (size != mTextPaint.getTextScaleX()) { 2220 mUserSetTextScaleX = true; 2221 mTextPaint.setTextScaleX(size); 2222 2223 if (mLayout != null) { 2224 nullLayouts(); 2225 requestLayout(); 2226 invalidate(); 2227 } 2228 } 2229 } 2230 2231 /** 2232 * Sets the typeface and style in which the text should be displayed. 2233 * Note that not all Typeface families actually have bold and italic 2234 * variants, so you may need to use 2235 * {@link #setTypeface(Typeface, int)} to get the appearance 2236 * that you actually want. 2237 * 2238 * @attr ref android.R.styleable#TextView_typeface 2239 * @attr ref android.R.styleable#TextView_textStyle 2240 */ 2241 public void setTypeface(Typeface tf) { 2242 if (mTextPaint.getTypeface() != tf) { 2243 mTextPaint.setTypeface(tf); 2244 2245 if (mLayout != null) { 2246 nullLayouts(); 2247 requestLayout(); 2248 invalidate(); 2249 } 2250 } 2251 } 2252 2253 /** 2254 * @return the current typeface and style in which the text is being 2255 * displayed. 2256 */ 2257 public Typeface getTypeface() { 2258 return mTextPaint.getTypeface(); 2259 } 2260 2261 /** 2262 * Sets the text color for all the states (normal, selected, 2263 * focused) to be this color. 2264 * 2265 * @attr ref android.R.styleable#TextView_textColor 2266 */ 2267 @android.view.RemotableViewMethod 2268 public void setTextColor(int color) { 2269 mTextColor = ColorStateList.valueOf(color); 2270 updateTextColors(); 2271 } 2272 2273 /** 2274 * Sets the text color. 2275 * 2276 * @attr ref android.R.styleable#TextView_textColor 2277 */ 2278 public void setTextColor(ColorStateList colors) { 2279 if (colors == null) { 2280 throw new NullPointerException(); 2281 } 2282 2283 mTextColor = colors; 2284 updateTextColors(); 2285 } 2286 2287 /** 2288 * Return the set of text colors. 2289 * 2290 * @return Returns the set of text colors. 2291 */ 2292 public final ColorStateList getTextColors() { 2293 return mTextColor; 2294 } 2295 2296 /** 2297 * <p>Return the current color selected for normal text.</p> 2298 * 2299 * @return Returns the current text color. 2300 */ 2301 public final int getCurrentTextColor() { 2302 return mCurTextColor; 2303 } 2304 2305 /** 2306 * Sets the color used to display the selection highlight. 2307 * 2308 * @attr ref android.R.styleable#TextView_textColorHighlight 2309 */ 2310 @android.view.RemotableViewMethod 2311 public void setHighlightColor(int color) { 2312 if (mHighlightColor != color) { 2313 mHighlightColor = color; 2314 mTextDisplayListIsValid = false; 2315 invalidate(); 2316 } 2317 } 2318 2319 /** 2320 * Gives the text a shadow of the specified radius and color, the specified 2321 * distance from its normal position. 2322 * 2323 * @attr ref android.R.styleable#TextView_shadowColor 2324 * @attr ref android.R.styleable#TextView_shadowDx 2325 * @attr ref android.R.styleable#TextView_shadowDy 2326 * @attr ref android.R.styleable#TextView_shadowRadius 2327 */ 2328 public void setShadowLayer(float radius, float dx, float dy, int color) { 2329 mTextPaint.setShadowLayer(radius, dx, dy, color); 2330 2331 mShadowRadius = radius; 2332 mShadowDx = dx; 2333 mShadowDy = dy; 2334 2335 mTextDisplayListIsValid = false; 2336 invalidate(); 2337 } 2338 2339 /** 2340 * @return the base paint used for the text. Please use this only to 2341 * consult the Paint's properties and not to change them. 2342 */ 2343 public TextPaint getPaint() { 2344 return mTextPaint; 2345 } 2346 2347 /** 2348 * Sets the autolink mask of the text. See {@link 2349 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 2350 * possible values. 2351 * 2352 * @attr ref android.R.styleable#TextView_autoLink 2353 */ 2354 @android.view.RemotableViewMethod 2355 public final void setAutoLinkMask(int mask) { 2356 mAutoLinkMask = mask; 2357 } 2358 2359 /** 2360 * Sets whether the movement method will automatically be set to 2361 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 2362 * set to nonzero and links are detected in {@link #setText}. 2363 * The default is true. 2364 * 2365 * @attr ref android.R.styleable#TextView_linksClickable 2366 */ 2367 @android.view.RemotableViewMethod 2368 public final void setLinksClickable(boolean whether) { 2369 mLinksClickable = whether; 2370 } 2371 2372 /** 2373 * Returns whether the movement method will automatically be set to 2374 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 2375 * set to nonzero and links are detected in {@link #setText}. 2376 * The default is true. 2377 * 2378 * @attr ref android.R.styleable#TextView_linksClickable 2379 */ 2380 public final boolean getLinksClickable() { 2381 return mLinksClickable; 2382 } 2383 2384 /** 2385 * Returns the list of URLSpans attached to the text 2386 * (by {@link Linkify} or otherwise) if any. You can call 2387 * {@link URLSpan#getURL} on them to find where they link to 2388 * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd} 2389 * to find the region of the text they are attached to. 2390 */ 2391 public URLSpan[] getUrls() { 2392 if (mText instanceof Spanned) { 2393 return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class); 2394 } else { 2395 return new URLSpan[0]; 2396 } 2397 } 2398 2399 /** 2400 * Sets the color of the hint text. 2401 * 2402 * @attr ref android.R.styleable#TextView_textColorHint 2403 */ 2404 @android.view.RemotableViewMethod 2405 public final void setHintTextColor(int color) { 2406 mHintTextColor = ColorStateList.valueOf(color); 2407 updateTextColors(); 2408 } 2409 2410 /** 2411 * Sets the color of the hint text. 2412 * 2413 * @attr ref android.R.styleable#TextView_textColorHint 2414 */ 2415 public final void setHintTextColor(ColorStateList colors) { 2416 mHintTextColor = colors; 2417 updateTextColors(); 2418 } 2419 2420 /** 2421 * <p>Return the color used to paint the hint text.</p> 2422 * 2423 * @return Returns the list of hint text colors. 2424 */ 2425 public final ColorStateList getHintTextColors() { 2426 return mHintTextColor; 2427 } 2428 2429 /** 2430 * <p>Return the current color selected to paint the hint text.</p> 2431 * 2432 * @return Returns the current hint text color. 2433 */ 2434 public final int getCurrentHintTextColor() { 2435 return mHintTextColor != null ? mCurHintTextColor : mCurTextColor; 2436 } 2437 2438 /** 2439 * Sets the color of links in the text. 2440 * 2441 * @attr ref android.R.styleable#TextView_textColorLink 2442 */ 2443 @android.view.RemotableViewMethod 2444 public final void setLinkTextColor(int color) { 2445 mLinkTextColor = ColorStateList.valueOf(color); 2446 updateTextColors(); 2447 } 2448 2449 /** 2450 * Sets the color of links in the text. 2451 * 2452 * @attr ref android.R.styleable#TextView_textColorLink 2453 */ 2454 public final void setLinkTextColor(ColorStateList colors) { 2455 mLinkTextColor = colors; 2456 updateTextColors(); 2457 } 2458 2459 /** 2460 * <p>Returns the color used to paint links in the text.</p> 2461 * 2462 * @return Returns the list of link text colors. 2463 */ 2464 public final ColorStateList getLinkTextColors() { 2465 return mLinkTextColor; 2466 } 2467 2468 /** 2469 * Sets the horizontal alignment of the text and the 2470 * vertical gravity that will be used when there is extra space 2471 * in the TextView beyond what is required for the text itself. 2472 * 2473 * @see android.view.Gravity 2474 * @attr ref android.R.styleable#TextView_gravity 2475 */ 2476 public void setGravity(int gravity) { 2477 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 2478 gravity |= Gravity.START; 2479 } 2480 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 2481 gravity |= Gravity.TOP; 2482 } 2483 2484 boolean newLayout = false; 2485 2486 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) != 2487 (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK)) { 2488 newLayout = true; 2489 } 2490 2491 if (gravity != mGravity) { 2492 invalidate(); 2493 mLayoutAlignment = null; 2494 } 2495 2496 mGravity = gravity; 2497 2498 if (mLayout != null && newLayout) { 2499 // XXX this is heavy-handed because no actual content changes. 2500 int want = mLayout.getWidth(); 2501 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 2502 2503 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 2504 mRight - mLeft - getCompoundPaddingLeft() - 2505 getCompoundPaddingRight(), true); 2506 } 2507 } 2508 2509 /** 2510 * Returns the horizontal and vertical alignment of this TextView. 2511 * 2512 * @see android.view.Gravity 2513 * @attr ref android.R.styleable#TextView_gravity 2514 */ 2515 public int getGravity() { 2516 return mGravity; 2517 } 2518 2519 /** 2520 * @return the flags on the Paint being used to display the text. 2521 * @see Paint#getFlags 2522 */ 2523 public int getPaintFlags() { 2524 return mTextPaint.getFlags(); 2525 } 2526 2527 /** 2528 * Sets flags on the Paint being used to display the text and 2529 * reflows the text if they are different from the old flags. 2530 * @see Paint#setFlags 2531 */ 2532 @android.view.RemotableViewMethod 2533 public void setPaintFlags(int flags) { 2534 if (mTextPaint.getFlags() != flags) { 2535 mTextPaint.setFlags(flags); 2536 2537 if (mLayout != null) { 2538 nullLayouts(); 2539 requestLayout(); 2540 invalidate(); 2541 } 2542 } 2543 } 2544 2545 /** 2546 * Sets whether the text should be allowed to be wider than the 2547 * View is. If false, it will be wrapped to the width of the View. 2548 * 2549 * @attr ref android.R.styleable#TextView_scrollHorizontally 2550 */ 2551 public void setHorizontallyScrolling(boolean whether) { 2552 if (mHorizontallyScrolling != whether) { 2553 mHorizontallyScrolling = whether; 2554 2555 if (mLayout != null) { 2556 nullLayouts(); 2557 requestLayout(); 2558 invalidate(); 2559 } 2560 } 2561 } 2562 2563 /** 2564 * Returns whether the text is allowed to be wider than the View is. 2565 * If false, the text will be wrapped to the width of the View. 2566 * 2567 * @attr ref android.R.styleable#TextView_scrollHorizontally 2568 * @hide 2569 */ 2570 public boolean getHorizontallyScrolling() { 2571 return mHorizontallyScrolling; 2572 } 2573 2574 /** 2575 * Makes the TextView at least this many lines tall. 2576 * 2577 * Setting this value overrides any other (minimum) height setting. A single line TextView will 2578 * set this value to 1. 2579 * 2580 * @attr ref android.R.styleable#TextView_minLines 2581 */ 2582 @android.view.RemotableViewMethod 2583 public void setMinLines(int minlines) { 2584 mMinimum = minlines; 2585 mMinMode = LINES; 2586 2587 requestLayout(); 2588 invalidate(); 2589 } 2590 2591 /** 2592 * Makes the TextView at least this many pixels tall. 2593 * 2594 * Setting this value overrides any other (minimum) number of lines setting. 2595 * 2596 * @attr ref android.R.styleable#TextView_minHeight 2597 */ 2598 @android.view.RemotableViewMethod 2599 public void setMinHeight(int minHeight) { 2600 mMinimum = minHeight; 2601 mMinMode = PIXELS; 2602 2603 requestLayout(); 2604 invalidate(); 2605 } 2606 2607 /** 2608 * Makes the TextView at most this many lines tall. 2609 * 2610 * Setting this value overrides any other (maximum) height setting. 2611 * 2612 * @attr ref android.R.styleable#TextView_maxLines 2613 */ 2614 @android.view.RemotableViewMethod 2615 public void setMaxLines(int maxlines) { 2616 mMaximum = maxlines; 2617 mMaxMode = LINES; 2618 2619 requestLayout(); 2620 invalidate(); 2621 } 2622 2623 /** 2624 * Makes the TextView at most this many pixels tall. This option is mutually exclusive with the 2625 * {@link #setMaxLines(int)} method. 2626 * 2627 * Setting this value overrides any other (maximum) number of lines setting. 2628 * 2629 * @attr ref android.R.styleable#TextView_maxHeight 2630 */ 2631 @android.view.RemotableViewMethod 2632 public void setMaxHeight(int maxHeight) { 2633 mMaximum = maxHeight; 2634 mMaxMode = PIXELS; 2635 2636 requestLayout(); 2637 invalidate(); 2638 } 2639 2640 /** 2641 * Makes the TextView exactly this many lines tall. 2642 * 2643 * Note that setting this value overrides any other (minimum / maximum) number of lines or 2644 * height setting. A single line TextView will set this value to 1. 2645 * 2646 * @attr ref android.R.styleable#TextView_lines 2647 */ 2648 @android.view.RemotableViewMethod 2649 public void setLines(int lines) { 2650 mMaximum = mMinimum = lines; 2651 mMaxMode = mMinMode = LINES; 2652 2653 requestLayout(); 2654 invalidate(); 2655 } 2656 2657 /** 2658 * Makes the TextView exactly this many pixels tall. 2659 * You could do the same thing by specifying this number in the 2660 * LayoutParams. 2661 * 2662 * Note that setting this value overrides any other (minimum / maximum) number of lines or 2663 * height setting. 2664 * 2665 * @attr ref android.R.styleable#TextView_height 2666 */ 2667 @android.view.RemotableViewMethod 2668 public void setHeight(int pixels) { 2669 mMaximum = mMinimum = pixels; 2670 mMaxMode = mMinMode = PIXELS; 2671 2672 requestLayout(); 2673 invalidate(); 2674 } 2675 2676 /** 2677 * Makes the TextView at least this many ems wide 2678 * 2679 * @attr ref android.R.styleable#TextView_minEms 2680 */ 2681 @android.view.RemotableViewMethod 2682 public void setMinEms(int minems) { 2683 mMinWidth = minems; 2684 mMinWidthMode = EMS; 2685 2686 requestLayout(); 2687 invalidate(); 2688 } 2689 2690 /** 2691 * Makes the TextView at least this many pixels wide 2692 * 2693 * @attr ref android.R.styleable#TextView_minWidth 2694 */ 2695 @android.view.RemotableViewMethod 2696 public void setMinWidth(int minpixels) { 2697 mMinWidth = minpixels; 2698 mMinWidthMode = PIXELS; 2699 2700 requestLayout(); 2701 invalidate(); 2702 } 2703 2704 /** 2705 * Makes the TextView at most this many ems wide 2706 * 2707 * @attr ref android.R.styleable#TextView_maxEms 2708 */ 2709 @android.view.RemotableViewMethod 2710 public void setMaxEms(int maxems) { 2711 mMaxWidth = maxems; 2712 mMaxWidthMode = EMS; 2713 2714 requestLayout(); 2715 invalidate(); 2716 } 2717 2718 /** 2719 * Makes the TextView at most this many pixels wide 2720 * 2721 * @attr ref android.R.styleable#TextView_maxWidth 2722 */ 2723 @android.view.RemotableViewMethod 2724 public void setMaxWidth(int maxpixels) { 2725 mMaxWidth = maxpixels; 2726 mMaxWidthMode = PIXELS; 2727 2728 requestLayout(); 2729 invalidate(); 2730 } 2731 2732 /** 2733 * Makes the TextView exactly this many ems wide 2734 * 2735 * @attr ref android.R.styleable#TextView_ems 2736 */ 2737 @android.view.RemotableViewMethod 2738 public void setEms(int ems) { 2739 mMaxWidth = mMinWidth = ems; 2740 mMaxWidthMode = mMinWidthMode = EMS; 2741 2742 requestLayout(); 2743 invalidate(); 2744 } 2745 2746 /** 2747 * Makes the TextView exactly this many pixels wide. 2748 * You could do the same thing by specifying this number in the 2749 * LayoutParams. 2750 * 2751 * @attr ref android.R.styleable#TextView_width 2752 */ 2753 @android.view.RemotableViewMethod 2754 public void setWidth(int pixels) { 2755 mMaxWidth = mMinWidth = pixels; 2756 mMaxWidthMode = mMinWidthMode = PIXELS; 2757 2758 requestLayout(); 2759 invalidate(); 2760 } 2761 2762 2763 /** 2764 * Sets line spacing for this TextView. Each line will have its height 2765 * multiplied by <code>mult</code> and have <code>add</code> added to it. 2766 * 2767 * @attr ref android.R.styleable#TextView_lineSpacingExtra 2768 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 2769 */ 2770 public void setLineSpacing(float add, float mult) { 2771 if (mSpacingAdd != add || mSpacingMult != mult) { 2772 mSpacingAdd = add; 2773 mSpacingMult = mult; 2774 2775 if (mLayout != null) { 2776 nullLayouts(); 2777 requestLayout(); 2778 invalidate(); 2779 } 2780 } 2781 } 2782 2783 /** 2784 * Convenience method: Append the specified text to the TextView's 2785 * display buffer, upgrading it to BufferType.EDITABLE if it was 2786 * not already editable. 2787 */ 2788 public final void append(CharSequence text) { 2789 append(text, 0, text.length()); 2790 } 2791 2792 /** 2793 * Convenience method: Append the specified text slice to the TextView's 2794 * display buffer, upgrading it to BufferType.EDITABLE if it was 2795 * not already editable. 2796 */ 2797 public void append(CharSequence text, int start, int end) { 2798 if (!(mText instanceof Editable)) { 2799 setText(mText, BufferType.EDITABLE); 2800 } 2801 2802 ((Editable) mText).append(text, start, end); 2803 } 2804 2805 private void updateTextColors() { 2806 boolean inval = false; 2807 int color = mTextColor.getColorForState(getDrawableState(), 0); 2808 if (color != mCurTextColor) { 2809 mCurTextColor = color; 2810 inval = true; 2811 } 2812 if (mLinkTextColor != null) { 2813 color = mLinkTextColor.getColorForState(getDrawableState(), 0); 2814 if (color != mTextPaint.linkColor) { 2815 mTextPaint.linkColor = color; 2816 inval = true; 2817 } 2818 } 2819 if (mHintTextColor != null) { 2820 color = mHintTextColor.getColorForState(getDrawableState(), 0); 2821 if (color != mCurHintTextColor && mText.length() == 0) { 2822 mCurHintTextColor = color; 2823 inval = true; 2824 } 2825 } 2826 if (inval) { 2827 mTextDisplayListIsValid = false; 2828 invalidate(); 2829 } 2830 } 2831 2832 @Override 2833 protected void drawableStateChanged() { 2834 super.drawableStateChanged(); 2835 if (mTextColor != null && mTextColor.isStateful() 2836 || (mHintTextColor != null && mHintTextColor.isStateful()) 2837 || (mLinkTextColor != null && mLinkTextColor.isStateful())) { 2838 updateTextColors(); 2839 } 2840 2841 final Drawables dr = mDrawables; 2842 if (dr != null) { 2843 int[] state = getDrawableState(); 2844 if (dr.mDrawableTop != null && dr.mDrawableTop.isStateful()) { 2845 dr.mDrawableTop.setState(state); 2846 } 2847 if (dr.mDrawableBottom != null && dr.mDrawableBottom.isStateful()) { 2848 dr.mDrawableBottom.setState(state); 2849 } 2850 if (dr.mDrawableLeft != null && dr.mDrawableLeft.isStateful()) { 2851 dr.mDrawableLeft.setState(state); 2852 } 2853 if (dr.mDrawableRight != null && dr.mDrawableRight.isStateful()) { 2854 dr.mDrawableRight.setState(state); 2855 } 2856 if (dr.mDrawableStart != null && dr.mDrawableStart.isStateful()) { 2857 dr.mDrawableStart.setState(state); 2858 } 2859 if (dr.mDrawableEnd != null && dr.mDrawableEnd.isStateful()) { 2860 dr.mDrawableEnd.setState(state); 2861 } 2862 } 2863 } 2864 2865 /** 2866 * User interface state that is stored by TextView for implementing 2867 * {@link View#onSaveInstanceState}. 2868 */ 2869 public static class SavedState extends BaseSavedState { 2870 int selStart; 2871 int selEnd; 2872 CharSequence text; 2873 boolean frozenWithFocus; 2874 CharSequence error; 2875 2876 SavedState(Parcelable superState) { 2877 super(superState); 2878 } 2879 2880 @Override 2881 public void writeToParcel(Parcel out, int flags) { 2882 super.writeToParcel(out, flags); 2883 out.writeInt(selStart); 2884 out.writeInt(selEnd); 2885 out.writeInt(frozenWithFocus ? 1 : 0); 2886 TextUtils.writeToParcel(text, out, flags); 2887 2888 if (error == null) { 2889 out.writeInt(0); 2890 } else { 2891 out.writeInt(1); 2892 TextUtils.writeToParcel(error, out, flags); 2893 } 2894 } 2895 2896 @Override 2897 public String toString() { 2898 String str = "TextView.SavedState{" 2899 + Integer.toHexString(System.identityHashCode(this)) 2900 + " start=" + selStart + " end=" + selEnd; 2901 if (text != null) { 2902 str += " text=" + text; 2903 } 2904 return str + "}"; 2905 } 2906 2907 @SuppressWarnings("hiding") 2908 public static final Parcelable.Creator<SavedState> CREATOR 2909 = new Parcelable.Creator<SavedState>() { 2910 public SavedState createFromParcel(Parcel in) { 2911 return new SavedState(in); 2912 } 2913 2914 public SavedState[] newArray(int size) { 2915 return new SavedState[size]; 2916 } 2917 }; 2918 2919 private SavedState(Parcel in) { 2920 super(in); 2921 selStart = in.readInt(); 2922 selEnd = in.readInt(); 2923 frozenWithFocus = (in.readInt() != 0); 2924 text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 2925 2926 if (in.readInt() != 0) { 2927 error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 2928 } 2929 } 2930 } 2931 2932 @Override 2933 public Parcelable onSaveInstanceState() { 2934 Parcelable superState = super.onSaveInstanceState(); 2935 2936 // Save state if we are forced to 2937 boolean save = mFreezesText; 2938 int start = 0; 2939 int end = 0; 2940 2941 if (mText != null) { 2942 start = getSelectionStart(); 2943 end = getSelectionEnd(); 2944 if (start >= 0 || end >= 0) { 2945 // Or save state if there is a selection 2946 save = true; 2947 } 2948 } 2949 2950 if (save) { 2951 SavedState ss = new SavedState(superState); 2952 // XXX Should also save the current scroll position! 2953 ss.selStart = start; 2954 ss.selEnd = end; 2955 2956 if (mText instanceof Spanned) { 2957 /* 2958 * Calling setText() strips off any ChangeWatchers; 2959 * strip them now to avoid leaking references. 2960 * But do it to a copy so that if there are any 2961 * further changes to the text of this view, it 2962 * won't get into an inconsistent state. 2963 */ 2964 2965 Spannable sp = new SpannableString(mText); 2966 2967 for (ChangeWatcher cw : sp.getSpans(0, sp.length(), ChangeWatcher.class)) { 2968 sp.removeSpan(cw); 2969 } 2970 2971 removeMisspelledSpans(sp); 2972 sp.removeSpan(mSuggestionRangeSpan); 2973 2974 ss.text = sp; 2975 } else { 2976 ss.text = mText.toString(); 2977 } 2978 2979 if (isFocused() && start >= 0 && end >= 0) { 2980 ss.frozenWithFocus = true; 2981 } 2982 2983 ss.error = mError; 2984 2985 return ss; 2986 } 2987 2988 return superState; 2989 } 2990 2991 void removeMisspelledSpans(Spannable spannable) { 2992 SuggestionSpan[] suggestionSpans = spannable.getSpans(0, spannable.length(), 2993 SuggestionSpan.class); 2994 for (int i = 0; i < suggestionSpans.length; i++) { 2995 int flags = suggestionSpans[i].getFlags(); 2996 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 2997 && (flags & SuggestionSpan.FLAG_MISSPELLED) != 0) { 2998 spannable.removeSpan(suggestionSpans[i]); 2999 } 3000 } 3001 } 3002 3003 @Override 3004 public void onRestoreInstanceState(Parcelable state) { 3005 if (!(state instanceof SavedState)) { 3006 super.onRestoreInstanceState(state); 3007 return; 3008 } 3009 3010 SavedState ss = (SavedState)state; 3011 super.onRestoreInstanceState(ss.getSuperState()); 3012 3013 // XXX restore buffer type too, as well as lots of other stuff 3014 if (ss.text != null) { 3015 setText(ss.text); 3016 } 3017 3018 if (ss.selStart >= 0 && ss.selEnd >= 0) { 3019 if (mText instanceof Spannable) { 3020 int len = mText.length(); 3021 3022 if (ss.selStart > len || ss.selEnd > len) { 3023 String restored = ""; 3024 3025 if (ss.text != null) { 3026 restored = "(restored) "; 3027 } 3028 3029 Log.e(LOG_TAG, "Saved cursor position " + ss.selStart + 3030 "/" + ss.selEnd + " out of range for " + restored + 3031 "text " + mText); 3032 } else { 3033 Selection.setSelection((Spannable) mText, ss.selStart, 3034 ss.selEnd); 3035 3036 if (ss.frozenWithFocus) { 3037 mFrozenWithFocus = true; 3038 } 3039 } 3040 } 3041 } 3042 3043 if (ss.error != null) { 3044 final CharSequence error = ss.error; 3045 // Display the error later, after the first layout pass 3046 post(new Runnable() { 3047 public void run() { 3048 setError(error); 3049 } 3050 }); 3051 } 3052 } 3053 3054 /** 3055 * Control whether this text view saves its entire text contents when 3056 * freezing to an icicle, in addition to dynamic state such as cursor 3057 * position. By default this is false, not saving the text. Set to true 3058 * if the text in the text view is not being saved somewhere else in 3059 * persistent storage (such as in a content provider) so that if the 3060 * view is later thawed the user will not lose their data. 3061 * 3062 * @param freezesText Controls whether a frozen icicle should include the 3063 * entire text data: true to include it, false to not. 3064 * 3065 * @attr ref android.R.styleable#TextView_freezesText 3066 */ 3067 @android.view.RemotableViewMethod 3068 public void setFreezesText(boolean freezesText) { 3069 mFreezesText = freezesText; 3070 } 3071 3072 /** 3073 * Return whether this text view is including its entire text contents 3074 * in frozen icicles. 3075 * 3076 * @return Returns true if text is included, false if it isn't. 3077 * 3078 * @see #setFreezesText 3079 */ 3080 public boolean getFreezesText() { 3081 return mFreezesText; 3082 } 3083 3084 /////////////////////////////////////////////////////////////////////////// 3085 3086 /** 3087 * Sets the Factory used to create new Editables. 3088 */ 3089 public final void setEditableFactory(Editable.Factory factory) { 3090 mEditableFactory = factory; 3091 setText(mText); 3092 } 3093 3094 /** 3095 * Sets the Factory used to create new Spannables. 3096 */ 3097 public final void setSpannableFactory(Spannable.Factory factory) { 3098 mSpannableFactory = factory; 3099 setText(mText); 3100 } 3101 3102 /** 3103 * Sets the string value of the TextView. TextView <em>does not</em> accept 3104 * HTML-like formatting, which you can do with text strings in XML resource files. 3105 * To style your strings, attach android.text.style.* objects to a 3106 * {@link android.text.SpannableString SpannableString}, or see the 3107 * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources"> 3108 * Available Resource Types</a> documentation for an example of setting 3109 * formatted text in the XML resource file. 3110 * 3111 * @attr ref android.R.styleable#TextView_text 3112 */ 3113 @android.view.RemotableViewMethod 3114 public final void setText(CharSequence text) { 3115 setText(text, mBufferType); 3116 } 3117 3118 /** 3119 * Like {@link #setText(CharSequence)}, 3120 * except that the cursor position (if any) is retained in the new text. 3121 * 3122 * @param text The new text to place in the text view. 3123 * 3124 * @see #setText(CharSequence) 3125 */ 3126 @android.view.RemotableViewMethod 3127 public final void setTextKeepState(CharSequence text) { 3128 setTextKeepState(text, mBufferType); 3129 } 3130 3131 /** 3132 * Sets the text that this TextView is to display (see 3133 * {@link #setText(CharSequence)}) and also sets whether it is stored 3134 * in a styleable/spannable buffer and whether it is editable. 3135 * 3136 * @attr ref android.R.styleable#TextView_text 3137 * @attr ref android.R.styleable#TextView_bufferType 3138 */ 3139 public void setText(CharSequence text, BufferType type) { 3140 setText(text, type, true, 0); 3141 3142 if (mCharWrapper != null) { 3143 mCharWrapper.mChars = null; 3144 } 3145 } 3146 3147 private void setText(CharSequence text, BufferType type, 3148 boolean notifyBefore, int oldlen) { 3149 if (text == null) { 3150 text = ""; 3151 } 3152 3153 // If suggestions are not enabled, remove the suggestion spans from the text 3154 if (!isSuggestionsEnabled()) { 3155 text = removeSuggestionSpans(text); 3156 } 3157 3158 if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f); 3159 3160 if (text instanceof Spanned && 3161 ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) { 3162 if (ViewConfiguration.get(mContext).isFadingMarqueeEnabled()) { 3163 setHorizontalFadingEdgeEnabled(true); 3164 mMarqueeFadeMode = MARQUEE_FADE_NORMAL; 3165 } else { 3166 setHorizontalFadingEdgeEnabled(false); 3167 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 3168 } 3169 setEllipsize(TextUtils.TruncateAt.MARQUEE); 3170 } 3171 3172 int n = mFilters.length; 3173 for (int i = 0; i < n; i++) { 3174 CharSequence out = mFilters[i].filter(text, 0, text.length(), EMPTY_SPANNED, 0, 0); 3175 if (out != null) { 3176 text = out; 3177 } 3178 } 3179 3180 if (notifyBefore) { 3181 if (mText != null) { 3182 oldlen = mText.length(); 3183 sendBeforeTextChanged(mText, 0, oldlen, text.length()); 3184 } else { 3185 sendBeforeTextChanged("", 0, 0, text.length()); 3186 } 3187 } 3188 3189 boolean needEditableForNotification = false; 3190 3191 if (mListeners != null && mListeners.size() != 0) { 3192 needEditableForNotification = true; 3193 } 3194 3195 if (type == BufferType.EDITABLE || mInput != null || needEditableForNotification) { 3196 Editable t = mEditableFactory.newEditable(text); 3197 text = t; 3198 setFilters(t, mFilters); 3199 InputMethodManager imm = InputMethodManager.peekInstance(); 3200 if (imm != null) imm.restartInput(this); 3201 } else if (type == BufferType.SPANNABLE || mMovement != null) { 3202 text = mSpannableFactory.newSpannable(text); 3203 } else if (!(text instanceof CharWrapper)) { 3204 text = TextUtils.stringOrSpannedString(text); 3205 } 3206 3207 if (mAutoLinkMask != 0) { 3208 Spannable s2; 3209 3210 if (type == BufferType.EDITABLE || text instanceof Spannable) { 3211 s2 = (Spannable) text; 3212 } else { 3213 s2 = mSpannableFactory.newSpannable(text); 3214 } 3215 3216 if (Linkify.addLinks(s2, mAutoLinkMask)) { 3217 text = s2; 3218 type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE; 3219 3220 /* 3221 * We must go ahead and set the text before changing the 3222 * movement method, because setMovementMethod() may call 3223 * setText() again to try to upgrade the buffer type. 3224 */ 3225 mText = text; 3226 3227 // Do not change the movement method for text that support text selection as it 3228 // would prevent an arbitrary cursor displacement. 3229 if (mLinksClickable && !textCanBeSelected()) { 3230 setMovementMethod(LinkMovementMethod.getInstance()); 3231 } 3232 } 3233 } 3234 3235 mBufferType = type; 3236 mText = text; 3237 3238 if (mTransformation == null) { 3239 mTransformed = text; 3240 } else { 3241 mTransformed = mTransformation.getTransformation(text, this); 3242 } 3243 3244 final int textLength = text.length(); 3245 3246 if (text instanceof Spannable && !mAllowTransformationLengthChange) { 3247 Spannable sp = (Spannable) text; 3248 3249 // Remove any ChangeWatchers that might have come 3250 // from other TextViews. 3251 final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class); 3252 final int count = watchers.length; 3253 for (int i = 0; i < count; i++) 3254 sp.removeSpan(watchers[i]); 3255 3256 if (mChangeWatcher == null) 3257 mChangeWatcher = new ChangeWatcher(); 3258 3259 sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE | 3260 (PRIORITY << Spanned.SPAN_PRIORITY_SHIFT)); 3261 3262 if (mInput != null) { 3263 sp.setSpan(mInput, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 3264 } 3265 3266 if (mTransformation != null) { 3267 sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 3268 } 3269 3270 if (mMovement != null) { 3271 mMovement.initialize(this, (Spannable) text); 3272 3273 /* 3274 * Initializing the movement method will have set the 3275 * selection, so reset mSelectionMoved to keep that from 3276 * interfering with the normal on-focus selection-setting. 3277 */ 3278 mSelectionMoved = false; 3279 } 3280 } 3281 3282 if (mLayout != null) { 3283 checkForRelayout(); 3284 } 3285 3286 sendOnTextChanged(text, 0, oldlen, textLength); 3287 onTextChanged(text, 0, oldlen, textLength); 3288 3289 if (needEditableForNotification) { 3290 sendAfterTextChanged((Editable) text); 3291 } 3292 3293 // SelectionModifierCursorController depends on textCanBeSelected, which depends on text 3294 prepareCursorControllers(); 3295 } 3296 3297 /** 3298 * Sets the TextView to display the specified slice of the specified 3299 * char array. You must promise that you will not change the contents 3300 * of the array except for right before another call to setText(), 3301 * since the TextView has no way to know that the text 3302 * has changed and that it needs to invalidate and re-layout. 3303 */ 3304 public final void setText(char[] text, int start, int len) { 3305 int oldlen = 0; 3306 3307 if (start < 0 || len < 0 || start + len > text.length) { 3308 throw new IndexOutOfBoundsException(start + ", " + len); 3309 } 3310 3311 /* 3312 * We must do the before-notification here ourselves because if 3313 * the old text is a CharWrapper we destroy it before calling 3314 * into the normal path. 3315 */ 3316 if (mText != null) { 3317 oldlen = mText.length(); 3318 sendBeforeTextChanged(mText, 0, oldlen, len); 3319 } else { 3320 sendBeforeTextChanged("", 0, 0, len); 3321 } 3322 3323 if (mCharWrapper == null) { 3324 mCharWrapper = new CharWrapper(text, start, len); 3325 } else { 3326 mCharWrapper.set(text, start, len); 3327 } 3328 3329 setText(mCharWrapper, mBufferType, false, oldlen); 3330 } 3331 3332 private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations { 3333 private char[] mChars; 3334 private int mStart, mLength; 3335 3336 public CharWrapper(char[] chars, int start, int len) { 3337 mChars = chars; 3338 mStart = start; 3339 mLength = len; 3340 } 3341 3342 /* package */ void set(char[] chars, int start, int len) { 3343 mChars = chars; 3344 mStart = start; 3345 mLength = len; 3346 } 3347 3348 public int length() { 3349 return mLength; 3350 } 3351 3352 public char charAt(int off) { 3353 return mChars[off + mStart]; 3354 } 3355 3356 @Override 3357 public String toString() { 3358 return new String(mChars, mStart, mLength); 3359 } 3360 3361 public CharSequence subSequence(int start, int end) { 3362 if (start < 0 || end < 0 || start > mLength || end > mLength) { 3363 throw new IndexOutOfBoundsException(start + ", " + end); 3364 } 3365 3366 return new String(mChars, start + mStart, end - start); 3367 } 3368 3369 public void getChars(int start, int end, char[] buf, int off) { 3370 if (start < 0 || end < 0 || start > mLength || end > mLength) { 3371 throw new IndexOutOfBoundsException(start + ", " + end); 3372 } 3373 3374 System.arraycopy(mChars, start + mStart, buf, off, end - start); 3375 } 3376 3377 public void drawText(Canvas c, int start, int end, 3378 float x, float y, Paint p) { 3379 c.drawText(mChars, start + mStart, end - start, x, y, p); 3380 } 3381 3382 public void drawTextRun(Canvas c, int start, int end, 3383 int contextStart, int contextEnd, float x, float y, int flags, Paint p) { 3384 int count = end - start; 3385 int contextCount = contextEnd - contextStart; 3386 c.drawTextRun(mChars, start + mStart, count, contextStart + mStart, 3387 contextCount, x, y, flags, p); 3388 } 3389 3390 public float measureText(int start, int end, Paint p) { 3391 return p.measureText(mChars, start + mStart, end - start); 3392 } 3393 3394 public int getTextWidths(int start, int end, float[] widths, Paint p) { 3395 return p.getTextWidths(mChars, start + mStart, end - start, widths); 3396 } 3397 3398 public float getTextRunAdvances(int start, int end, int contextStart, 3399 int contextEnd, int flags, float[] advances, int advancesIndex, 3400 Paint p) { 3401 int count = end - start; 3402 int contextCount = contextEnd - contextStart; 3403 return p.getTextRunAdvances(mChars, start + mStart, count, 3404 contextStart + mStart, contextCount, flags, advances, 3405 advancesIndex); 3406 } 3407 3408 public float getTextRunAdvances(int start, int end, int contextStart, 3409 int contextEnd, int flags, float[] advances, int advancesIndex, 3410 Paint p, int reserved) { 3411 int count = end - start; 3412 int contextCount = contextEnd - contextStart; 3413 return p.getTextRunAdvances(mChars, start + mStart, count, 3414 contextStart + mStart, contextCount, flags, advances, 3415 advancesIndex, reserved); 3416 } 3417 3418 public int getTextRunCursor(int contextStart, int contextEnd, int flags, 3419 int offset, int cursorOpt, Paint p) { 3420 int contextCount = contextEnd - contextStart; 3421 return p.getTextRunCursor(mChars, contextStart + mStart, 3422 contextCount, flags, offset + mStart, cursorOpt); 3423 } 3424 } 3425 3426 /** 3427 * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)}, 3428 * except that the cursor position (if any) is retained in the new text. 3429 * 3430 * @see #setText(CharSequence, android.widget.TextView.BufferType) 3431 */ 3432 public final void setTextKeepState(CharSequence text, BufferType type) { 3433 int start = getSelectionStart(); 3434 int end = getSelectionEnd(); 3435 int len = text.length(); 3436 3437 setText(text, type); 3438 3439 if (start >= 0 || end >= 0) { 3440 if (mText instanceof Spannable) { 3441 Selection.setSelection((Spannable) mText, 3442 Math.max(0, Math.min(start, len)), 3443 Math.max(0, Math.min(end, len))); 3444 } 3445 } 3446 } 3447 3448 @android.view.RemotableViewMethod 3449 public final void setText(int resid) { 3450 setText(getContext().getResources().getText(resid)); 3451 } 3452 3453 public final void setText(int resid, BufferType type) { 3454 setText(getContext().getResources().getText(resid), type); 3455 } 3456 3457 /** 3458 * Sets the text to be displayed when the text of the TextView is empty. 3459 * Null means to use the normal empty text. The hint does not currently 3460 * participate in determining the size of the view. 3461 * 3462 * @attr ref android.R.styleable#TextView_hint 3463 */ 3464 @android.view.RemotableViewMethod 3465 public final void setHint(CharSequence hint) { 3466 mHint = TextUtils.stringOrSpannedString(hint); 3467 3468 if (mLayout != null) { 3469 checkForRelayout(); 3470 } 3471 3472 if (mText.length() == 0) { 3473 invalidate(); 3474 } 3475 3476 // Invalidate display list if hint will be used 3477 if (mText.length() == 0 && mHint != null) mTextDisplayListIsValid = false; 3478 } 3479 3480 /** 3481 * Sets the text to be displayed when the text of the TextView is empty, 3482 * from a resource. 3483 * 3484 * @attr ref android.R.styleable#TextView_hint 3485 */ 3486 @android.view.RemotableViewMethod 3487 public final void setHint(int resid) { 3488 setHint(getContext().getResources().getText(resid)); 3489 } 3490 3491 /** 3492 * Returns the hint that is displayed when the text of the TextView 3493 * is empty. 3494 * 3495 * @attr ref android.R.styleable#TextView_hint 3496 */ 3497 @ViewDebug.CapturedViewProperty 3498 public CharSequence getHint() { 3499 return mHint; 3500 } 3501 3502 private static boolean isMultilineInputType(int type) { 3503 return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == 3504 (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); 3505 } 3506 3507 /** 3508 * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This 3509 * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, 3510 * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} 3511 * then a soft keyboard will not be displayed for this text view. 3512 * 3513 * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be 3514 * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input 3515 * type. 3516 * 3517 * @see #getInputType() 3518 * @see #setRawInputType(int) 3519 * @see android.text.InputType 3520 * @attr ref android.R.styleable#TextView_inputType 3521 */ 3522 public void setInputType(int type) { 3523 final boolean wasPassword = isPasswordInputType(mInputType); 3524 final boolean wasVisiblePassword = isVisiblePasswordInputType(mInputType); 3525 setInputType(type, false); 3526 final boolean isPassword = isPasswordInputType(type); 3527 final boolean isVisiblePassword = isVisiblePasswordInputType(type); 3528 boolean forceUpdate = false; 3529 if (isPassword) { 3530 setTransformationMethod(PasswordTransformationMethod.getInstance()); 3531 setTypefaceByIndex(MONOSPACE, 0); 3532 } else if (isVisiblePassword) { 3533 if (mTransformation == PasswordTransformationMethod.getInstance()) { 3534 forceUpdate = true; 3535 } 3536 setTypefaceByIndex(MONOSPACE, 0); 3537 } else if (wasPassword || wasVisiblePassword) { 3538 // not in password mode, clean up typeface and transformation 3539 setTypefaceByIndex(-1, -1); 3540 if (mTransformation == PasswordTransformationMethod.getInstance()) { 3541 forceUpdate = true; 3542 } 3543 } 3544 3545 boolean singleLine = !isMultilineInputType(type); 3546 3547 // We need to update the single line mode if it has changed or we 3548 // were previously in password mode. 3549 if (mSingleLine != singleLine || forceUpdate) { 3550 // Change single line mode, but only change the transformation if 3551 // we are not in password mode. 3552 applySingleLine(singleLine, !isPassword, true); 3553 } 3554 3555 if (!isSuggestionsEnabled()) { 3556 mText = removeSuggestionSpans(mText); 3557 } 3558 3559 InputMethodManager imm = InputMethodManager.peekInstance(); 3560 if (imm != null) imm.restartInput(this); 3561 } 3562 3563 /** 3564 * It would be better to rely on the input type for everything. A password inputType should have 3565 * a password transformation. We should hence use isPasswordInputType instead of this method. 3566 * 3567 * We should: 3568 * - Call setInputType in setKeyListener instead of changing the input type directly (which 3569 * would install the correct transformation). 3570 * - Refuse the installation of a non-password transformation in setTransformation if the input 3571 * type is password. 3572 * 3573 * However, this is like this for legacy reasons and we cannot break existing apps. This method 3574 * is useful since it matches what the user can see (obfuscated text or not). 3575 * 3576 * @return true if the current transformation method is of the password type. 3577 */ 3578 private boolean hasPasswordTransformationMethod() { 3579 return mTransformation instanceof PasswordTransformationMethod; 3580 } 3581 3582 private static boolean isPasswordInputType(int inputType) { 3583 final int variation = 3584 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 3585 return variation 3586 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD) 3587 || variation 3588 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD) 3589 || variation 3590 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 3591 } 3592 3593 private static boolean isVisiblePasswordInputType(int inputType) { 3594 final int variation = 3595 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 3596 return variation 3597 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); 3598 } 3599 3600 /** 3601 * Directly change the content type integer of the text view, without 3602 * modifying any other state. 3603 * @see #setInputType(int) 3604 * @see android.text.InputType 3605 * @attr ref android.R.styleable#TextView_inputType 3606 */ 3607 public void setRawInputType(int type) { 3608 mInputType = type; 3609 } 3610 3611 private void setInputType(int type, boolean direct) { 3612 final int cls = type & EditorInfo.TYPE_MASK_CLASS; 3613 KeyListener input; 3614 if (cls == EditorInfo.TYPE_CLASS_TEXT) { 3615 boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0; 3616 TextKeyListener.Capitalize cap; 3617 if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) { 3618 cap = TextKeyListener.Capitalize.CHARACTERS; 3619 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) { 3620 cap = TextKeyListener.Capitalize.WORDS; 3621 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) { 3622 cap = TextKeyListener.Capitalize.SENTENCES; 3623 } else { 3624 cap = TextKeyListener.Capitalize.NONE; 3625 } 3626 input = TextKeyListener.getInstance(autotext, cap); 3627 } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) { 3628 input = DigitsKeyListener.getInstance( 3629 (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0, 3630 (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0); 3631 } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) { 3632 switch (type & EditorInfo.TYPE_MASK_VARIATION) { 3633 case EditorInfo.TYPE_DATETIME_VARIATION_DATE: 3634 input = DateKeyListener.getInstance(); 3635 break; 3636 case EditorInfo.TYPE_DATETIME_VARIATION_TIME: 3637 input = TimeKeyListener.getInstance(); 3638 break; 3639 default: 3640 input = DateTimeKeyListener.getInstance(); 3641 break; 3642 } 3643 } else if (cls == EditorInfo.TYPE_CLASS_PHONE) { 3644 input = DialerKeyListener.getInstance(); 3645 } else { 3646 input = TextKeyListener.getInstance(); 3647 } 3648 setRawInputType(type); 3649 if (direct) mInput = input; 3650 else { 3651 setKeyListenerOnly(input); 3652 } 3653 } 3654 3655 /** 3656 * Get the type of the content. 3657 * 3658 * @see #setInputType(int) 3659 * @see android.text.InputType 3660 */ 3661 public int getInputType() { 3662 return mInputType; 3663 } 3664 3665 /** 3666 * Change the editor type integer associated with the text view, which 3667 * will be reported to an IME with {@link EditorInfo#imeOptions} when it 3668 * has focus. 3669 * @see #getImeOptions 3670 * @see android.view.inputmethod.EditorInfo 3671 * @attr ref android.R.styleable#TextView_imeOptions 3672 */ 3673 public void setImeOptions(int imeOptions) { 3674 if (mInputContentType == null) { 3675 mInputContentType = new InputContentType(); 3676 } 3677 mInputContentType.imeOptions = imeOptions; 3678 } 3679 3680 /** 3681 * Get the type of the IME editor. 3682 * 3683 * @see #setImeOptions(int) 3684 * @see android.view.inputmethod.EditorInfo 3685 */ 3686 public int getImeOptions() { 3687 return mInputContentType != null 3688 ? mInputContentType.imeOptions : EditorInfo.IME_NULL; 3689 } 3690 3691 /** 3692 * Change the custom IME action associated with the text view, which 3693 * will be reported to an IME with {@link EditorInfo#actionLabel} 3694 * and {@link EditorInfo#actionId} when it has focus. 3695 * @see #getImeActionLabel 3696 * @see #getImeActionId 3697 * @see android.view.inputmethod.EditorInfo 3698 * @attr ref android.R.styleable#TextView_imeActionLabel 3699 * @attr ref android.R.styleable#TextView_imeActionId 3700 */ 3701 public void setImeActionLabel(CharSequence label, int actionId) { 3702 if (mInputContentType == null) { 3703 mInputContentType = new InputContentType(); 3704 } 3705 mInputContentType.imeActionLabel = label; 3706 mInputContentType.imeActionId = actionId; 3707 } 3708 3709 /** 3710 * Get the IME action label previous set with {@link #setImeActionLabel}. 3711 * 3712 * @see #setImeActionLabel 3713 * @see android.view.inputmethod.EditorInfo 3714 */ 3715 public CharSequence getImeActionLabel() { 3716 return mInputContentType != null 3717 ? mInputContentType.imeActionLabel : null; 3718 } 3719 3720 /** 3721 * Get the IME action ID previous set with {@link #setImeActionLabel}. 3722 * 3723 * @see #setImeActionLabel 3724 * @see android.view.inputmethod.EditorInfo 3725 */ 3726 public int getImeActionId() { 3727 return mInputContentType != null 3728 ? mInputContentType.imeActionId : 0; 3729 } 3730 3731 /** 3732 * Set a special listener to be called when an action is performed 3733 * on the text view. This will be called when the enter key is pressed, 3734 * or when an action supplied to the IME is selected by the user. Setting 3735 * this means that the normal hard key event will not insert a newline 3736 * into the text view, even if it is multi-line; holding down the ALT 3737 * modifier will, however, allow the user to insert a newline character. 3738 */ 3739 public void setOnEditorActionListener(OnEditorActionListener l) { 3740 if (mInputContentType == null) { 3741 mInputContentType = new InputContentType(); 3742 } 3743 mInputContentType.onEditorActionListener = l; 3744 } 3745 3746 /** 3747 * Called when an attached input method calls 3748 * {@link InputConnection#performEditorAction(int) 3749 * InputConnection.performEditorAction()} 3750 * for this text view. The default implementation will call your action 3751 * listener supplied to {@link #setOnEditorActionListener}, or perform 3752 * a standard operation for {@link EditorInfo#IME_ACTION_NEXT 3753 * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS 3754 * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE 3755 * EditorInfo.IME_ACTION_DONE}. 3756 * 3757 * <p>For backwards compatibility, if no IME options have been set and the 3758 * text view would not normally advance focus on enter, then 3759 * the NEXT and DONE actions received here will be turned into an enter 3760 * key down/up pair to go through the normal key handling. 3761 * 3762 * @param actionCode The code of the action being performed. 3763 * 3764 * @see #setOnEditorActionListener 3765 */ 3766 public void onEditorAction(int actionCode) { 3767 final InputContentType ict = mInputContentType; 3768 if (ict != null) { 3769 if (ict.onEditorActionListener != null) { 3770 if (ict.onEditorActionListener.onEditorAction(this, 3771 actionCode, null)) { 3772 return; 3773 } 3774 } 3775 3776 // This is the handling for some default action. 3777 // Note that for backwards compatibility we don't do this 3778 // default handling if explicit ime options have not been given, 3779 // instead turning this into the normal enter key codes that an 3780 // app may be expecting. 3781 if (actionCode == EditorInfo.IME_ACTION_NEXT) { 3782 View v = focusSearch(FOCUS_FORWARD); 3783 if (v != null) { 3784 if (!v.requestFocus(FOCUS_FORWARD)) { 3785 throw new IllegalStateException("focus search returned a view " + 3786 "that wasn't able to take focus!"); 3787 } 3788 } 3789 return; 3790 3791 } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) { 3792 View v = focusSearch(FOCUS_BACKWARD); 3793 if (v != null) { 3794 if (!v.requestFocus(FOCUS_BACKWARD)) { 3795 throw new IllegalStateException("focus search returned a view " + 3796 "that wasn't able to take focus!"); 3797 } 3798 } 3799 return; 3800 3801 } else if (actionCode == EditorInfo.IME_ACTION_DONE) { 3802 InputMethodManager imm = InputMethodManager.peekInstance(); 3803 if (imm != null && imm.isActive(this)) { 3804 imm.hideSoftInputFromWindow(getWindowToken(), 0); 3805 } 3806 return; 3807 } 3808 } 3809 3810 ViewRootImpl viewRootImpl = getViewRootImpl(); 3811 if (viewRootImpl != null) { 3812 long eventTime = SystemClock.uptimeMillis(); 3813 viewRootImpl.dispatchKeyFromIme( 3814 new KeyEvent(eventTime, eventTime, 3815 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, 3816 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3817 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3818 | KeyEvent.FLAG_EDITOR_ACTION)); 3819 viewRootImpl.dispatchKeyFromIme( 3820 new KeyEvent(SystemClock.uptimeMillis(), eventTime, 3821 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 3822 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3823 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3824 | KeyEvent.FLAG_EDITOR_ACTION)); 3825 } 3826 } 3827 3828 /** 3829 * Set the private content type of the text, which is the 3830 * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} 3831 * field that will be filled in when creating an input connection. 3832 * 3833 * @see #getPrivateImeOptions() 3834 * @see EditorInfo#privateImeOptions 3835 * @attr ref android.R.styleable#TextView_privateImeOptions 3836 */ 3837 public void setPrivateImeOptions(String type) { 3838 if (mInputContentType == null) mInputContentType = new InputContentType(); 3839 mInputContentType.privateImeOptions = type; 3840 } 3841 3842 /** 3843 * Get the private type of the content. 3844 * 3845 * @see #setPrivateImeOptions(String) 3846 * @see EditorInfo#privateImeOptions 3847 */ 3848 public String getPrivateImeOptions() { 3849 return mInputContentType != null 3850 ? mInputContentType.privateImeOptions : null; 3851 } 3852 3853 /** 3854 * Set the extra input data of the text, which is the 3855 * {@link EditorInfo#extras TextBoxAttribute.extras} 3856 * Bundle that will be filled in when creating an input connection. The 3857 * given integer is the resource ID of an XML resource holding an 3858 * {@link android.R.styleable#InputExtras <input-extras>} XML tree. 3859 * 3860 * @see #getInputExtras(boolean) 3861 * @see EditorInfo#extras 3862 * @attr ref android.R.styleable#TextView_editorExtras 3863 */ 3864 public void setInputExtras(int xmlResId) 3865 throws XmlPullParserException, IOException { 3866 XmlResourceParser parser = getResources().getXml(xmlResId); 3867 if (mInputContentType == null) mInputContentType = new InputContentType(); 3868 mInputContentType.extras = new Bundle(); 3869 getResources().parseBundleExtras(parser, mInputContentType.extras); 3870 } 3871 3872 /** 3873 * Retrieve the input extras currently associated with the text view, which 3874 * can be viewed as well as modified. 3875 * 3876 * @param create If true, the extras will be created if they don't already 3877 * exist. Otherwise, null will be returned if none have been created. 3878 * @see #setInputExtras(int) 3879 * @see EditorInfo#extras 3880 * @attr ref android.R.styleable#TextView_editorExtras 3881 */ 3882 public Bundle getInputExtras(boolean create) { 3883 if (mInputContentType == null) { 3884 if (!create) return null; 3885 mInputContentType = new InputContentType(); 3886 } 3887 if (mInputContentType.extras == null) { 3888 if (!create) return null; 3889 mInputContentType.extras = new Bundle(); 3890 } 3891 return mInputContentType.extras; 3892 } 3893 3894 /** 3895 * Returns the error message that was set to be displayed with 3896 * {@link #setError}, or <code>null</code> if no error was set 3897 * or if it the error was cleared by the widget after user input. 3898 */ 3899 public CharSequence getError() { 3900 return mError; 3901 } 3902 3903 /** 3904 * Sets the right-hand compound drawable of the TextView to the "error" 3905 * icon and sets an error message that will be displayed in a popup when 3906 * the TextView has focus. The icon and error message will be reset to 3907 * null when any key events cause changes to the TextView's text. If the 3908 * <code>error</code> is <code>null</code>, the error message and icon 3909 * will be cleared. 3910 */ 3911 @android.view.RemotableViewMethod 3912 public void setError(CharSequence error) { 3913 if (error == null) { 3914 setError(null, null); 3915 } else { 3916 Drawable dr = getContext().getResources(). 3917 getDrawable(com.android.internal.R.drawable.indicator_input_error); 3918 3919 dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); 3920 setError(error, dr); 3921 } 3922 } 3923 3924 /** 3925 * Sets the right-hand compound drawable of the TextView to the specified 3926 * icon and sets an error message that will be displayed in a popup when 3927 * the TextView has focus. The icon and error message will be reset to 3928 * null when any key events cause changes to the TextView's text. The 3929 * drawable must already have had {@link Drawable#setBounds} set on it. 3930 * If the <code>error</code> is <code>null</code>, the error message will 3931 * be cleared (and you should provide a <code>null</code> icon as well). 3932 */ 3933 public void setError(CharSequence error, Drawable icon) { 3934 error = TextUtils.stringOrSpannedString(error); 3935 3936 mError = error; 3937 mErrorWasChanged = true; 3938 final Drawables dr = mDrawables; 3939 if (dr != null) { 3940 switch (getResolvedLayoutDirection()) { 3941 default: 3942 case LAYOUT_DIRECTION_LTR: 3943 setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon, 3944 dr.mDrawableBottom); 3945 break; 3946 case LAYOUT_DIRECTION_RTL: 3947 setCompoundDrawables(icon, dr.mDrawableTop, dr.mDrawableRight, 3948 dr.mDrawableBottom); 3949 break; 3950 } 3951 } else { 3952 setCompoundDrawables(null, null, icon, null); 3953 } 3954 3955 if (error == null) { 3956 if (mPopup != null) { 3957 if (mPopup.isShowing()) { 3958 mPopup.dismiss(); 3959 } 3960 3961 mPopup = null; 3962 } 3963 } else { 3964 if (isFocused()) { 3965 showError(); 3966 } 3967 } 3968 } 3969 3970 private void showError() { 3971 if (getWindowToken() == null) { 3972 mShowErrorAfterAttach = true; 3973 return; 3974 } 3975 3976 if (mPopup == null) { 3977 LayoutInflater inflater = LayoutInflater.from(getContext()); 3978 final TextView err = (TextView) inflater.inflate( 3979 com.android.internal.R.layout.textview_hint, null); 3980 3981 final float scale = getResources().getDisplayMetrics().density; 3982 mPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f)); 3983 mPopup.setFocusable(false); 3984 // The user is entering text, so the input method is needed. We 3985 // don't want the popup to be displayed on top of it. 3986 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 3987 } 3988 3989 TextView tv = (TextView) mPopup.getContentView(); 3990 chooseSize(mPopup, mError, tv); 3991 tv.setText(mError); 3992 3993 mPopup.showAsDropDown(this, getErrorX(), getErrorY()); 3994 mPopup.fixDirection(mPopup.isAboveAnchor()); 3995 } 3996 3997 private static class ErrorPopup extends PopupWindow { 3998 private boolean mAbove = false; 3999 private final TextView mView; 4000 private int mPopupInlineErrorBackgroundId = 0; 4001 private int mPopupInlineErrorAboveBackgroundId = 0; 4002 4003 ErrorPopup(TextView v, int width, int height) { 4004 super(v, width, height); 4005 mView = v; 4006 // Make sure the TextView has a background set as it will be used the first time it is 4007 // shown and positionned. Initialized with below background, which should have 4008 // dimensions identical to the above version for this to work (and is more likely). 4009 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 4010 com.android.internal.R.styleable.Theme_errorMessageBackground); 4011 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 4012 } 4013 4014 void fixDirection(boolean above) { 4015 mAbove = above; 4016 4017 if (above) { 4018 mPopupInlineErrorAboveBackgroundId = 4019 getResourceId(mPopupInlineErrorAboveBackgroundId, 4020 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 4021 } else { 4022 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 4023 com.android.internal.R.styleable.Theme_errorMessageBackground); 4024 } 4025 4026 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 4027 mPopupInlineErrorBackgroundId); 4028 } 4029 4030 private int getResourceId(int currentId, int index) { 4031 if (currentId == 0) { 4032 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 4033 R.styleable.Theme); 4034 currentId = styledAttributes.getResourceId(index, 0); 4035 styledAttributes.recycle(); 4036 } 4037 return currentId; 4038 } 4039 4040 @Override 4041 public void update(int x, int y, int w, int h, boolean force) { 4042 super.update(x, y, w, h, force); 4043 4044 boolean above = isAboveAnchor(); 4045 if (above != mAbove) { 4046 fixDirection(above); 4047 } 4048 } 4049 } 4050 4051 /** 4052 * Returns the Y offset to make the pointy top of the error point 4053 * at the middle of the error icon. 4054 */ 4055 private int getErrorX() { 4056 /* 4057 * The "25" is the distance between the point and the right edge 4058 * of the background 4059 */ 4060 final float scale = getResources().getDisplayMetrics().density; 4061 4062 final Drawables dr = mDrawables; 4063 return getWidth() - mPopup.getWidth() - getPaddingRight() - 4064 (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f); 4065 } 4066 4067 /** 4068 * Returns the Y offset to make the pointy top of the error point 4069 * at the bottom of the error icon. 4070 */ 4071 private int getErrorY() { 4072 /* 4073 * Compound, not extended, because the icon is not clipped 4074 * if the text height is smaller. 4075 */ 4076 final int compoundPaddingTop = getCompoundPaddingTop(); 4077 int vspace = mBottom - mTop - getCompoundPaddingBottom() - compoundPaddingTop; 4078 4079 final Drawables dr = mDrawables; 4080 int icontop = compoundPaddingTop + 4081 (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2; 4082 4083 /* 4084 * The "2" is the distance between the point and the top edge 4085 * of the background. 4086 */ 4087 final float scale = getResources().getDisplayMetrics().density; 4088 return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - getHeight() - 4089 (int) (2 * scale + 0.5f); 4090 } 4091 4092 private void hideError() { 4093 if (mPopup != null) { 4094 if (mPopup.isShowing()) { 4095 mPopup.dismiss(); 4096 } 4097 } 4098 4099 mShowErrorAfterAttach = false; 4100 } 4101 4102 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { 4103 int wid = tv.getPaddingLeft() + tv.getPaddingRight(); 4104 int ht = tv.getPaddingTop() + tv.getPaddingBottom(); 4105 4106 int defaultWidthInPixels = getResources().getDimensionPixelSize( 4107 com.android.internal.R.dimen.textview_error_popup_default_width); 4108 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, 4109 Layout.Alignment.ALIGN_NORMAL, 1, 0, true); 4110 float max = 0; 4111 for (int i = 0; i < l.getLineCount(); i++) { 4112 max = Math.max(max, l.getLineWidth(i)); 4113 } 4114 4115 /* 4116 * Now set the popup size to be big enough for the text plus the border capped 4117 * to DEFAULT_MAX_POPUP_WIDTH 4118 */ 4119 pop.setWidth(wid + (int) Math.ceil(max)); 4120 pop.setHeight(ht + l.getHeight()); 4121 } 4122 4123 4124 @Override 4125 protected boolean setFrame(int l, int t, int r, int b) { 4126 boolean result = super.setFrame(l, t, r, b); 4127 4128 if (mPopup != null) { 4129 TextView tv = (TextView) mPopup.getContentView(); 4130 chooseSize(mPopup, mError, tv); 4131 mPopup.update(this, getErrorX(), getErrorY(), 4132 mPopup.getWidth(), mPopup.getHeight()); 4133 } 4134 4135 restartMarqueeIfNeeded(); 4136 4137 return result; 4138 } 4139 4140 private void restartMarqueeIfNeeded() { 4141 if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 4142 mRestartMarquee = false; 4143 startMarquee(); 4144 } 4145 } 4146 4147 /** 4148 * Sets the list of input filters that will be used if the buffer is 4149 * Editable. Has no effect otherwise. 4150 * 4151 * @attr ref android.R.styleable#TextView_maxLength 4152 */ 4153 public void setFilters(InputFilter[] filters) { 4154 if (filters == null) { 4155 throw new IllegalArgumentException(); 4156 } 4157 4158 mFilters = filters; 4159 4160 if (mText instanceof Editable) { 4161 setFilters((Editable) mText, filters); 4162 } 4163 } 4164 4165 /** 4166 * Sets the list of input filters on the specified Editable, 4167 * and includes mInput in the list if it is an InputFilter. 4168 */ 4169 private void setFilters(Editable e, InputFilter[] filters) { 4170 if (mInput instanceof InputFilter) { 4171 InputFilter[] nf = new InputFilter[filters.length + 1]; 4172 4173 System.arraycopy(filters, 0, nf, 0, filters.length); 4174 nf[filters.length] = (InputFilter) mInput; 4175 4176 e.setFilters(nf); 4177 } else { 4178 e.setFilters(filters); 4179 } 4180 } 4181 4182 /** 4183 * Returns the current list of input filters. 4184 */ 4185 public InputFilter[] getFilters() { 4186 return mFilters; 4187 } 4188 4189 ///////////////////////////////////////////////////////////////////////// 4190 4191 private int getVerticalOffset(boolean forceNormal) { 4192 int voffset = 0; 4193 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 4194 4195 Layout l = mLayout; 4196 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 4197 l = mHintLayout; 4198 } 4199 4200 if (gravity != Gravity.TOP) { 4201 int boxht; 4202 4203 if (l == mHintLayout) { 4204 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 4205 getCompoundPaddingBottom(); 4206 } else { 4207 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 4208 getExtendedPaddingBottom(); 4209 } 4210 int textht = l.getHeight(); 4211 4212 if (textht < boxht) { 4213 if (gravity == Gravity.BOTTOM) 4214 voffset = boxht - textht; 4215 else // (gravity == Gravity.CENTER_VERTICAL) 4216 voffset = (boxht - textht) >> 1; 4217 } 4218 } 4219 return voffset; 4220 } 4221 4222 private int getBottomVerticalOffset(boolean forceNormal) { 4223 int voffset = 0; 4224 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 4225 4226 Layout l = mLayout; 4227 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 4228 l = mHintLayout; 4229 } 4230 4231 if (gravity != Gravity.BOTTOM) { 4232 int boxht; 4233 4234 if (l == mHintLayout) { 4235 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 4236 getCompoundPaddingBottom(); 4237 } else { 4238 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 4239 getExtendedPaddingBottom(); 4240 } 4241 int textht = l.getHeight(); 4242 4243 if (textht < boxht) { 4244 if (gravity == Gravity.TOP) 4245 voffset = boxht - textht; 4246 else // (gravity == Gravity.CENTER_VERTICAL) 4247 voffset = (boxht - textht) >> 1; 4248 } 4249 } 4250 return voffset; 4251 } 4252 4253 private void invalidateCursorPath() { 4254 if (mHighlightPathBogus) { 4255 invalidateCursor(); 4256 } else { 4257 final int horizontalPadding = getCompoundPaddingLeft(); 4258 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 4259 4260 if (mCursorCount == 0) { 4261 synchronized (sTempRect) { 4262 /* 4263 * The reason for this concern about the thickness of the 4264 * cursor and doing the floor/ceil on the coordinates is that 4265 * some EditTexts (notably textfields in the Browser) have 4266 * anti-aliased text where not all the characters are 4267 * necessarily at integer-multiple locations. This should 4268 * make sure the entire cursor gets invalidated instead of 4269 * sometimes missing half a pixel. 4270 */ 4271 float thick = FloatMath.ceil(mTextPaint.getStrokeWidth()); 4272 if (thick < 1.0f) { 4273 thick = 1.0f; 4274 } 4275 4276 thick /= 2.0f; 4277 4278 mHighlightPath.computeBounds(sTempRect, false); 4279 4280 invalidate((int) FloatMath.floor(horizontalPadding + sTempRect.left - thick), 4281 (int) FloatMath.floor(verticalPadding + sTempRect.top - thick), 4282 (int) FloatMath.ceil(horizontalPadding + sTempRect.right + thick), 4283 (int) FloatMath.ceil(verticalPadding + sTempRect.bottom + thick)); 4284 } 4285 } else { 4286 for (int i = 0; i < mCursorCount; i++) { 4287 Rect bounds = mCursorDrawable[i].getBounds(); 4288 invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding, 4289 bounds.right + horizontalPadding, bounds.bottom + verticalPadding); 4290 } 4291 } 4292 } 4293 } 4294 4295 private void invalidateCursor() { 4296 int where = getSelectionEnd(); 4297 4298 invalidateCursor(where, where, where); 4299 } 4300 4301 private void invalidateCursor(int a, int b, int c) { 4302 if (a >= 0 || b >= 0 || c >= 0) { 4303 int start = Math.min(Math.min(a, b), c); 4304 int end = Math.max(Math.max(a, b), c); 4305 invalidateRegion(start, end, true /* Also invalidates blinking cursor */); 4306 } 4307 } 4308 4309 /** 4310 * Invalidates the region of text enclosed between the start and end text offsets. 4311 * 4312 * @hide 4313 */ 4314 void invalidateRegion(int start, int end, boolean invalidateCursor) { 4315 if (mLayout == null) { 4316 invalidate(); 4317 } else { 4318 int lineStart = mLayout.getLineForOffset(start); 4319 int top = mLayout.getLineTop(lineStart); 4320 4321 // This is ridiculous, but the descent from the line above 4322 // can hang down into the line we really want to redraw, 4323 // so we have to invalidate part of the line above to make 4324 // sure everything that needs to be redrawn really is. 4325 // (But not the whole line above, because that would cause 4326 // the same problem with the descenders on the line above it!) 4327 if (lineStart > 0) { 4328 top -= mLayout.getLineDescent(lineStart - 1); 4329 } 4330 4331 int lineEnd; 4332 4333 if (start == end) 4334 lineEnd = lineStart; 4335 else 4336 lineEnd = mLayout.getLineForOffset(end); 4337 4338 int bottom = mLayout.getLineBottom(lineEnd); 4339 4340 if (invalidateCursor) { 4341 for (int i = 0; i < mCursorCount; i++) { 4342 Rect bounds = mCursorDrawable[i].getBounds(); 4343 top = Math.min(top, bounds.top); 4344 bottom = Math.max(bottom, bounds.bottom); 4345 } 4346 } 4347 4348 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4349 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 4350 4351 int left, right; 4352 if (lineStart == lineEnd && !invalidateCursor) { 4353 left = (int) mLayout.getPrimaryHorizontal(start); 4354 right = (int) (mLayout.getPrimaryHorizontal(end) + 1.0); 4355 left += compoundPaddingLeft; 4356 right += compoundPaddingLeft; 4357 } else { 4358 // Rectangle bounding box when the region spans several lines 4359 left = compoundPaddingLeft; 4360 right = getWidth() - getCompoundPaddingRight(); 4361 } 4362 4363 invalidate(mScrollX + left, verticalPadding + top, 4364 mScrollX + right, verticalPadding + bottom); 4365 } 4366 } 4367 4368 private void registerForPreDraw() { 4369 if (!mPreDrawRegistered) { 4370 getViewTreeObserver().addOnPreDrawListener(this); 4371 mPreDrawRegistered = true; 4372 } 4373 } 4374 4375 /** 4376 * {@inheritDoc} 4377 */ 4378 public boolean onPreDraw() { 4379 if (mLayout == null) { 4380 assumeLayout(); 4381 } 4382 4383 boolean changed = false; 4384 4385 if (mMovement != null) { 4386 /* This code also provides auto-scrolling when a cursor is moved using a 4387 * CursorController (insertion point or selection limits). 4388 * For selection, ensure start or end is visible depending on controller's state. 4389 */ 4390 int curs = getSelectionEnd(); 4391 // Do not create the controller if it is not already created. 4392 if (mSelectionModifierCursorController != null && 4393 mSelectionModifierCursorController.isSelectionStartDragged()) { 4394 curs = getSelectionStart(); 4395 } 4396 4397 /* 4398 * TODO: This should really only keep the end in view if 4399 * it already was before the text changed. I'm not sure 4400 * of a good way to tell from here if it was. 4401 */ 4402 if (curs < 0 && 4403 (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 4404 curs = mText.length(); 4405 } 4406 4407 if (curs >= 0) { 4408 changed = bringPointIntoView(curs); 4409 } 4410 } else { 4411 changed = bringTextIntoView(); 4412 } 4413 4414 // This has to be checked here since: 4415 // - onFocusChanged cannot start it when focus is given to a view with selected text (after 4416 // a screen rotation) since layout is not yet initialized at that point. 4417 if (mCreatedWithASelection) { 4418 startSelectionActionMode(); 4419 mCreatedWithASelection = false; 4420 } 4421 4422 // Phone specific code (there is no ExtractEditText on tablets). 4423 // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can 4424 // not be set. Do the test here instead. 4425 if (this instanceof ExtractEditText && hasSelection()) { 4426 startSelectionActionMode(); 4427 } 4428 4429 getViewTreeObserver().removeOnPreDrawListener(this); 4430 mPreDrawRegistered = false; 4431 4432 return !changed; 4433 } 4434 4435 @Override 4436 protected void onAttachedToWindow() { 4437 super.onAttachedToWindow(); 4438 4439 mTemporaryDetach = false; 4440 4441 if (mShowErrorAfterAttach) { 4442 showError(); 4443 mShowErrorAfterAttach = false; 4444 } 4445 4446 final ViewTreeObserver observer = getViewTreeObserver(); 4447 // No need to create the controller. 4448 // The get method will add the listener on controller creation. 4449 if (mInsertionPointCursorController != null) { 4450 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 4451 } 4452 if (mSelectionModifierCursorController != null) { 4453 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 4454 } 4455 4456 // Resolve drawables as the layout direction has been resolved 4457 resolveDrawables(); 4458 4459 updateSpellCheckSpans(0, mText.length(), true /* create the spell checker if needed */); 4460 } 4461 4462 @Override 4463 protected void onDetachedFromWindow() { 4464 super.onDetachedFromWindow(); 4465 4466 if (mPreDrawRegistered) { 4467 getViewTreeObserver().removeOnPreDrawListener(this); 4468 mPreDrawRegistered = false; 4469 } 4470 4471 if (mError != null) { 4472 hideError(); 4473 } 4474 4475 if (mBlink != null) { 4476 mBlink.removeCallbacks(mBlink); 4477 } 4478 4479 if (mInsertionPointCursorController != null) { 4480 mInsertionPointCursorController.onDetached(); 4481 } 4482 4483 if (mSelectionModifierCursorController != null) { 4484 mSelectionModifierCursorController.onDetached(); 4485 } 4486 4487 if (mShowSuggestionRunnable != null) { 4488 removeCallbacks(mShowSuggestionRunnable); 4489 } 4490 4491 hideControllers(); 4492 4493 resetResolvedDrawables(); 4494 4495 if (mTextDisplayList != null) { 4496 mTextDisplayList.invalidate(); 4497 } 4498 4499 if (mSpellChecker != null) { 4500 mSpellChecker.closeSession(); 4501 // Forces the creation of a new SpellChecker next time this window is created. 4502 // Will handle the cases where the settings has been changed in the meantime. 4503 mSpellChecker = null; 4504 } 4505 } 4506 4507 @Override 4508 protected boolean isPaddingOffsetRequired() { 4509 return mShadowRadius != 0 || mDrawables != null; 4510 } 4511 4512 @Override 4513 protected int getLeftPaddingOffset() { 4514 return getCompoundPaddingLeft() - mPaddingLeft + 4515 (int) Math.min(0, mShadowDx - mShadowRadius); 4516 } 4517 4518 @Override 4519 protected int getTopPaddingOffset() { 4520 return (int) Math.min(0, mShadowDy - mShadowRadius); 4521 } 4522 4523 @Override 4524 protected int getBottomPaddingOffset() { 4525 return (int) Math.max(0, mShadowDy + mShadowRadius); 4526 } 4527 4528 @Override 4529 protected int getRightPaddingOffset() { 4530 return -(getCompoundPaddingRight() - mPaddingRight) + 4531 (int) Math.max(0, mShadowDx + mShadowRadius); 4532 } 4533 4534 @Override 4535 protected boolean verifyDrawable(Drawable who) { 4536 final boolean verified = super.verifyDrawable(who); 4537 if (!verified && mDrawables != null) { 4538 return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || 4539 who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom || 4540 who == mDrawables.mDrawableStart || who == mDrawables.mDrawableEnd; 4541 } 4542 return verified; 4543 } 4544 4545 @Override 4546 public void jumpDrawablesToCurrentState() { 4547 super.jumpDrawablesToCurrentState(); 4548 if (mDrawables != null) { 4549 if (mDrawables.mDrawableLeft != null) { 4550 mDrawables.mDrawableLeft.jumpToCurrentState(); 4551 } 4552 if (mDrawables.mDrawableTop != null) { 4553 mDrawables.mDrawableTop.jumpToCurrentState(); 4554 } 4555 if (mDrawables.mDrawableRight != null) { 4556 mDrawables.mDrawableRight.jumpToCurrentState(); 4557 } 4558 if (mDrawables.mDrawableBottom != null) { 4559 mDrawables.mDrawableBottom.jumpToCurrentState(); 4560 } 4561 if (mDrawables.mDrawableStart != null) { 4562 mDrawables.mDrawableStart.jumpToCurrentState(); 4563 } 4564 if (mDrawables.mDrawableEnd != null) { 4565 mDrawables.mDrawableEnd.jumpToCurrentState(); 4566 } 4567 } 4568 } 4569 4570 @Override 4571 public void invalidateDrawable(Drawable drawable) { 4572 if (verifyDrawable(drawable)) { 4573 final Rect dirty = drawable.getBounds(); 4574 int scrollX = mScrollX; 4575 int scrollY = mScrollY; 4576 4577 // IMPORTANT: The coordinates below are based on the coordinates computed 4578 // for each compound drawable in onDraw(). Make sure to update each section 4579 // accordingly. 4580 final TextView.Drawables drawables = mDrawables; 4581 if (drawables != null) { 4582 if (drawable == drawables.mDrawableLeft) { 4583 final int compoundPaddingTop = getCompoundPaddingTop(); 4584 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4585 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4586 4587 scrollX += mPaddingLeft; 4588 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 4589 } else if (drawable == drawables.mDrawableRight) { 4590 final int compoundPaddingTop = getCompoundPaddingTop(); 4591 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4592 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4593 4594 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 4595 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 4596 } else if (drawable == drawables.mDrawableTop) { 4597 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4598 final int compoundPaddingRight = getCompoundPaddingRight(); 4599 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4600 4601 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 4602 scrollY += mPaddingTop; 4603 } else if (drawable == drawables.mDrawableBottom) { 4604 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4605 final int compoundPaddingRight = getCompoundPaddingRight(); 4606 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4607 4608 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 4609 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 4610 } 4611 } 4612 4613 invalidate(dirty.left + scrollX, dirty.top + scrollY, 4614 dirty.right + scrollX, dirty.bottom + scrollY); 4615 } 4616 } 4617 4618 /** 4619 * @hide 4620 */ 4621 @Override 4622 public int getResolvedLayoutDirection(Drawable who) { 4623 if (who == null) return View.LAYOUT_DIRECTION_LTR; 4624 if (mDrawables != null) { 4625 final Drawables drawables = mDrawables; 4626 if (who == drawables.mDrawableLeft || who == drawables.mDrawableRight || 4627 who == drawables.mDrawableTop || who == drawables.mDrawableBottom || 4628 who == drawables.mDrawableStart || who == drawables.mDrawableEnd) { 4629 return getResolvedLayoutDirection(); 4630 } 4631 } 4632 return super.getResolvedLayoutDirection(who); 4633 } 4634 4635 @Override 4636 protected boolean onSetAlpha(int alpha) { 4637 // Alpha is supported if and only if the drawing can be done in one pass. 4638 // TODO text with spans with a background color currently do not respect this alpha. 4639 if (getBackground() == null) { 4640 if (mCurrentAlpha != alpha) { 4641 mCurrentAlpha = alpha; 4642 final Drawables dr = mDrawables; 4643 if (dr != null) { 4644 if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha); 4645 if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha); 4646 if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha); 4647 if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha); 4648 if (dr.mDrawableStart != null) dr.mDrawableStart.mutate().setAlpha(alpha); 4649 if (dr.mDrawableEnd != null) dr.mDrawableEnd.mutate().setAlpha(alpha); 4650 } 4651 mTextDisplayListIsValid = false; 4652 } 4653 return true; 4654 } 4655 4656 if (mCurrentAlpha != 255) { 4657 mTextDisplayListIsValid = false; 4658 } 4659 mCurrentAlpha = 255; 4660 return false; 4661 } 4662 4663 /** 4664 * When a TextView is used to display a useful piece of information to the user (such as a 4665 * contact's address), it should be made selectable, so that the user can select and copy this 4666 * content. 4667 * 4668 * Use {@link #setTextIsSelectable(boolean)} or the 4669 * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView 4670 * selectable (text is not selectable by default). 4671 * 4672 * Note that this method simply returns the state of this flag. Although this flag has to be set 4673 * in order to select text in non-editable TextView, the content of an {@link EditText} can 4674 * always be selected, independently of the value of this flag. 4675 * 4676 * @return True if the text displayed in this TextView can be selected by the user. 4677 * 4678 * @attr ref android.R.styleable#TextView_textIsSelectable 4679 */ 4680 public boolean isTextSelectable() { 4681 return mTextIsSelectable; 4682 } 4683 4684 /** 4685 * Sets whether or not (default) the content of this view is selectable by the user. 4686 * 4687 * Note that this methods affect the {@link #setFocusable(boolean)}, 4688 * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and 4689 * {@link #setLongClickable(boolean)} states and you may want to restore these if they were 4690 * customized. 4691 * 4692 * See {@link #isTextSelectable} for details. 4693 * 4694 * @param selectable Whether or not the content of this TextView should be selectable. 4695 */ 4696 public void setTextIsSelectable(boolean selectable) { 4697 if (mTextIsSelectable == selectable) return; 4698 4699 mTextIsSelectable = selectable; 4700 4701 setFocusableInTouchMode(selectable); 4702 setFocusable(selectable); 4703 setClickable(selectable); 4704 setLongClickable(selectable); 4705 4706 // mInputType is already EditorInfo.TYPE_NULL and mInput is null; 4707 4708 setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); 4709 setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL); 4710 4711 // Called by setText above, but safer in case of future code changes 4712 prepareCursorControllers(); 4713 } 4714 4715 @Override 4716 protected int[] onCreateDrawableState(int extraSpace) { 4717 final int[] drawableState; 4718 4719 if (mSingleLine) { 4720 drawableState = super.onCreateDrawableState(extraSpace); 4721 } else { 4722 drawableState = super.onCreateDrawableState(extraSpace + 1); 4723 mergeDrawableStates(drawableState, MULTILINE_STATE_SET); 4724 } 4725 4726 if (mTextIsSelectable) { 4727 // Disable pressed state, which was introduced when TextView was made clickable. 4728 // Prevents text color change. 4729 // setClickable(false) would have a similar effect, but it also disables focus changes 4730 // and long press actions, which are both needed by text selection. 4731 final int length = drawableState.length; 4732 for (int i = 0; i < length; i++) { 4733 if (drawableState[i] == R.attr.state_pressed) { 4734 final int[] nonPressedState = new int[length - 1]; 4735 System.arraycopy(drawableState, 0, nonPressedState, 0, i); 4736 System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); 4737 return nonPressedState; 4738 } 4739 } 4740 } 4741 4742 return drawableState; 4743 } 4744 4745 @Override 4746 protected void onDraw(Canvas canvas) { 4747 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return; 4748 4749 restartMarqueeIfNeeded(); 4750 4751 // Draw the background for this view 4752 super.onDraw(canvas); 4753 4754 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4755 final int compoundPaddingTop = getCompoundPaddingTop(); 4756 final int compoundPaddingRight = getCompoundPaddingRight(); 4757 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4758 final int scrollX = mScrollX; 4759 final int scrollY = mScrollY; 4760 final int right = mRight; 4761 final int left = mLeft; 4762 final int bottom = mBottom; 4763 final int top = mTop; 4764 4765 final Drawables dr = mDrawables; 4766 if (dr != null) { 4767 /* 4768 * Compound, not extended, because the icon is not clipped 4769 * if the text height is smaller. 4770 */ 4771 4772 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 4773 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 4774 4775 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4776 // Make sure to update invalidateDrawable() when changing this code. 4777 if (dr.mDrawableLeft != null) { 4778 canvas.save(); 4779 canvas.translate(scrollX + mPaddingLeft, 4780 scrollY + compoundPaddingTop + 4781 (vspace - dr.mDrawableHeightLeft) / 2); 4782 dr.mDrawableLeft.draw(canvas); 4783 canvas.restore(); 4784 } 4785 4786 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4787 // Make sure to update invalidateDrawable() when changing this code. 4788 if (dr.mDrawableRight != null) { 4789 canvas.save(); 4790 canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight, 4791 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 4792 dr.mDrawableRight.draw(canvas); 4793 canvas.restore(); 4794 } 4795 4796 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4797 // Make sure to update invalidateDrawable() when changing this code. 4798 if (dr.mDrawableTop != null) { 4799 canvas.save(); 4800 canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, 4801 scrollY + mPaddingTop); 4802 dr.mDrawableTop.draw(canvas); 4803 canvas.restore(); 4804 } 4805 4806 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4807 // Make sure to update invalidateDrawable() when changing this code. 4808 if (dr.mDrawableBottom != null) { 4809 canvas.save(); 4810 canvas.translate(scrollX + compoundPaddingLeft + 4811 (hspace - dr.mDrawableWidthBottom) / 2, 4812 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 4813 dr.mDrawableBottom.draw(canvas); 4814 canvas.restore(); 4815 } 4816 } 4817 4818 int color = mCurTextColor; 4819 4820 if (mLayout == null) { 4821 assumeLayout(); 4822 } 4823 4824 Layout layout = mLayout; 4825 int cursorcolor = color; 4826 4827 if (mHint != null && mText.length() == 0) { 4828 if (mHintTextColor != null) { 4829 color = mCurHintTextColor; 4830 } 4831 4832 layout = mHintLayout; 4833 } 4834 4835 mTextPaint.setColor(color); 4836 if (mCurrentAlpha != 255) { 4837 // If set, the alpha will override the color's alpha. Multiply the alphas. 4838 mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255); 4839 } 4840 mTextPaint.drawableState = getDrawableState(); 4841 4842 canvas.save(); 4843 /* Would be faster if we didn't have to do this. Can we chop the 4844 (displayable) text so that we don't need to do this ever? 4845 */ 4846 4847 int extendedPaddingTop = getExtendedPaddingTop(); 4848 int extendedPaddingBottom = getExtendedPaddingBottom(); 4849 4850 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4851 final int maxScrollY = mLayout.getHeight() - vspace; 4852 4853 float clipLeft = compoundPaddingLeft + scrollX; 4854 float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY; 4855 float clipRight = right - left - compoundPaddingRight + scrollX; 4856 float clipBottom = bottom - top + scrollY - 4857 ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom); 4858 4859 if (mShadowRadius != 0) { 4860 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 4861 clipRight += Math.max(0, mShadowDx + mShadowRadius); 4862 4863 clipTop += Math.min(0, mShadowDy - mShadowRadius); 4864 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 4865 } 4866 4867 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 4868 4869 int voffsetText = 0; 4870 int voffsetCursor = 0; 4871 4872 // translate in by our padding 4873 { 4874 /* shortcircuit calling getVerticaOffset() */ 4875 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4876 voffsetText = getVerticalOffset(false); 4877 voffsetCursor = getVerticalOffset(true); 4878 } 4879 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 4880 } 4881 4882 final int layoutDirection = getResolvedLayoutDirection(); 4883 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 4884 if (mEllipsize == TextUtils.TruncateAt.MARQUEE && 4885 mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 4886 if (!mSingleLine && getLineCount() == 1 && canMarquee() && 4887 (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 4888 canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft - 4889 getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f); 4890 } 4891 4892 if (mMarquee != null && mMarquee.isRunning()) { 4893 canvas.translate(-mMarquee.mScroll, 0.0f); 4894 } 4895 } 4896 4897 Path highlight = null; 4898 int selStart = -1, selEnd = -1; 4899 boolean drawCursor = false; 4900 4901 // If there is no movement method, then there can be no selection. 4902 // Check that first and attempt to skip everything having to do with 4903 // the cursor. 4904 // XXX This is not strictly true -- a program could set the 4905 // selection manually if it really wanted to. 4906 if (mMovement != null && (isFocused() || isPressed())) { 4907 selStart = getSelectionStart(); 4908 selEnd = getSelectionEnd(); 4909 4910 if (selStart >= 0) { 4911 if (mHighlightPath == null) mHighlightPath = new Path(); 4912 4913 if (selStart == selEnd) { 4914 if (isCursorVisible() && 4915 (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) { 4916 if (mHighlightPathBogus) { 4917 mHighlightPath.reset(); 4918 mLayout.getCursorPath(selStart, mHighlightPath, mText); 4919 updateCursorsPositions(); 4920 mHighlightPathBogus = false; 4921 } 4922 4923 // XXX should pass to skin instead of drawing directly 4924 mHighlightPaint.setColor(cursorcolor); 4925 if (mCurrentAlpha != 255) { 4926 mHighlightPaint.setAlpha( 4927 (mCurrentAlpha * Color.alpha(cursorcolor)) / 255); 4928 } 4929 mHighlightPaint.setStyle(Paint.Style.STROKE); 4930 highlight = mHighlightPath; 4931 drawCursor = mCursorCount > 0; 4932 } 4933 } else if (textCanBeSelected()) { 4934 if (mHighlightPathBogus) { 4935 mHighlightPath.reset(); 4936 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 4937 mHighlightPathBogus = false; 4938 } 4939 4940 // XXX should pass to skin instead of drawing directly 4941 mHighlightPaint.setColor(mHighlightColor); 4942 if (mCurrentAlpha != 255) { 4943 mHighlightPaint.setAlpha( 4944 (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255); 4945 } 4946 mHighlightPaint.setStyle(Paint.Style.FILL); 4947 4948 highlight = mHighlightPath; 4949 } 4950 } 4951 } 4952 4953 final InputMethodState ims = mInputMethodState; 4954 final int cursorOffsetVertical = voffsetCursor - voffsetText; 4955 if (ims != null && ims.mBatchEditNesting == 0) { 4956 InputMethodManager imm = InputMethodManager.peekInstance(); 4957 if (imm != null) { 4958 if (imm.isActive(this)) { 4959 boolean reported = false; 4960 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4961 // We are in extract mode and the content has changed 4962 // in some way... just report complete new text to the 4963 // input method. 4964 reported = reportExtractedText(); 4965 } 4966 if (!reported && highlight != null) { 4967 int candStart = -1; 4968 int candEnd = -1; 4969 if (mText instanceof Spannable) { 4970 Spannable sp = (Spannable)mText; 4971 candStart = EditableInputConnection.getComposingSpanStart(sp); 4972 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 4973 } 4974 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 4975 } 4976 } 4977 4978 if (imm.isWatchingCursor(this) && highlight != null) { 4979 highlight.computeBounds(ims.mTmpRectF, true); 4980 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 4981 4982 canvas.getMatrix().mapPoints(ims.mTmpOffset); 4983 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 4984 4985 ims.mTmpRectF.offset(0, cursorOffsetVertical); 4986 4987 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 4988 (int)(ims.mTmpRectF.top + 0.5), 4989 (int)(ims.mTmpRectF.right + 0.5), 4990 (int)(ims.mTmpRectF.bottom + 0.5)); 4991 4992 imm.updateCursor(this, 4993 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 4994 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 4995 } 4996 } 4997 } 4998 4999 if (mCorrectionHighlighter != null) { 5000 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 5001 } 5002 5003 if (drawCursor) { 5004 drawCursor(canvas, cursorOffsetVertical); 5005 // Rely on the drawable entirely, do not draw the cursor line. 5006 // Has to be done after the IMM related code above which relies on the highlight. 5007 highlight = null; 5008 } 5009 5010 if (canHaveDisplayList() && canvas.isHardwareAccelerated()) { 5011 final int width = mRight - mLeft; 5012 final int height = mBottom - mTop; 5013 5014 if (mTextDisplayList == null || !mTextDisplayList.isValid() || 5015 !mTextDisplayListIsValid) { 5016 if (mTextDisplayList == null) { 5017 mTextDisplayList = getHardwareRenderer().createDisplayList("Text"); 5018 } 5019 5020 final HardwareCanvas hardwareCanvas = mTextDisplayList.start(); 5021 try { 5022 hardwareCanvas.setViewport(width, height); 5023 // The dirty rect should always be null for a display list 5024 hardwareCanvas.onPreDraw(null); 5025 layout.draw(hardwareCanvas, highlight, mHighlightPaint, cursorOffsetVertical); 5026 } finally { 5027 hardwareCanvas.onPostDraw(); 5028 mTextDisplayList.end(); 5029 mTextDisplayListIsValid = true; 5030 } 5031 } 5032 ((HardwareCanvas) canvas).drawDisplayList(mTextDisplayList, 5033 mScrollX + width, mScrollY + height, null); 5034 } else { 5035 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 5036 } 5037 5038 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 5039 canvas.translate((int) mMarquee.getGhostOffset(), 0.0f); 5040 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 5041 } 5042 5043 canvas.restore(); 5044 } 5045 5046 private void updateCursorsPositions() { 5047 if (mCursorDrawableRes == 0) { 5048 mCursorCount = 0; 5049 return; 5050 } 5051 5052 final int offset = getSelectionStart(); 5053 final int line = mLayout.getLineForOffset(offset); 5054 final int top = mLayout.getLineTop(line); 5055 final int bottom = mLayout.getLineTop(line + 1); 5056 5057 mCursorCount = mLayout.isLevelBoundary(offset) ? 2 : 1; 5058 5059 int middle = bottom; 5060 if (mCursorCount == 2) { 5061 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)} 5062 middle = (top + bottom) >> 1; 5063 } 5064 5065 updateCursorPosition(0, top, middle, mLayout.getPrimaryHorizontal(offset)); 5066 5067 if (mCursorCount == 2) { 5068 updateCursorPosition(1, middle, bottom, mLayout.getSecondaryHorizontal(offset)); 5069 } 5070 } 5071 5072 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) { 5073 if (mCursorDrawable[cursorIndex] == null) 5074 mCursorDrawable[cursorIndex] = mContext.getResources().getDrawable(mCursorDrawableRes); 5075 5076 if (mTempRect == null) mTempRect = new Rect(); 5077 5078 mCursorDrawable[cursorIndex].getPadding(mTempRect); 5079 final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth(); 5080 horizontal = Math.max(0.5f, horizontal - 0.5f); 5081 final int left = (int) (horizontal) - mTempRect.left; 5082 mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width, 5083 bottom + mTempRect.bottom); 5084 } 5085 5086 private void drawCursor(Canvas canvas, int cursorOffsetVertical) { 5087 final boolean translate = cursorOffsetVertical != 0; 5088 if (translate) canvas.translate(0, cursorOffsetVertical); 5089 for (int i = 0; i < mCursorCount; i++) { 5090 mCursorDrawable[i].draw(canvas); 5091 } 5092 if (translate) canvas.translate(0, -cursorOffsetVertical); 5093 } 5094 5095 @Override 5096 public void getFocusedRect(Rect r) { 5097 if (mLayout == null) { 5098 super.getFocusedRect(r); 5099 return; 5100 } 5101 5102 int selEnd = getSelectionEnd(); 5103 if (selEnd < 0) { 5104 super.getFocusedRect(r); 5105 return; 5106 } 5107 5108 int selStart = getSelectionStart(); 5109 if (selStart < 0 || selStart >= selEnd) { 5110 int line = mLayout.getLineForOffset(selEnd); 5111 r.top = mLayout.getLineTop(line); 5112 r.bottom = mLayout.getLineBottom(line); 5113 r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2; 5114 r.right = r.left + 4; 5115 } else { 5116 int lineStart = mLayout.getLineForOffset(selStart); 5117 int lineEnd = mLayout.getLineForOffset(selEnd); 5118 r.top = mLayout.getLineTop(lineStart); 5119 r.bottom = mLayout.getLineBottom(lineEnd); 5120 if (lineStart == lineEnd) { 5121 r.left = (int) mLayout.getPrimaryHorizontal(selStart); 5122 r.right = (int) mLayout.getPrimaryHorizontal(selEnd); 5123 } else { 5124 // Selection extends across multiple lines -- the focused 5125 // rect covers the entire width. 5126 if (mHighlightPath == null) mHighlightPath = new Path(); 5127 if (mHighlightPathBogus) { 5128 mHighlightPath.reset(); 5129 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 5130 mHighlightPathBogus = false; 5131 } 5132 synchronized (sTempRect) { 5133 mHighlightPath.computeBounds(sTempRect, true); 5134 r.left = (int)sTempRect.left-1; 5135 r.right = (int)sTempRect.right+1; 5136 } 5137 } 5138 } 5139 5140 // Adjust for padding and gravity. 5141 int paddingLeft = getCompoundPaddingLeft(); 5142 int paddingTop = getExtendedPaddingTop(); 5143 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5144 paddingTop += getVerticalOffset(false); 5145 } 5146 r.offset(paddingLeft, paddingTop); 5147 int paddingBottom = getExtendedPaddingBottom(); 5148 r.bottom += paddingBottom; 5149 } 5150 5151 /** 5152 * Return the number of lines of text, or 0 if the internal Layout has not 5153 * been built. 5154 */ 5155 public int getLineCount() { 5156 return mLayout != null ? mLayout.getLineCount() : 0; 5157 } 5158 5159 /** 5160 * Return the baseline for the specified line (0...getLineCount() - 1) 5161 * If bounds is not null, return the top, left, right, bottom extents 5162 * of the specified line in it. If the internal Layout has not been built, 5163 * return 0 and set bounds to (0, 0, 0, 0) 5164 * @param line which line to examine (0..getLineCount() - 1) 5165 * @param bounds Optional. If not null, it returns the extent of the line 5166 * @return the Y-coordinate of the baseline 5167 */ 5168 public int getLineBounds(int line, Rect bounds) { 5169 if (mLayout == null) { 5170 if (bounds != null) { 5171 bounds.set(0, 0, 0, 0); 5172 } 5173 return 0; 5174 } 5175 else { 5176 int baseline = mLayout.getLineBounds(line, bounds); 5177 5178 int voffset = getExtendedPaddingTop(); 5179 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5180 voffset += getVerticalOffset(true); 5181 } 5182 if (bounds != null) { 5183 bounds.offset(getCompoundPaddingLeft(), voffset); 5184 } 5185 return baseline + voffset; 5186 } 5187 } 5188 5189 @Override 5190 public int getBaseline() { 5191 if (mLayout == null) { 5192 return super.getBaseline(); 5193 } 5194 5195 int voffset = 0; 5196 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5197 voffset = getVerticalOffset(true); 5198 } 5199 5200 return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); 5201 } 5202 5203 /** 5204 * @hide 5205 * @param offsetRequired 5206 */ 5207 @Override 5208 protected int getFadeTop(boolean offsetRequired) { 5209 if (mLayout == null) return 0; 5210 5211 int voffset = 0; 5212 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5213 voffset = getVerticalOffset(true); 5214 } 5215 5216 if (offsetRequired) voffset += getTopPaddingOffset(); 5217 5218 return getExtendedPaddingTop() + voffset; 5219 } 5220 5221 /** 5222 * @hide 5223 * @param offsetRequired 5224 */ 5225 @Override 5226 protected int getFadeHeight(boolean offsetRequired) { 5227 return mLayout != null ? mLayout.getHeight() : 0; 5228 } 5229 5230 @Override 5231 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5232 if (keyCode == KeyEvent.KEYCODE_BACK) { 5233 boolean isInSelectionMode = mSelectionActionMode != null; 5234 5235 if (isInSelectionMode) { 5236 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { 5237 KeyEvent.DispatcherState state = getKeyDispatcherState(); 5238 if (state != null) { 5239 state.startTracking(event, this); 5240 } 5241 return true; 5242 } else if (event.getAction() == KeyEvent.ACTION_UP) { 5243 KeyEvent.DispatcherState state = getKeyDispatcherState(); 5244 if (state != null) { 5245 state.handleUpEvent(event); 5246 } 5247 if (event.isTracking() && !event.isCanceled()) { 5248 stopSelectionActionMode(); 5249 return true; 5250 } 5251 } 5252 } 5253 } 5254 return super.onKeyPreIme(keyCode, event); 5255 } 5256 5257 @Override 5258 public boolean onKeyDown(int keyCode, KeyEvent event) { 5259 int which = doKeyDown(keyCode, event, null); 5260 if (which == 0) { 5261 // Go through default dispatching. 5262 return super.onKeyDown(keyCode, event); 5263 } 5264 5265 return true; 5266 } 5267 5268 @Override 5269 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5270 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 5271 5272 int which = doKeyDown(keyCode, down, event); 5273 if (which == 0) { 5274 // Go through default dispatching. 5275 return super.onKeyMultiple(keyCode, repeatCount, event); 5276 } 5277 if (which == -1) { 5278 // Consumed the whole thing. 5279 return true; 5280 } 5281 5282 repeatCount--; 5283 5284 // We are going to dispatch the remaining events to either the input 5285 // or movement method. To do this, we will just send a repeated stream 5286 // of down and up events until we have done the complete repeatCount. 5287 // It would be nice if those interfaces had an onKeyMultiple() method, 5288 // but adding that is a more complicated change. 5289 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 5290 if (which == 1) { 5291 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 5292 while (--repeatCount > 0) { 5293 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 5294 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 5295 } 5296 hideErrorIfUnchanged(); 5297 5298 } else if (which == 2) { 5299 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 5300 while (--repeatCount > 0) { 5301 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 5302 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 5303 } 5304 } 5305 5306 return true; 5307 } 5308 5309 /** 5310 * Returns true if pressing ENTER in this field advances focus instead 5311 * of inserting the character. This is true mostly in single-line fields, 5312 * but also in mail addresses and subjects which will display on multiple 5313 * lines but where it doesn't make sense to insert newlines. 5314 */ 5315 private boolean shouldAdvanceFocusOnEnter() { 5316 if (mInput == null) { 5317 return false; 5318 } 5319 5320 if (mSingleLine) { 5321 return true; 5322 } 5323 5324 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 5325 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 5326 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS 5327 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 5328 return true; 5329 } 5330 } 5331 5332 return false; 5333 } 5334 5335 /** 5336 * Returns true if pressing TAB in this field advances focus instead 5337 * of inserting the character. Insert tabs only in multi-line editors. 5338 */ 5339 private boolean shouldAdvanceFocusOnTab() { 5340 if (mInput != null && !mSingleLine) { 5341 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 5342 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 5343 if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE 5344 || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { 5345 return false; 5346 } 5347 } 5348 } 5349 return true; 5350 } 5351 5352 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 5353 if (!isEnabled()) { 5354 return 0; 5355 } 5356 5357 switch (keyCode) { 5358 case KeyEvent.KEYCODE_ENTER: 5359 if (event.hasNoModifiers()) { 5360 // When mInputContentType is set, we know that we are 5361 // running in a "modern" cupcake environment, so don't need 5362 // to worry about the application trying to capture 5363 // enter key events. 5364 if (mInputContentType != null) { 5365 // If there is an action listener, given them a 5366 // chance to consume the event. 5367 if (mInputContentType.onEditorActionListener != null && 5368 mInputContentType.onEditorActionListener.onEditorAction( 5369 this, EditorInfo.IME_NULL, event)) { 5370 mInputContentType.enterDown = true; 5371 // We are consuming the enter key for them. 5372 return -1; 5373 } 5374 } 5375 5376 // If our editor should move focus when enter is pressed, or 5377 // this is a generated event from an IME action button, then 5378 // don't let it be inserted into the text. 5379 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 5380 || shouldAdvanceFocusOnEnter()) { 5381 if (hasOnClickListeners()) { 5382 return 0; 5383 } 5384 return -1; 5385 } 5386 } 5387 break; 5388 5389 case KeyEvent.KEYCODE_DPAD_CENTER: 5390 if (event.hasNoModifiers()) { 5391 if (shouldAdvanceFocusOnEnter()) { 5392 return 0; 5393 } 5394 } 5395 break; 5396 5397 case KeyEvent.KEYCODE_TAB: 5398 if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 5399 if (shouldAdvanceFocusOnTab()) { 5400 return 0; 5401 } 5402 } 5403 break; 5404 5405 // Has to be done on key down (and not on key up) to correctly be intercepted. 5406 case KeyEvent.KEYCODE_BACK: 5407 if (mSelectionActionMode != null) { 5408 stopSelectionActionMode(); 5409 return -1; 5410 } 5411 break; 5412 } 5413 5414 if (mInput != null) { 5415 resetErrorChangedFlag(); 5416 5417 boolean doDown = true; 5418 if (otherEvent != null) { 5419 try { 5420 beginBatchEdit(); 5421 final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent); 5422 hideErrorIfUnchanged(); 5423 doDown = false; 5424 if (handled) { 5425 return -1; 5426 } 5427 } catch (AbstractMethodError e) { 5428 // onKeyOther was added after 1.0, so if it isn't 5429 // implemented we need to try to dispatch as a regular down. 5430 } finally { 5431 endBatchEdit(); 5432 } 5433 } 5434 5435 if (doDown) { 5436 beginBatchEdit(); 5437 final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event); 5438 endBatchEdit(); 5439 hideErrorIfUnchanged(); 5440 if (handled) return 1; 5441 } 5442 } 5443 5444 // bug 650865: sometimes we get a key event before a layout. 5445 // don't try to move around if we don't know the layout. 5446 5447 if (mMovement != null && mLayout != null) { 5448 boolean doDown = true; 5449 if (otherEvent != null) { 5450 try { 5451 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 5452 otherEvent); 5453 doDown = false; 5454 if (handled) { 5455 return -1; 5456 } 5457 } catch (AbstractMethodError e) { 5458 // onKeyOther was added after 1.0, so if it isn't 5459 // implemented we need to try to dispatch as a regular down. 5460 } 5461 } 5462 if (doDown) { 5463 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 5464 return 2; 5465 } 5466 } 5467 5468 return 0; 5469 } 5470 5471 /** 5472 * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} 5473 * can be recorded. 5474 * @hide 5475 */ 5476 public void resetErrorChangedFlag() { 5477 /* 5478 * Keep track of what the error was before doing the input 5479 * so that if an input filter changed the error, we leave 5480 * that error showing. Otherwise, we take down whatever 5481 * error was showing when the user types something. 5482 */ 5483 mErrorWasChanged = false; 5484 } 5485 5486 /** 5487 * @hide 5488 */ 5489 public void hideErrorIfUnchanged() { 5490 if (mError != null && !mErrorWasChanged) { 5491 setError(null, null); 5492 } 5493 } 5494 5495 @Override 5496 public boolean onKeyUp(int keyCode, KeyEvent event) { 5497 if (!isEnabled()) { 5498 return super.onKeyUp(keyCode, event); 5499 } 5500 5501 switch (keyCode) { 5502 case KeyEvent.KEYCODE_DPAD_CENTER: 5503 if (event.hasNoModifiers()) { 5504 /* 5505 * If there is a click listener, just call through to 5506 * super, which will invoke it. 5507 * 5508 * If there isn't a click listener, try to show the soft 5509 * input method. (It will also 5510 * call performClick(), but that won't do anything in 5511 * this case.) 5512 */ 5513 if (!hasOnClickListeners()) { 5514 if (mMovement != null && mText instanceof Editable 5515 && mLayout != null && onCheckIsTextEditor()) { 5516 InputMethodManager imm = InputMethodManager.peekInstance(); 5517 viewClicked(imm); 5518 if (imm != null) { 5519 imm.showSoftInput(this, 0); 5520 } 5521 } 5522 } 5523 } 5524 return super.onKeyUp(keyCode, event); 5525 5526 case KeyEvent.KEYCODE_ENTER: 5527 if (event.hasNoModifiers()) { 5528 if (mInputContentType != null 5529 && mInputContentType.onEditorActionListener != null 5530 && mInputContentType.enterDown) { 5531 mInputContentType.enterDown = false; 5532 if (mInputContentType.onEditorActionListener.onEditorAction( 5533 this, EditorInfo.IME_NULL, event)) { 5534 return true; 5535 } 5536 } 5537 5538 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 5539 || shouldAdvanceFocusOnEnter()) { 5540 /* 5541 * If there is a click listener, just call through to 5542 * super, which will invoke it. 5543 * 5544 * If there isn't a click listener, try to advance focus, 5545 * but still call through to super, which will reset the 5546 * pressed state and longpress state. (It will also 5547 * call performClick(), but that won't do anything in 5548 * this case.) 5549 */ 5550 if (!hasOnClickListeners()) { 5551 View v = focusSearch(FOCUS_DOWN); 5552 5553 if (v != null) { 5554 if (!v.requestFocus(FOCUS_DOWN)) { 5555 throw new IllegalStateException( 5556 "focus search returned a view " + 5557 "that wasn't able to take focus!"); 5558 } 5559 5560 /* 5561 * Return true because we handled the key; super 5562 * will return false because there was no click 5563 * listener. 5564 */ 5565 super.onKeyUp(keyCode, event); 5566 return true; 5567 } else if ((event.getFlags() 5568 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 5569 // No target for next focus, but make sure the IME 5570 // if this came from it. 5571 InputMethodManager imm = InputMethodManager.peekInstance(); 5572 if (imm != null && imm.isActive(this)) { 5573 imm.hideSoftInputFromWindow(getWindowToken(), 0); 5574 } 5575 } 5576 } 5577 } 5578 return super.onKeyUp(keyCode, event); 5579 } 5580 break; 5581 } 5582 5583 if (mInput != null) 5584 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 5585 return true; 5586 5587 if (mMovement != null && mLayout != null) 5588 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 5589 return true; 5590 5591 return super.onKeyUp(keyCode, event); 5592 } 5593 5594 @Override 5595 public boolean onCheckIsTextEditor() { 5596 return mInputType != EditorInfo.TYPE_NULL; 5597 } 5598 5599 @Override 5600 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5601 if (onCheckIsTextEditor() && isEnabled()) { 5602 if (mInputMethodState == null) { 5603 mInputMethodState = new InputMethodState(); 5604 } 5605 outAttrs.inputType = mInputType; 5606 if (mInputContentType != null) { 5607 outAttrs.imeOptions = mInputContentType.imeOptions; 5608 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 5609 outAttrs.actionLabel = mInputContentType.imeActionLabel; 5610 outAttrs.actionId = mInputContentType.imeActionId; 5611 outAttrs.extras = mInputContentType.extras; 5612 } else { 5613 outAttrs.imeOptions = EditorInfo.IME_NULL; 5614 } 5615 if (focusSearch(FOCUS_DOWN) != null) { 5616 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 5617 } 5618 if (focusSearch(FOCUS_UP) != null) { 5619 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 5620 } 5621 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 5622 == EditorInfo.IME_ACTION_UNSPECIFIED) { 5623 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 5624 // An action has not been set, but the enter key will move to 5625 // the next focus, so set the action to that. 5626 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 5627 } else { 5628 // An action has not been set, and there is no focus to move 5629 // to, so let's just supply a "done" action. 5630 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 5631 } 5632 if (!shouldAdvanceFocusOnEnter()) { 5633 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5634 } 5635 } 5636 if (isMultilineInputType(outAttrs.inputType)) { 5637 // Multi-line text editors should always show an enter key. 5638 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5639 } 5640 outAttrs.hintText = mHint; 5641 if (mText instanceof Editable) { 5642 InputConnection ic = new EditableInputConnection(this); 5643 outAttrs.initialSelStart = getSelectionStart(); 5644 outAttrs.initialSelEnd = getSelectionEnd(); 5645 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 5646 return ic; 5647 } 5648 } 5649 return null; 5650 } 5651 5652 /** 5653 * If this TextView contains editable content, extract a portion of it 5654 * based on the information in <var>request</var> in to <var>outText</var>. 5655 * @return Returns true if the text was successfully extracted, else false. 5656 */ 5657 public boolean extractText(ExtractedTextRequest request, 5658 ExtractedText outText) { 5659 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 5660 EXTRACT_UNKNOWN, outText); 5661 } 5662 5663 static final int EXTRACT_NOTHING = -2; 5664 static final int EXTRACT_UNKNOWN = -1; 5665 5666 boolean extractTextInternal(ExtractedTextRequest request, 5667 int partialStartOffset, int partialEndOffset, int delta, 5668 ExtractedText outText) { 5669 final CharSequence content = mText; 5670 if (content != null) { 5671 if (partialStartOffset != EXTRACT_NOTHING) { 5672 final int N = content.length(); 5673 if (partialStartOffset < 0) { 5674 outText.partialStartOffset = outText.partialEndOffset = -1; 5675 partialStartOffset = 0; 5676 partialEndOffset = N; 5677 } else { 5678 // Now use the delta to determine the actual amount of text 5679 // we need. 5680 partialEndOffset += delta; 5681 // Adjust offsets to ensure we contain full spans. 5682 if (content instanceof Spanned) { 5683 Spanned spanned = (Spanned)content; 5684 Object[] spans = spanned.getSpans(partialStartOffset, 5685 partialEndOffset, ParcelableSpan.class); 5686 int i = spans.length; 5687 while (i > 0) { 5688 i--; 5689 int j = spanned.getSpanStart(spans[i]); 5690 if (j < partialStartOffset) partialStartOffset = j; 5691 j = spanned.getSpanEnd(spans[i]); 5692 if (j > partialEndOffset) partialEndOffset = j; 5693 } 5694 } 5695 outText.partialStartOffset = partialStartOffset; 5696 outText.partialEndOffset = partialEndOffset - delta; 5697 5698 if (partialStartOffset > N) { 5699 partialStartOffset = N; 5700 } else if (partialStartOffset < 0) { 5701 partialStartOffset = 0; 5702 } 5703 if (partialEndOffset > N) { 5704 partialEndOffset = N; 5705 } else if (partialEndOffset < 0) { 5706 partialEndOffset = 0; 5707 } 5708 } 5709 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 5710 outText.text = content.subSequence(partialStartOffset, 5711 partialEndOffset); 5712 } else { 5713 outText.text = TextUtils.substring(content, partialStartOffset, 5714 partialEndOffset); 5715 } 5716 } else { 5717 outText.partialStartOffset = 0; 5718 outText.partialEndOffset = 0; 5719 outText.text = ""; 5720 } 5721 outText.flags = 0; 5722 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 5723 outText.flags |= ExtractedText.FLAG_SELECTING; 5724 } 5725 if (mSingleLine) { 5726 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 5727 } 5728 outText.startOffset = 0; 5729 outText.selectionStart = getSelectionStart(); 5730 outText.selectionEnd = getSelectionEnd(); 5731 return true; 5732 } 5733 return false; 5734 } 5735 5736 boolean reportExtractedText() { 5737 final InputMethodState ims = mInputMethodState; 5738 if (ims != null) { 5739 final boolean contentChanged = ims.mContentChanged; 5740 if (contentChanged || ims.mSelectionModeChanged) { 5741 ims.mContentChanged = false; 5742 ims.mSelectionModeChanged = false; 5743 final ExtractedTextRequest req = mInputMethodState.mExtracting; 5744 if (req != null) { 5745 InputMethodManager imm = InputMethodManager.peekInstance(); 5746 if (imm != null) { 5747 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 5748 + ims.mChangedStart + " end=" + ims.mChangedEnd 5749 + " delta=" + ims.mChangedDelta); 5750 if (ims.mChangedStart < 0 && !contentChanged) { 5751 ims.mChangedStart = EXTRACT_NOTHING; 5752 } 5753 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 5754 ims.mChangedDelta, ims.mTmpExtracted)) { 5755 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 5756 + ims.mTmpExtracted.partialStartOffset 5757 + " end=" + ims.mTmpExtracted.partialEndOffset 5758 + ": " + ims.mTmpExtracted.text); 5759 imm.updateExtractedText(this, req.token, 5760 mInputMethodState.mTmpExtracted); 5761 ims.mChangedStart = EXTRACT_UNKNOWN; 5762 ims.mChangedEnd = EXTRACT_UNKNOWN; 5763 ims.mChangedDelta = 0; 5764 ims.mContentChanged = false; 5765 return true; 5766 } 5767 } 5768 } 5769 } 5770 } 5771 return false; 5772 } 5773 5774 /** 5775 * This is used to remove all style-impacting spans from text before new 5776 * extracted text is being replaced into it, so that we don't have any 5777 * lingering spans applied during the replace. 5778 */ 5779 static void removeParcelableSpans(Spannable spannable, int start, int end) { 5780 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 5781 int i = spans.length; 5782 while (i > 0) { 5783 i--; 5784 spannable.removeSpan(spans[i]); 5785 } 5786 } 5787 5788 /** 5789 * Apply to this text view the given extracted text, as previously 5790 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 5791 */ 5792 public void setExtractedText(ExtractedText text) { 5793 Editable content = getEditableText(); 5794 if (text.text != null) { 5795 if (content == null) { 5796 setText(text.text, TextView.BufferType.EDITABLE); 5797 } else if (text.partialStartOffset < 0) { 5798 removeParcelableSpans(content, 0, content.length()); 5799 content.replace(0, content.length(), text.text); 5800 } else { 5801 final int N = content.length(); 5802 int start = text.partialStartOffset; 5803 if (start > N) start = N; 5804 int end = text.partialEndOffset; 5805 if (end > N) end = N; 5806 removeParcelableSpans(content, start, end); 5807 content.replace(start, end, text.text); 5808 } 5809 } 5810 5811 // Now set the selection position... make sure it is in range, to 5812 // avoid crashes. If this is a partial update, it is possible that 5813 // the underlying text may have changed, causing us problems here. 5814 // Also we just don't want to trust clients to do the right thing. 5815 Spannable sp = (Spannable)getText(); 5816 final int N = sp.length(); 5817 int start = text.selectionStart; 5818 if (start < 0) start = 0; 5819 else if (start > N) start = N; 5820 int end = text.selectionEnd; 5821 if (end < 0) end = 0; 5822 else if (end > N) end = N; 5823 Selection.setSelection(sp, start, end); 5824 5825 // Finally, update the selection mode. 5826 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 5827 MetaKeyKeyListener.startSelecting(this, sp); 5828 } else { 5829 MetaKeyKeyListener.stopSelecting(this, sp); 5830 } 5831 } 5832 5833 /** 5834 * @hide 5835 */ 5836 public void setExtracting(ExtractedTextRequest req) { 5837 if (mInputMethodState != null) { 5838 mInputMethodState.mExtracting = req; 5839 } 5840 // This would stop a possible selection mode, but no such mode is started in case 5841 // extracted mode will start. Some text is selected though, and will trigger an action mode 5842 // in the extracted view. 5843 hideControllers(); 5844 } 5845 5846 /** 5847 * Called by the framework in response to a text completion from 5848 * the current input method, provided by it calling 5849 * {@link InputConnection#commitCompletion 5850 * InputConnection.commitCompletion()}. The default implementation does 5851 * nothing; text views that are supporting auto-completion should override 5852 * this to do their desired behavior. 5853 * 5854 * @param text The auto complete text the user has selected. 5855 */ 5856 public void onCommitCompletion(CompletionInfo text) { 5857 // intentionally empty 5858 } 5859 5860 /** 5861 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 5862 * a dictionnary) from the current input method, provided by it calling 5863 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 5864 * implementation flashes the background of the corrected word to provide feedback to the user. 5865 * 5866 * @param info The auto correct info about the text that was corrected. 5867 */ 5868 public void onCommitCorrection(CorrectionInfo info) { 5869 if (mCorrectionHighlighter == null) { 5870 mCorrectionHighlighter = new CorrectionHighlighter(); 5871 } else { 5872 mCorrectionHighlighter.invalidate(false); 5873 } 5874 5875 mCorrectionHighlighter.highlight(info); 5876 } 5877 5878 private class CorrectionHighlighter { 5879 private final Path mPath = new Path(); 5880 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5881 private int mStart, mEnd; 5882 private long mFadingStartTime; 5883 private final static int FADE_OUT_DURATION = 400; 5884 5885 public CorrectionHighlighter() { 5886 mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale); 5887 mPaint.setStyle(Paint.Style.FILL); 5888 } 5889 5890 public void highlight(CorrectionInfo info) { 5891 mStart = info.getOffset(); 5892 mEnd = mStart + info.getNewText().length(); 5893 mFadingStartTime = SystemClock.uptimeMillis(); 5894 5895 if (mStart < 0 || mEnd < 0) { 5896 stopAnimation(); 5897 } 5898 } 5899 5900 public void draw(Canvas canvas, int cursorOffsetVertical) { 5901 if (updatePath() && updatePaint()) { 5902 if (cursorOffsetVertical != 0) { 5903 canvas.translate(0, cursorOffsetVertical); 5904 } 5905 5906 canvas.drawPath(mPath, mPaint); 5907 5908 if (cursorOffsetVertical != 0) { 5909 canvas.translate(0, -cursorOffsetVertical); 5910 } 5911 invalidate(true); // TODO invalidate cursor region only 5912 } else { 5913 stopAnimation(); 5914 invalidate(false); // TODO invalidate cursor region only 5915 } 5916 } 5917 5918 private boolean updatePaint() { 5919 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5920 if (duration > FADE_OUT_DURATION) return false; 5921 5922 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5923 final int highlightColorAlpha = Color.alpha(mHighlightColor); 5924 final int color = (mHighlightColor & 0x00FFFFFF) + 5925 ((int) (highlightColorAlpha * coef) << 24); 5926 mPaint.setColor(color); 5927 return true; 5928 } 5929 5930 private boolean updatePath() { 5931 final Layout layout = TextView.this.mLayout; 5932 if (layout == null) return false; 5933 5934 // Update in case text is edited while the animation is run 5935 final int length = mText.length(); 5936 int start = Math.min(length, mStart); 5937 int end = Math.min(length, mEnd); 5938 5939 mPath.reset(); 5940 TextView.this.mLayout.getSelectionPath(start, end, mPath); 5941 return true; 5942 } 5943 5944 private void invalidate(boolean delayed) { 5945 if (TextView.this.mLayout == null) return; 5946 5947 synchronized (sTempRect) { 5948 mPath.computeBounds(sTempRect, false); 5949 5950 int left = getCompoundPaddingLeft(); 5951 int top = getExtendedPaddingTop() + getVerticalOffset(true); 5952 5953 if (delayed) { 5954 TextView.this.postInvalidateDelayed(16, // 60 Hz update 5955 left + (int) sTempRect.left, top + (int) sTempRect.top, 5956 left + (int) sTempRect.right, top + (int) sTempRect.bottom); 5957 } else { 5958 TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top, 5959 (int) sTempRect.right, (int) sTempRect.bottom); 5960 } 5961 } 5962 } 5963 5964 private void stopAnimation() { 5965 TextView.this.mCorrectionHighlighter = null; 5966 } 5967 } 5968 5969 public void beginBatchEdit() { 5970 mInBatchEditControllers = true; 5971 final InputMethodState ims = mInputMethodState; 5972 if (ims != null) { 5973 int nesting = ++ims.mBatchEditNesting; 5974 if (nesting == 1) { 5975 ims.mCursorChanged = false; 5976 ims.mChangedDelta = 0; 5977 if (ims.mContentChanged) { 5978 // We already have a pending change from somewhere else, 5979 // so turn this into a full update. 5980 ims.mChangedStart = 0; 5981 ims.mChangedEnd = mText.length(); 5982 } else { 5983 ims.mChangedStart = EXTRACT_UNKNOWN; 5984 ims.mChangedEnd = EXTRACT_UNKNOWN; 5985 ims.mContentChanged = false; 5986 } 5987 onBeginBatchEdit(); 5988 } 5989 } 5990 } 5991 5992 public void endBatchEdit() { 5993 mInBatchEditControllers = false; 5994 final InputMethodState ims = mInputMethodState; 5995 if (ims != null) { 5996 int nesting = --ims.mBatchEditNesting; 5997 if (nesting == 0) { 5998 finishBatchEdit(ims); 5999 } 6000 } 6001 } 6002 6003 void ensureEndedBatchEdit() { 6004 final InputMethodState ims = mInputMethodState; 6005 if (ims != null && ims.mBatchEditNesting != 0) { 6006 ims.mBatchEditNesting = 0; 6007 finishBatchEdit(ims); 6008 } 6009 } 6010 6011 void finishBatchEdit(final InputMethodState ims) { 6012 onEndBatchEdit(); 6013 6014 if (ims.mContentChanged || ims.mSelectionModeChanged) { 6015 updateAfterEdit(); 6016 reportExtractedText(); 6017 } else if (ims.mCursorChanged) { 6018 // Cheezy way to get us to report the current cursor location. 6019 invalidateCursor(); 6020 } 6021 } 6022 6023 void updateAfterEdit() { 6024 invalidate(); 6025 int curs = getSelectionStart(); 6026 6027 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6028 registerForPreDraw(); 6029 } 6030 6031 if (curs >= 0) { 6032 mHighlightPathBogus = true; 6033 makeBlink(); 6034 bringPointIntoView(curs); 6035 } 6036 6037 checkForResize(); 6038 } 6039 6040 /** 6041 * Called by the framework in response to a request to begin a batch 6042 * of edit operations through a call to link {@link #beginBatchEdit()}. 6043 */ 6044 public void onBeginBatchEdit() { 6045 // intentionally empty 6046 } 6047 6048 /** 6049 * Called by the framework in response to a request to end a batch 6050 * of edit operations through a call to link {@link #endBatchEdit}. 6051 */ 6052 public void onEndBatchEdit() { 6053 // intentionally empty 6054 } 6055 6056 /** 6057 * Called by the framework in response to a private command from the 6058 * current method, provided by it calling 6059 * {@link InputConnection#performPrivateCommand 6060 * InputConnection.performPrivateCommand()}. 6061 * 6062 * @param action The action name of the command. 6063 * @param data Any additional data for the command. This may be null. 6064 * @return Return true if you handled the command, else false. 6065 */ 6066 public boolean onPrivateIMECommand(String action, Bundle data) { 6067 return false; 6068 } 6069 6070 private void nullLayouts() { 6071 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 6072 mSavedLayout = (BoringLayout) mLayout; 6073 } 6074 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 6075 mSavedHintLayout = (BoringLayout) mHintLayout; 6076 } 6077 6078 mSavedMarqueeModeLayout = mLayout = mHintLayout = null; 6079 6080 mBoring = mHintBoring = null; 6081 6082 // Since it depends on the value of mLayout 6083 prepareCursorControllers(); 6084 } 6085 6086 /** 6087 * Make a new Layout based on the already-measured size of the view, 6088 * on the assumption that it was measured correctly at some point. 6089 */ 6090 private void assumeLayout() { 6091 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6092 6093 if (width < 1) { 6094 width = 0; 6095 } 6096 6097 int physicalWidth = width; 6098 6099 if (mHorizontallyScrolling) { 6100 width = VERY_WIDE; 6101 } 6102 6103 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 6104 physicalWidth, false); 6105 } 6106 6107 @Override 6108 protected void resetResolvedLayoutDirection() { 6109 super.resetResolvedLayoutDirection(); 6110 6111 if (mLayoutAlignment != null && 6112 (mTextAlign == TextAlign.VIEW_START || 6113 mTextAlign == TextAlign.VIEW_END)) { 6114 mLayoutAlignment = null; 6115 } 6116 } 6117 6118 private Layout.Alignment getLayoutAlignment() { 6119 if (mLayoutAlignment == null) { 6120 Layout.Alignment alignment; 6121 TextAlign textAlign = mTextAlign; 6122 switch (textAlign) { 6123 case INHERIT: 6124 // fall through to gravity temporarily 6125 // intention is to inherit value through view hierarchy. 6126 case GRAVITY: 6127 switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) { 6128 case Gravity.START: 6129 alignment = Layout.Alignment.ALIGN_NORMAL; 6130 break; 6131 case Gravity.END: 6132 alignment = Layout.Alignment.ALIGN_OPPOSITE; 6133 break; 6134 case Gravity.LEFT: 6135 alignment = Layout.Alignment.ALIGN_LEFT; 6136 break; 6137 case Gravity.RIGHT: 6138 alignment = Layout.Alignment.ALIGN_RIGHT; 6139 break; 6140 case Gravity.CENTER_HORIZONTAL: 6141 alignment = Layout.Alignment.ALIGN_CENTER; 6142 break; 6143 default: 6144 alignment = Layout.Alignment.ALIGN_NORMAL; 6145 break; 6146 } 6147 break; 6148 case TEXT_START: 6149 alignment = Layout.Alignment.ALIGN_NORMAL; 6150 break; 6151 case TEXT_END: 6152 alignment = Layout.Alignment.ALIGN_OPPOSITE; 6153 break; 6154 case CENTER: 6155 alignment = Layout.Alignment.ALIGN_CENTER; 6156 break; 6157 case VIEW_START: 6158 alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 6159 Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; 6160 break; 6161 case VIEW_END: 6162 alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 6163 Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; 6164 break; 6165 default: 6166 alignment = Layout.Alignment.ALIGN_NORMAL; 6167 break; 6168 } 6169 mLayoutAlignment = alignment; 6170 } 6171 return mLayoutAlignment; 6172 } 6173 6174 /** 6175 * The width passed in is now the desired layout width, 6176 * not the full view width with padding. 6177 * {@hide} 6178 */ 6179 protected void makeNewLayout(int wantWidth, int hintWidth, 6180 BoringLayout.Metrics boring, 6181 BoringLayout.Metrics hintBoring, 6182 int ellipsisWidth, boolean bringIntoView) { 6183 stopMarquee(); 6184 6185 // Update "old" cached values 6186 mOldMaximum = mMaximum; 6187 mOldMaxMode = mMaxMode; 6188 6189 mHighlightPathBogus = true; 6190 6191 if (wantWidth < 0) { 6192 wantWidth = 0; 6193 } 6194 if (hintWidth < 0) { 6195 hintWidth = 0; 6196 } 6197 6198 Layout.Alignment alignment = getLayoutAlignment(); 6199 boolean shouldEllipsize = mEllipsize != null && mInput == null; 6200 final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE && 6201 mMarqueeFadeMode != MARQUEE_FADE_NORMAL; 6202 TruncateAt effectiveEllipsize = mEllipsize; 6203 if (mEllipsize == TruncateAt.MARQUEE && 6204 mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 6205 effectiveEllipsize = TruncateAt.END_SMALL; 6206 } 6207 6208 if (mTextDir == null) { 6209 resolveTextDirection(); 6210 } 6211 6212 mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, 6213 effectiveEllipsize, effectiveEllipsize == mEllipsize); 6214 if (switchEllipsize) { 6215 TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE ? 6216 TruncateAt.END : TruncateAt.MARQUEE; 6217 mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, 6218 shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize); 6219 } 6220 6221 shouldEllipsize = mEllipsize != null; 6222 mHintLayout = null; 6223 6224 if (mHint != null) { 6225 if (shouldEllipsize) hintWidth = wantWidth; 6226 6227 if (hintBoring == UNKNOWN_BORING) { 6228 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, 6229 mHintBoring); 6230 if (hintBoring != null) { 6231 mHintBoring = hintBoring; 6232 } 6233 } 6234 6235 if (hintBoring != null) { 6236 if (hintBoring.width <= hintWidth && 6237 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 6238 if (mSavedHintLayout != null) { 6239 mHintLayout = mSavedHintLayout. 6240 replaceOrMake(mHint, mTextPaint, 6241 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6242 hintBoring, mIncludePad); 6243 } else { 6244 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6245 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6246 hintBoring, mIncludePad); 6247 } 6248 6249 mSavedHintLayout = (BoringLayout) mHintLayout; 6250 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 6251 if (mSavedHintLayout != null) { 6252 mHintLayout = mSavedHintLayout. 6253 replaceOrMake(mHint, mTextPaint, 6254 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6255 hintBoring, mIncludePad, mEllipsize, 6256 ellipsisWidth); 6257 } else { 6258 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6259 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6260 hintBoring, mIncludePad, mEllipsize, 6261 ellipsisWidth); 6262 } 6263 } else if (shouldEllipsize) { 6264 mHintLayout = new StaticLayout(mHint, 6265 0, mHint.length(), 6266 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6267 mSpacingAdd, mIncludePad, mEllipsize, 6268 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6269 } else { 6270 mHintLayout = new StaticLayout(mHint, mTextPaint, 6271 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6272 mIncludePad); 6273 } 6274 } else if (shouldEllipsize) { 6275 mHintLayout = new StaticLayout(mHint, 6276 0, mHint.length(), 6277 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6278 mSpacingAdd, mIncludePad, mEllipsize, 6279 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6280 } else { 6281 mHintLayout = new StaticLayout(mHint, mTextPaint, 6282 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6283 mIncludePad); 6284 } 6285 } 6286 6287 if (bringIntoView) { 6288 registerForPreDraw(); 6289 } 6290 6291 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6292 if (!compressText(ellipsisWidth)) { 6293 final int height = mLayoutParams.height; 6294 // If the size of the view does not depend on the size of the text, try to 6295 // start the marquee immediately 6296 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 6297 startMarquee(); 6298 } else { 6299 // Defer the start of the marquee until we know our width (see setFrame()) 6300 mRestartMarquee = true; 6301 } 6302 } 6303 } 6304 6305 // CursorControllers need a non-null mLayout 6306 prepareCursorControllers(); 6307 } 6308 6309 private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth, 6310 Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize, 6311 boolean useSaved) { 6312 Layout result = null; 6313 if (mText instanceof Spannable) { 6314 result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth, 6315 alignment, mTextDir, mSpacingMult, 6316 mSpacingAdd, mIncludePad, mInput == null ? effectiveEllipsize : null, 6317 ellipsisWidth); 6318 } else { 6319 if (boring == UNKNOWN_BORING) { 6320 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6321 if (boring != null) { 6322 mBoring = boring; 6323 } 6324 } 6325 6326 if (boring != null) { 6327 if (boring.width <= wantWidth && 6328 (effectiveEllipsize == null || boring.width <= ellipsisWidth)) { 6329 if (useSaved && mSavedLayout != null) { 6330 result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, 6331 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6332 boring, mIncludePad); 6333 } else { 6334 result = BoringLayout.make(mTransformed, mTextPaint, 6335 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6336 boring, mIncludePad); 6337 } 6338 6339 if (useSaved) { 6340 mSavedLayout = (BoringLayout) result; 6341 } 6342 } else if (shouldEllipsize && boring.width <= wantWidth) { 6343 if (useSaved && mSavedLayout != null) { 6344 result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, 6345 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6346 boring, mIncludePad, effectiveEllipsize, 6347 ellipsisWidth); 6348 } else { 6349 result = BoringLayout.make(mTransformed, mTextPaint, 6350 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6351 boring, mIncludePad, effectiveEllipsize, 6352 ellipsisWidth); 6353 } 6354 } else if (shouldEllipsize) { 6355 result = new StaticLayout(mTransformed, 6356 0, mTransformed.length(), 6357 mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, 6358 mSpacingAdd, mIncludePad, effectiveEllipsize, 6359 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6360 } else { 6361 result = new StaticLayout(mTransformed, mTextPaint, 6362 wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6363 mIncludePad); 6364 } 6365 } else if (shouldEllipsize) { 6366 result = new StaticLayout(mTransformed, 6367 0, mTransformed.length(), 6368 mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, 6369 mSpacingAdd, mIncludePad, effectiveEllipsize, 6370 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6371 } else { 6372 result = new StaticLayout(mTransformed, mTextPaint, 6373 wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6374 mIncludePad); 6375 } 6376 } 6377 return result; 6378 } 6379 6380 private boolean compressText(float width) { 6381 if (isHardwareAccelerated()) return false; 6382 6383 // Only compress the text if it hasn't been compressed by the previous pass 6384 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 6385 mTextPaint.getTextScaleX() == 1.0f) { 6386 final float textWidth = mLayout.getLineWidth(0); 6387 final float overflow = (textWidth + 1.0f - width) / width; 6388 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 6389 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 6390 post(new Runnable() { 6391 public void run() { 6392 requestLayout(); 6393 } 6394 }); 6395 return true; 6396 } 6397 } 6398 6399 return false; 6400 } 6401 6402 private static int desired(Layout layout) { 6403 int n = layout.getLineCount(); 6404 CharSequence text = layout.getText(); 6405 float max = 0; 6406 6407 // if any line was wrapped, we can't use it. 6408 // but it's ok for the last line not to have a newline 6409 6410 for (int i = 0; i < n - 1; i++) { 6411 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 6412 return -1; 6413 } 6414 6415 for (int i = 0; i < n; i++) { 6416 max = Math.max(max, layout.getLineWidth(i)); 6417 } 6418 6419 return (int) FloatMath.ceil(max); 6420 } 6421 6422 /** 6423 * Set whether the TextView includes extra top and bottom padding to make 6424 * room for accents that go above the normal ascent and descent. 6425 * The default is true. 6426 * 6427 * @attr ref android.R.styleable#TextView_includeFontPadding 6428 */ 6429 public void setIncludeFontPadding(boolean includepad) { 6430 if (mIncludePad != includepad) { 6431 mIncludePad = includepad; 6432 6433 if (mLayout != null) { 6434 nullLayouts(); 6435 requestLayout(); 6436 invalidate(); 6437 } 6438 } 6439 } 6440 6441 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 6442 6443 @Override 6444 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6445 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6446 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6447 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6448 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6449 6450 int width; 6451 int height; 6452 6453 BoringLayout.Metrics boring = UNKNOWN_BORING; 6454 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 6455 6456 if (mTextDir == null) { 6457 resolveTextDirection(); 6458 } 6459 6460 int des = -1; 6461 boolean fromexisting = false; 6462 6463 if (widthMode == MeasureSpec.EXACTLY) { 6464 // Parent has told us how big to be. So be it. 6465 width = widthSize; 6466 } else { 6467 if (mLayout != null && mEllipsize == null) { 6468 des = desired(mLayout); 6469 } 6470 6471 if (des < 0) { 6472 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6473 if (boring != null) { 6474 mBoring = boring; 6475 } 6476 } else { 6477 fromexisting = true; 6478 } 6479 6480 if (boring == null || boring == UNKNOWN_BORING) { 6481 if (des < 0) { 6482 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 6483 } 6484 6485 width = des; 6486 } else { 6487 width = boring.width; 6488 } 6489 6490 final Drawables dr = mDrawables; 6491 if (dr != null) { 6492 width = Math.max(width, dr.mDrawableWidthTop); 6493 width = Math.max(width, dr.mDrawableWidthBottom); 6494 } 6495 6496 if (mHint != null) { 6497 int hintDes = -1; 6498 int hintWidth; 6499 6500 if (mHintLayout != null && mEllipsize == null) { 6501 hintDes = desired(mHintLayout); 6502 } 6503 6504 if (hintDes < 0) { 6505 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 6506 if (hintBoring != null) { 6507 mHintBoring = hintBoring; 6508 } 6509 } 6510 6511 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 6512 if (hintDes < 0) { 6513 hintDes = (int) FloatMath.ceil( 6514 Layout.getDesiredWidth(mHint, mTextPaint)); 6515 } 6516 6517 hintWidth = hintDes; 6518 } else { 6519 hintWidth = hintBoring.width; 6520 } 6521 6522 if (hintWidth > width) { 6523 width = hintWidth; 6524 } 6525 } 6526 6527 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 6528 6529 if (mMaxWidthMode == EMS) { 6530 width = Math.min(width, mMaxWidth * getLineHeight()); 6531 } else { 6532 width = Math.min(width, mMaxWidth); 6533 } 6534 6535 if (mMinWidthMode == EMS) { 6536 width = Math.max(width, mMinWidth * getLineHeight()); 6537 } else { 6538 width = Math.max(width, mMinWidth); 6539 } 6540 6541 // Check against our minimum width 6542 width = Math.max(width, getSuggestedMinimumWidth()); 6543 6544 if (widthMode == MeasureSpec.AT_MOST) { 6545 width = Math.min(widthSize, width); 6546 } 6547 } 6548 6549 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6550 int unpaddedWidth = want; 6551 6552 if (mHorizontallyScrolling) want = VERY_WIDE; 6553 6554 int hintWant = want; 6555 int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth(); 6556 6557 if (mLayout == null) { 6558 makeNewLayout(want, hintWant, boring, hintBoring, 6559 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6560 } else { 6561 final boolean layoutChanged = (mLayout.getWidth() != want) || 6562 (hintWidth != hintWant) || 6563 (mLayout.getEllipsizedWidth() != 6564 width - getCompoundPaddingLeft() - getCompoundPaddingRight()); 6565 6566 final boolean widthChanged = (mHint == null) && 6567 (mEllipsize == null) && 6568 (want > mLayout.getWidth()) && 6569 (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want)); 6570 6571 final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum); 6572 6573 if (layoutChanged || maximumChanged) { 6574 if (!maximumChanged && widthChanged) { 6575 mLayout.increaseWidthTo(want); 6576 } else { 6577 makeNewLayout(want, hintWant, boring, hintBoring, 6578 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6579 } 6580 } else { 6581 // Nothing has changed 6582 } 6583 } 6584 6585 if (heightMode == MeasureSpec.EXACTLY) { 6586 // Parent has told us how big to be. So be it. 6587 height = heightSize; 6588 mDesiredHeightAtMeasure = -1; 6589 } else { 6590 int desired = getDesiredHeight(); 6591 6592 height = desired; 6593 mDesiredHeightAtMeasure = desired; 6594 6595 if (heightMode == MeasureSpec.AT_MOST) { 6596 height = Math.min(desired, heightSize); 6597 } 6598 } 6599 6600 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 6601 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 6602 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 6603 } 6604 6605 /* 6606 * We didn't let makeNewLayout() register to bring the cursor into view, 6607 * so do it here if there is any possibility that it is needed. 6608 */ 6609 if (mMovement != null || 6610 mLayout.getWidth() > unpaddedWidth || 6611 mLayout.getHeight() > unpaddedHeight) { 6612 registerForPreDraw(); 6613 } else { 6614 scrollTo(0, 0); 6615 } 6616 6617 setMeasuredDimension(width, height); 6618 } 6619 6620 private int getDesiredHeight() { 6621 return Math.max( 6622 getDesiredHeight(mLayout, true), 6623 getDesiredHeight(mHintLayout, mEllipsize != null)); 6624 } 6625 6626 private int getDesiredHeight(Layout layout, boolean cap) { 6627 if (layout == null) { 6628 return 0; 6629 } 6630 6631 int linecount = layout.getLineCount(); 6632 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 6633 int desired = layout.getLineTop(linecount); 6634 6635 final Drawables dr = mDrawables; 6636 if (dr != null) { 6637 desired = Math.max(desired, dr.mDrawableHeightLeft); 6638 desired = Math.max(desired, dr.mDrawableHeightRight); 6639 } 6640 6641 desired += pad; 6642 6643 if (mMaxMode == LINES) { 6644 /* 6645 * Don't cap the hint to a certain number of lines. 6646 * (Do cap it, though, if we have a maximum pixel height.) 6647 */ 6648 if (cap) { 6649 if (linecount > mMaximum) { 6650 desired = layout.getLineTop(mMaximum); 6651 6652 if (dr != null) { 6653 desired = Math.max(desired, dr.mDrawableHeightLeft); 6654 desired = Math.max(desired, dr.mDrawableHeightRight); 6655 } 6656 6657 desired += pad; 6658 linecount = mMaximum; 6659 } 6660 } 6661 } else { 6662 desired = Math.min(desired, mMaximum); 6663 } 6664 6665 if (mMinMode == LINES) { 6666 if (linecount < mMinimum) { 6667 desired += getLineHeight() * (mMinimum - linecount); 6668 } 6669 } else { 6670 desired = Math.max(desired, mMinimum); 6671 } 6672 6673 // Check against our minimum height 6674 desired = Math.max(desired, getSuggestedMinimumHeight()); 6675 6676 return desired; 6677 } 6678 6679 /** 6680 * Check whether a change to the existing text layout requires a 6681 * new view layout. 6682 */ 6683 private void checkForResize() { 6684 boolean sizeChanged = false; 6685 6686 if (mLayout != null) { 6687 // Check if our width changed 6688 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 6689 sizeChanged = true; 6690 invalidate(); 6691 } 6692 6693 // Check if our height changed 6694 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 6695 int desiredHeight = getDesiredHeight(); 6696 6697 if (desiredHeight != this.getHeight()) { 6698 sizeChanged = true; 6699 } 6700 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 6701 if (mDesiredHeightAtMeasure >= 0) { 6702 int desiredHeight = getDesiredHeight(); 6703 6704 if (desiredHeight != mDesiredHeightAtMeasure) { 6705 sizeChanged = true; 6706 } 6707 } 6708 } 6709 } 6710 6711 if (sizeChanged) { 6712 requestLayout(); 6713 // caller will have already invalidated 6714 } 6715 } 6716 6717 /** 6718 * Check whether entirely new text requires a new view layout 6719 * or merely a new text layout. 6720 */ 6721 private void checkForRelayout() { 6722 // If we have a fixed width, we can just swap in a new text layout 6723 // if the text height stays the same or if the view height is fixed. 6724 6725 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 6726 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 6727 (mHint == null || mHintLayout != null) && 6728 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 6729 // Static width, so try making a new text layout. 6730 6731 int oldht = mLayout.getHeight(); 6732 int want = mLayout.getWidth(); 6733 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 6734 6735 /* 6736 * No need to bring the text into view, since the size is not 6737 * changing (unless we do the requestLayout(), in which case it 6738 * will happen at measure). 6739 */ 6740 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 6741 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 6742 false); 6743 6744 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 6745 // In a fixed-height view, so use our new text layout. 6746 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 6747 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 6748 invalidate(); 6749 return; 6750 } 6751 6752 // Dynamic height, but height has stayed the same, 6753 // so use our new text layout. 6754 if (mLayout.getHeight() == oldht && 6755 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 6756 invalidate(); 6757 return; 6758 } 6759 } 6760 6761 // We lose: the height has changed and we have a dynamic height. 6762 // Request a new view layout using our new text layout. 6763 requestLayout(); 6764 invalidate(); 6765 } else { 6766 // Dynamic width, so we have no choice but to request a new 6767 // view layout with a new text layout. 6768 nullLayouts(); 6769 requestLayout(); 6770 invalidate(); 6771 } 6772 } 6773 6774 @Override 6775 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 6776 super.onLayout(changed, left, top, right, bottom); 6777 if (changed) mTextDisplayListIsValid = false; 6778 } 6779 6780 /** 6781 * Returns true if anything changed. 6782 */ 6783 private boolean bringTextIntoView() { 6784 int line = 0; 6785 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6786 line = mLayout.getLineCount() - 1; 6787 } 6788 6789 Layout.Alignment a = mLayout.getParagraphAlignment(line); 6790 int dir = mLayout.getParagraphDirection(line); 6791 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6792 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6793 int ht = mLayout.getHeight(); 6794 6795 int scrollx, scrolly; 6796 6797 // Convert to left, center, or right alignment. 6798 if (a == Layout.Alignment.ALIGN_NORMAL) { 6799 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT : 6800 Layout.Alignment.ALIGN_RIGHT; 6801 } else if (a == Layout.Alignment.ALIGN_OPPOSITE){ 6802 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT : 6803 Layout.Alignment.ALIGN_LEFT; 6804 } 6805 6806 if (a == Layout.Alignment.ALIGN_CENTER) { 6807 /* 6808 * Keep centered if possible, or, if it is too wide to fit, 6809 * keep leading edge in view. 6810 */ 6811 6812 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6813 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6814 6815 if (right - left < hspace) { 6816 scrollx = (right + left) / 2 - hspace / 2; 6817 } else { 6818 if (dir < 0) { 6819 scrollx = right - hspace; 6820 } else { 6821 scrollx = left; 6822 } 6823 } 6824 } else if (a == Layout.Alignment.ALIGN_RIGHT) { 6825 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6826 scrollx = right - hspace; 6827 } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) 6828 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6829 } 6830 6831 if (ht < vspace) { 6832 scrolly = 0; 6833 } else { 6834 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6835 scrolly = ht - vspace; 6836 } else { 6837 scrolly = 0; 6838 } 6839 } 6840 6841 if (scrollx != mScrollX || scrolly != mScrollY) { 6842 scrollTo(scrollx, scrolly); 6843 return true; 6844 } else { 6845 return false; 6846 } 6847 } 6848 6849 /** 6850 * Move the point, specified by the offset, into the view if it is needed. 6851 * This has to be called after layout. Returns true if anything changed. 6852 */ 6853 public boolean bringPointIntoView(int offset) { 6854 boolean changed = false; 6855 6856 if (mLayout == null) return changed; 6857 6858 int line = mLayout.getLineForOffset(offset); 6859 6860 // FIXME: Is it okay to truncate this, or should we round? 6861 final int x = (int)mLayout.getPrimaryHorizontal(offset); 6862 final int top = mLayout.getLineTop(line); 6863 final int bottom = mLayout.getLineTop(line + 1); 6864 6865 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6866 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6867 int ht = mLayout.getHeight(); 6868 6869 int grav; 6870 6871 switch (mLayout.getParagraphAlignment(line)) { 6872 case ALIGN_LEFT: 6873 grav = 1; 6874 break; 6875 case ALIGN_RIGHT: 6876 grav = -1; 6877 break; 6878 case ALIGN_NORMAL: 6879 grav = mLayout.getParagraphDirection(line); 6880 break; 6881 case ALIGN_OPPOSITE: 6882 grav = -mLayout.getParagraphDirection(line); 6883 break; 6884 case ALIGN_CENTER: 6885 default: 6886 grav = 0; 6887 break; 6888 } 6889 6890 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6891 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6892 6893 int hslack = (bottom - top) / 2; 6894 int vslack = hslack; 6895 6896 if (vslack > vspace / 4) 6897 vslack = vspace / 4; 6898 if (hslack > hspace / 4) 6899 hslack = hspace / 4; 6900 6901 int hs = mScrollX; 6902 int vs = mScrollY; 6903 6904 if (top - vs < vslack) 6905 vs = top - vslack; 6906 if (bottom - vs > vspace - vslack) 6907 vs = bottom - (vspace - vslack); 6908 if (ht - vs < vspace) 6909 vs = ht - vspace; 6910 if (0 - vs > 0) 6911 vs = 0; 6912 6913 if (grav != 0) { 6914 if (x - hs < hslack) { 6915 hs = x - hslack; 6916 } 6917 if (x - hs > hspace - hslack) { 6918 hs = x - (hspace - hslack); 6919 } 6920 } 6921 6922 if (grav < 0) { 6923 if (left - hs > 0) 6924 hs = left; 6925 if (right - hs < hspace) 6926 hs = right - hspace; 6927 } else if (grav > 0) { 6928 if (right - hs < hspace) 6929 hs = right - hspace; 6930 if (left - hs > 0) 6931 hs = left; 6932 } else /* grav == 0 */ { 6933 if (right - left <= hspace) { 6934 /* 6935 * If the entire text fits, center it exactly. 6936 */ 6937 hs = left - (hspace - (right - left)) / 2; 6938 } else if (x > right - hslack) { 6939 /* 6940 * If we are near the right edge, keep the right edge 6941 * at the edge of the view. 6942 */ 6943 hs = right - hspace; 6944 } else if (x < left + hslack) { 6945 /* 6946 * If we are near the left edge, keep the left edge 6947 * at the edge of the view. 6948 */ 6949 hs = left; 6950 } else if (left > hs) { 6951 /* 6952 * Is there whitespace visible at the left? Fix it if so. 6953 */ 6954 hs = left; 6955 } else if (right < hs + hspace) { 6956 /* 6957 * Is there whitespace visible at the right? Fix it if so. 6958 */ 6959 hs = right - hspace; 6960 } else { 6961 /* 6962 * Otherwise, float as needed. 6963 */ 6964 if (x - hs < hslack) { 6965 hs = x - hslack; 6966 } 6967 if (x - hs > hspace - hslack) { 6968 hs = x - (hspace - hslack); 6969 } 6970 } 6971 } 6972 6973 if (hs != mScrollX || vs != mScrollY) { 6974 if (mScroller == null) { 6975 scrollTo(hs, vs); 6976 } else { 6977 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6978 int dx = hs - mScrollX; 6979 int dy = vs - mScrollY; 6980 6981 if (duration > ANIMATED_SCROLL_GAP) { 6982 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6983 awakenScrollBars(mScroller.getDuration()); 6984 invalidate(); 6985 } else { 6986 if (!mScroller.isFinished()) { 6987 mScroller.abortAnimation(); 6988 } 6989 6990 scrollBy(dx, dy); 6991 } 6992 6993 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6994 } 6995 6996 changed = true; 6997 } 6998 6999 if (isFocused()) { 7000 // This offsets because getInterestingRect() is in terms of viewport coordinates, but 7001 // requestRectangleOnScreen() is in terms of content coordinates. 7002 7003 if (mTempRect == null) mTempRect = new Rect(); 7004 // The offsets here are to ensure the rectangle we are using is 7005 // within our view bounds, in case the cursor is on the far left 7006 // or right. If it isn't withing the bounds, then this request 7007 // will be ignored. 7008 mTempRect.set(x - 2, top, x + 2, bottom); 7009 getInterestingRect(mTempRect, line); 7010 mTempRect.offset(mScrollX, mScrollY); 7011 7012 if (requestRectangleOnScreen(mTempRect)) { 7013 changed = true; 7014 } 7015 } 7016 7017 return changed; 7018 } 7019 7020 /** 7021 * Move the cursor, if needed, so that it is at an offset that is visible 7022 * to the user. This will not move the cursor if it represents more than 7023 * one character (a selection range). This will only work if the 7024 * TextView contains spannable text; otherwise it will do nothing. 7025 * 7026 * @return True if the cursor was actually moved, false otherwise. 7027 */ 7028 public boolean moveCursorToVisibleOffset() { 7029 if (!(mText instanceof Spannable)) { 7030 return false; 7031 } 7032 int start = getSelectionStart(); 7033 int end = getSelectionEnd(); 7034 if (start != end) { 7035 return false; 7036 } 7037 7038 // First: make sure the line is visible on screen: 7039 7040 int line = mLayout.getLineForOffset(start); 7041 7042 final int top = mLayout.getLineTop(line); 7043 final int bottom = mLayout.getLineTop(line + 1); 7044 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 7045 int vslack = (bottom - top) / 2; 7046 if (vslack > vspace / 4) 7047 vslack = vspace / 4; 7048 final int vs = mScrollY; 7049 7050 if (top < (vs+vslack)) { 7051 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 7052 } else if (bottom > (vspace+vs-vslack)) { 7053 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 7054 } 7055 7056 // Next: make sure the character is visible on screen: 7057 7058 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 7059 final int hs = mScrollX; 7060 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 7061 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 7062 7063 // line might contain bidirectional text 7064 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 7065 final int highChar = leftChar > rightChar ? leftChar : rightChar; 7066 7067 int newStart = start; 7068 if (newStart < lowChar) { 7069 newStart = lowChar; 7070 } else if (newStart > highChar) { 7071 newStart = highChar; 7072 } 7073 7074 if (newStart != start) { 7075 Selection.setSelection((Spannable)mText, newStart); 7076 return true; 7077 } 7078 7079 return false; 7080 } 7081 7082 @Override 7083 public void computeScroll() { 7084 if (mScroller != null) { 7085 if (mScroller.computeScrollOffset()) { 7086 mScrollX = mScroller.getCurrX(); 7087 mScrollY = mScroller.getCurrY(); 7088 invalidateParentCaches(); 7089 postInvalidate(); // So we draw again 7090 } 7091 } 7092 } 7093 7094 private void getInterestingRect(Rect r, int line) { 7095 convertFromViewportToContentCoordinates(r); 7096 7097 // Rectangle can can be expanded on first and last line to take 7098 // padding into account. 7099 // TODO Take left/right padding into account too? 7100 if (line == 0) r.top -= getExtendedPaddingTop(); 7101 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 7102 } 7103 7104 private void convertFromViewportToContentCoordinates(Rect r) { 7105 final int horizontalOffset = viewportToContentHorizontalOffset(); 7106 r.left += horizontalOffset; 7107 r.right += horizontalOffset; 7108 7109 final int verticalOffset = viewportToContentVerticalOffset(); 7110 r.top += verticalOffset; 7111 r.bottom += verticalOffset; 7112 } 7113 7114 private int viewportToContentHorizontalOffset() { 7115 return getCompoundPaddingLeft() - mScrollX; 7116 } 7117 7118 private int viewportToContentVerticalOffset() { 7119 int offset = getExtendedPaddingTop() - mScrollY; 7120 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7121 offset += getVerticalOffset(false); 7122 } 7123 return offset; 7124 } 7125 7126 @Override 7127 public void debug(int depth) { 7128 super.debug(depth); 7129 7130 String output = debugIndent(depth); 7131 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 7132 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 7133 + "} "; 7134 7135 if (mText != null) { 7136 7137 output += "mText=\"" + mText + "\" "; 7138 if (mLayout != null) { 7139 output += "mLayout width=" + mLayout.getWidth() 7140 + " height=" + mLayout.getHeight(); 7141 } 7142 } else { 7143 output += "mText=NULL"; 7144 } 7145 Log.d(VIEW_LOG_TAG, output); 7146 } 7147 7148 /** 7149 * Convenience for {@link Selection#getSelectionStart}. 7150 */ 7151 @ViewDebug.ExportedProperty(category = "text") 7152 public int getSelectionStart() { 7153 return Selection.getSelectionStart(getText()); 7154 } 7155 7156 /** 7157 * Convenience for {@link Selection#getSelectionEnd}. 7158 */ 7159 @ViewDebug.ExportedProperty(category = "text") 7160 public int getSelectionEnd() { 7161 return Selection.getSelectionEnd(getText()); 7162 } 7163 7164 /** 7165 * Return true iff there is a selection inside this text view. 7166 */ 7167 public boolean hasSelection() { 7168 final int selectionStart = getSelectionStart(); 7169 final int selectionEnd = getSelectionEnd(); 7170 7171 return selectionStart >= 0 && selectionStart != selectionEnd; 7172 } 7173 7174 /** 7175 * Sets the properties of this field (lines, horizontally scrolling, 7176 * transformation method) to be for a single-line input. 7177 * 7178 * @attr ref android.R.styleable#TextView_singleLine 7179 */ 7180 public void setSingleLine() { 7181 setSingleLine(true); 7182 } 7183 7184 /** 7185 * Sets the properties of this field to transform input to ALL CAPS 7186 * display. This may use a "small caps" formatting if available. 7187 * This setting will be ignored if this field is editable or selectable. 7188 * 7189 * This call replaces the current transformation method. Disabling this 7190 * will not necessarily restore the previous behavior from before this 7191 * was enabled. 7192 * 7193 * @see #setTransformationMethod(TransformationMethod) 7194 * @attr ref android.R.styleable#TextView_textAllCaps 7195 */ 7196 public void setAllCaps(boolean allCaps) { 7197 if (allCaps) { 7198 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 7199 } else { 7200 setTransformationMethod(null); 7201 } 7202 } 7203 7204 /** 7205 * If true, sets the properties of this field (number of lines, horizontally scrolling, 7206 * transformation method) to be for a single-line input; if false, restores these to the default 7207 * conditions. 7208 * 7209 * Note that the default conditions are not necessarily those that were in effect prior this 7210 * method, and you may want to reset these properties to your custom values. 7211 * 7212 * @attr ref android.R.styleable#TextView_singleLine 7213 */ 7214 @android.view.RemotableViewMethod 7215 public void setSingleLine(boolean singleLine) { 7216 // Could be used, but may break backward compatibility. 7217 // if (mSingleLine == singleLine) return; 7218 setInputTypeSingleLine(singleLine); 7219 applySingleLine(singleLine, true, true); 7220 } 7221 7222 /** 7223 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 7224 * @param singleLine 7225 */ 7226 private void setInputTypeSingleLine(boolean singleLine) { 7227 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 7228 if (singleLine) { 7229 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7230 } else { 7231 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7232 } 7233 } 7234 } 7235 7236 private void applySingleLine(boolean singleLine, boolean applyTransformation, 7237 boolean changeMaxLines) { 7238 mSingleLine = singleLine; 7239 if (singleLine) { 7240 setLines(1); 7241 setHorizontallyScrolling(true); 7242 if (applyTransformation) { 7243 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 7244 } 7245 } else { 7246 if (changeMaxLines) { 7247 setMaxLines(Integer.MAX_VALUE); 7248 } 7249 setHorizontallyScrolling(false); 7250 if (applyTransformation) { 7251 setTransformationMethod(null); 7252 } 7253 } 7254 } 7255 7256 /** 7257 * Causes words in the text that are longer than the view is wide 7258 * to be ellipsized instead of broken in the middle. You may also 7259 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 7260 * to constrain the text to a single line. Use <code>null</code> 7261 * to turn off ellipsizing. 7262 * 7263 * If {@link #setMaxLines} has been used to set two or more lines, 7264 * {@link android.text.TextUtils.TruncateAt#END} and 7265 * {@link android.text.TextUtils.TruncateAt#MARQUEE}* are only supported 7266 * (other ellipsizing types will not do anything). 7267 * 7268 * @attr ref android.R.styleable#TextView_ellipsize 7269 */ 7270 public void setEllipsize(TextUtils.TruncateAt where) { 7271 // TruncateAt is an enum. != comparison is ok between these singleton objects. 7272 if (mEllipsize != where) { 7273 mEllipsize = where; 7274 7275 if (mLayout != null) { 7276 nullLayouts(); 7277 requestLayout(); 7278 invalidate(); 7279 } 7280 } 7281 } 7282 7283 /** 7284 * Sets how many times to repeat the marquee animation. Only applied if the 7285 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 7286 * 7287 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 7288 */ 7289 public void setMarqueeRepeatLimit(int marqueeLimit) { 7290 mMarqueeRepeatLimit = marqueeLimit; 7291 } 7292 7293 /** 7294 * Returns where, if anywhere, words that are longer than the view 7295 * is wide should be ellipsized. 7296 */ 7297 @ViewDebug.ExportedProperty 7298 public TextUtils.TruncateAt getEllipsize() { 7299 return mEllipsize; 7300 } 7301 7302 /** 7303 * Set the TextView so that when it takes focus, all the text is 7304 * selected. 7305 * 7306 * @attr ref android.R.styleable#TextView_selectAllOnFocus 7307 */ 7308 @android.view.RemotableViewMethod 7309 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 7310 mSelectAllOnFocus = selectAllOnFocus; 7311 7312 if (selectAllOnFocus && !(mText instanceof Spannable)) { 7313 setText(mText, BufferType.SPANNABLE); 7314 } 7315 } 7316 7317 /** 7318 * Set whether the cursor is visible. The default is true. 7319 * 7320 * @attr ref android.R.styleable#TextView_cursorVisible 7321 */ 7322 @android.view.RemotableViewMethod 7323 public void setCursorVisible(boolean visible) { 7324 if (mCursorVisible != visible) { 7325 mCursorVisible = visible; 7326 invalidate(); 7327 7328 makeBlink(); 7329 7330 // InsertionPointCursorController depends on mCursorVisible 7331 prepareCursorControllers(); 7332 } 7333 } 7334 7335 private boolean isCursorVisible() { 7336 return mCursorVisible && isTextEditable(); 7337 } 7338 7339 private boolean canMarquee() { 7340 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 7341 return width > 0 && (mLayout.getLineWidth(0) > width || 7342 (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null && 7343 mSavedMarqueeModeLayout.getLineWidth(0) > width)); 7344 } 7345 7346 private void startMarquee() { 7347 // Do not ellipsize EditText 7348 if (mInput != null) return; 7349 7350 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 7351 return; 7352 } 7353 7354 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 7355 getLineCount() == 1 && canMarquee()) { 7356 7357 if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 7358 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE; 7359 final Layout tmp = mLayout; 7360 mLayout = mSavedMarqueeModeLayout; 7361 mSavedMarqueeModeLayout = tmp; 7362 setHorizontalFadingEdgeEnabled(true); 7363 requestLayout(); 7364 invalidate(); 7365 } 7366 7367 if (mMarquee == null) mMarquee = new Marquee(this); 7368 mMarquee.start(mMarqueeRepeatLimit); 7369 } 7370 } 7371 7372 private void stopMarquee() { 7373 if (mMarquee != null && !mMarquee.isStopped()) { 7374 mMarquee.stop(); 7375 } 7376 7377 if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) { 7378 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 7379 final Layout tmp = mSavedMarqueeModeLayout; 7380 mSavedMarqueeModeLayout = mLayout; 7381 mLayout = tmp; 7382 setHorizontalFadingEdgeEnabled(false); 7383 requestLayout(); 7384 invalidate(); 7385 } 7386 } 7387 7388 private void startStopMarquee(boolean start) { 7389 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7390 if (start) { 7391 startMarquee(); 7392 } else { 7393 stopMarquee(); 7394 } 7395 } 7396 } 7397 7398 private static final class Marquee extends Handler { 7399 // TODO: Add an option to configure this 7400 private static final float MARQUEE_DELTA_MAX = 0.07f; 7401 private static final int MARQUEE_DELAY = 1200; 7402 private static final int MARQUEE_RESTART_DELAY = 1200; 7403 private static final int MARQUEE_RESOLUTION = 1000 / 30; 7404 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 7405 7406 private static final byte MARQUEE_STOPPED = 0x0; 7407 private static final byte MARQUEE_STARTING = 0x1; 7408 private static final byte MARQUEE_RUNNING = 0x2; 7409 7410 private static final int MESSAGE_START = 0x1; 7411 private static final int MESSAGE_TICK = 0x2; 7412 private static final int MESSAGE_RESTART = 0x3; 7413 7414 private final WeakReference<TextView> mView; 7415 7416 private byte mStatus = MARQUEE_STOPPED; 7417 private final float mScrollUnit; 7418 private float mMaxScroll; 7419 float mMaxFadeScroll; 7420 private float mGhostStart; 7421 private float mGhostOffset; 7422 private float mFadeStop; 7423 private int mRepeatLimit; 7424 7425 float mScroll; 7426 7427 Marquee(TextView v) { 7428 final float density = v.getContext().getResources().getDisplayMetrics().density; 7429 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 7430 mView = new WeakReference<TextView>(v); 7431 } 7432 7433 @Override 7434 public void handleMessage(Message msg) { 7435 switch (msg.what) { 7436 case MESSAGE_START: 7437 mStatus = MARQUEE_RUNNING; 7438 tick(); 7439 break; 7440 case MESSAGE_TICK: 7441 tick(); 7442 break; 7443 case MESSAGE_RESTART: 7444 if (mStatus == MARQUEE_RUNNING) { 7445 if (mRepeatLimit >= 0) { 7446 mRepeatLimit--; 7447 } 7448 start(mRepeatLimit); 7449 } 7450 break; 7451 } 7452 } 7453 7454 void tick() { 7455 if (mStatus != MARQUEE_RUNNING) { 7456 return; 7457 } 7458 7459 removeMessages(MESSAGE_TICK); 7460 7461 final TextView textView = mView.get(); 7462 if (textView != null && (textView.isFocused() || textView.isSelected())) { 7463 mScroll += mScrollUnit; 7464 if (mScroll > mMaxScroll) { 7465 mScroll = mMaxScroll; 7466 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 7467 } else { 7468 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 7469 } 7470 textView.invalidate(); 7471 } 7472 } 7473 7474 void stop() { 7475 mStatus = MARQUEE_STOPPED; 7476 removeMessages(MESSAGE_START); 7477 removeMessages(MESSAGE_RESTART); 7478 removeMessages(MESSAGE_TICK); 7479 resetScroll(); 7480 } 7481 7482 private void resetScroll() { 7483 mScroll = 0.0f; 7484 final TextView textView = mView.get(); 7485 if (textView != null) textView.invalidate(); 7486 } 7487 7488 void start(int repeatLimit) { 7489 if (repeatLimit == 0) { 7490 stop(); 7491 return; 7492 } 7493 mRepeatLimit = repeatLimit; 7494 final TextView textView = mView.get(); 7495 if (textView != null && textView.mLayout != null) { 7496 mStatus = MARQUEE_STARTING; 7497 mScroll = 0.0f; 7498 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 7499 textView.getCompoundPaddingRight(); 7500 final float lineWidth = textView.mLayout.getLineWidth(0); 7501 final float gap = textWidth / 3.0f; 7502 mGhostStart = lineWidth - textWidth + gap; 7503 mMaxScroll = mGhostStart + textWidth; 7504 mGhostOffset = lineWidth + gap; 7505 mFadeStop = lineWidth + textWidth / 6.0f; 7506 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 7507 7508 textView.invalidate(); 7509 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 7510 } 7511 } 7512 7513 float getGhostOffset() { 7514 return mGhostOffset; 7515 } 7516 7517 boolean shouldDrawLeftFade() { 7518 return mScroll <= mFadeStop; 7519 } 7520 7521 boolean shouldDrawGhost() { 7522 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 7523 } 7524 7525 boolean isRunning() { 7526 return mStatus == MARQUEE_RUNNING; 7527 } 7528 7529 boolean isStopped() { 7530 return mStatus == MARQUEE_STOPPED; 7531 } 7532 } 7533 7534 /** 7535 * This method is called when the text is changed, in case any subclasses 7536 * would like to know. 7537 * 7538 * Within <code>text</code>, the <code>lengthAfter</code> characters 7539 * beginning at <code>start</code> have just replaced old text that had 7540 * length <code>lengthBefore</code>. It is an error to attempt to make 7541 * changes to <code>text</code> from this callback. 7542 * 7543 * @param text The text the TextView is displaying 7544 * @param start The offset of the start of the range of the text that was 7545 * modified 7546 * @param lengthBefore The length of the former text that has been replaced 7547 * @param lengthAfter The length of the replacement modified text 7548 */ 7549 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 7550 // intentionally empty, template pattern method can be overridden by subclasses 7551 } 7552 7553 /** 7554 * This method is called when the selection has changed, in case any 7555 * subclasses would like to know. 7556 * 7557 * @param selStart The new selection start location. 7558 * @param selEnd The new selection end location. 7559 */ 7560 protected void onSelectionChanged(int selStart, int selEnd) { 7561 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7562 mTextDisplayListIsValid = false; 7563 } 7564 7565 /** 7566 * Adds a TextWatcher to the list of those whose methods are called 7567 * whenever this TextView's text changes. 7568 * <p> 7569 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 7570 * not called after {@link #setText} calls. Now, doing {@link #setText} 7571 * if there are any text changed listeners forces the buffer type to 7572 * Editable if it would not otherwise be and does call this method. 7573 */ 7574 public void addTextChangedListener(TextWatcher watcher) { 7575 if (mListeners == null) { 7576 mListeners = new ArrayList<TextWatcher>(); 7577 } 7578 7579 mListeners.add(watcher); 7580 } 7581 7582 /** 7583 * Removes the specified TextWatcher from the list of those whose 7584 * methods are called 7585 * whenever this TextView's text changes. 7586 */ 7587 public void removeTextChangedListener(TextWatcher watcher) { 7588 if (mListeners != null) { 7589 int i = mListeners.indexOf(watcher); 7590 7591 if (i >= 0) { 7592 mListeners.remove(i); 7593 } 7594 } 7595 } 7596 7597 private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) { 7598 if (mListeners != null) { 7599 final ArrayList<TextWatcher> list = mListeners; 7600 final int count = list.size(); 7601 for (int i = 0; i < count; i++) { 7602 list.get(i).beforeTextChanged(text, start, before, after); 7603 } 7604 } 7605 7606 // The spans that are inside or intersect the modified region no longer make sense 7607 removeIntersectingSpans(start, start + before, SpellCheckSpan.class); 7608 removeIntersectingSpans(start, start + before, SuggestionSpan.class); 7609 } 7610 7611 // Removes all spans that are inside or actually overlap the start..end range 7612 private <T> void removeIntersectingSpans(int start, int end, Class<T> type) { 7613 if (!(mText instanceof Editable)) return; 7614 Editable text = (Editable) mText; 7615 7616 T[] spans = text.getSpans(start, end, type); 7617 final int length = spans.length; 7618 for (int i = 0; i < length; i++) { 7619 final int s = text.getSpanStart(spans[i]); 7620 final int e = text.getSpanEnd(spans[i]); 7621 // Spans that are adjacent to the edited region will be handled in 7622 // updateSpellCheckSpans. Result depends on what will be added (space or text) 7623 if (e == start || s == end) break; 7624 text.removeSpan(spans[i]); 7625 } 7626 } 7627 7628 /** 7629 * Not private so it can be called from an inner class without going 7630 * through a thunk. 7631 */ 7632 void sendOnTextChanged(CharSequence text, int start, int before, int after) { 7633 if (mListeners != null) { 7634 final ArrayList<TextWatcher> list = mListeners; 7635 final int count = list.size(); 7636 for (int i = 0; i < count; i++) { 7637 list.get(i).onTextChanged(text, start, before, after); 7638 } 7639 } 7640 7641 updateSpellCheckSpans(start, start + after, false); 7642 mTextDisplayListIsValid = false; 7643 7644 // Hide the controllers as soon as text is modified (typing, procedural...) 7645 // We do not hide the span controllers, since they can be added when a new text is 7646 // inserted into the text view (voice IME). 7647 hideCursorControllers(); 7648 } 7649 7650 /** 7651 * Not private so it can be called from an inner class without going 7652 * through a thunk. 7653 */ 7654 void sendAfterTextChanged(Editable text) { 7655 if (mListeners != null) { 7656 final ArrayList<TextWatcher> list = mListeners; 7657 final int count = list.size(); 7658 for (int i = 0; i < count; i++) { 7659 list.get(i).afterTextChanged(text); 7660 } 7661 } 7662 } 7663 7664 /** 7665 * Not private so it can be called from an inner class without going 7666 * through a thunk. 7667 */ 7668 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 7669 final InputMethodState ims = mInputMethodState; 7670 if (ims == null || ims.mBatchEditNesting == 0) { 7671 updateAfterEdit(); 7672 } 7673 if (ims != null) { 7674 ims.mContentChanged = true; 7675 if (ims.mChangedStart < 0) { 7676 ims.mChangedStart = start; 7677 ims.mChangedEnd = start+before; 7678 } else { 7679 ims.mChangedStart = Math.min(ims.mChangedStart, start); 7680 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 7681 } 7682 ims.mChangedDelta += after-before; 7683 } 7684 7685 sendOnTextChanged(buffer, start, before, after); 7686 onTextChanged(buffer, start, before, after); 7687 } 7688 7689 /** 7690 * Not private so it can be called from an inner class without going 7691 * through a thunk. 7692 */ 7693 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 7694 // XXX Make the start and end move together if this ends up 7695 // spending too much time invalidating. 7696 7697 boolean selChanged = false; 7698 int newSelStart=-1, newSelEnd=-1; 7699 7700 final InputMethodState ims = mInputMethodState; 7701 7702 if (what == Selection.SELECTION_END) { 7703 mHighlightPathBogus = true; 7704 selChanged = true; 7705 newSelEnd = newStart; 7706 7707 if (!isFocused()) { 7708 mSelectionMoved = true; 7709 } 7710 7711 if (oldStart >= 0 || newStart >= 0) { 7712 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 7713 registerForPreDraw(); 7714 makeBlink(); 7715 } 7716 } 7717 7718 if (what == Selection.SELECTION_START) { 7719 mHighlightPathBogus = true; 7720 selChanged = true; 7721 newSelStart = newStart; 7722 7723 if (!isFocused()) { 7724 mSelectionMoved = true; 7725 } 7726 7727 if (oldStart >= 0 || newStart >= 0) { 7728 int end = Selection.getSelectionEnd(buf); 7729 invalidateCursor(end, oldStart, newStart); 7730 } 7731 } 7732 7733 if (selChanged) { 7734 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 7735 if (newSelStart < 0) { 7736 newSelStart = Selection.getSelectionStart(buf); 7737 } 7738 if (newSelEnd < 0) { 7739 newSelEnd = Selection.getSelectionEnd(buf); 7740 } 7741 onSelectionChanged(newSelStart, newSelEnd); 7742 } 7743 } 7744 7745 if (what instanceof UpdateAppearance || what instanceof ParagraphStyle || 7746 what instanceof CharacterStyle) { 7747 if (ims == null || ims.mBatchEditNesting == 0) { 7748 invalidate(); 7749 mHighlightPathBogus = true; 7750 checkForResize(); 7751 } else { 7752 ims.mContentChanged = true; 7753 } 7754 mTextDisplayListIsValid = false; 7755 } 7756 7757 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 7758 mHighlightPathBogus = true; 7759 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 7760 ims.mSelectionModeChanged = true; 7761 } 7762 7763 if (Selection.getSelectionStart(buf) >= 0) { 7764 if (ims == null || ims.mBatchEditNesting == 0) { 7765 invalidateCursor(); 7766 } else { 7767 ims.mCursorChanged = true; 7768 } 7769 } 7770 } 7771 7772 if (what instanceof ParcelableSpan) { 7773 // If this is a span that can be sent to a remote process, 7774 // the current extract editor would be interested in it. 7775 if (ims != null && ims.mExtracting != null) { 7776 if (ims.mBatchEditNesting != 0) { 7777 if (oldStart >= 0) { 7778 if (ims.mChangedStart > oldStart) { 7779 ims.mChangedStart = oldStart; 7780 } 7781 if (ims.mChangedStart > oldEnd) { 7782 ims.mChangedStart = oldEnd; 7783 } 7784 } 7785 if (newStart >= 0) { 7786 if (ims.mChangedStart > newStart) { 7787 ims.mChangedStart = newStart; 7788 } 7789 if (ims.mChangedStart > newEnd) { 7790 ims.mChangedStart = newEnd; 7791 } 7792 } 7793 } else { 7794 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 7795 + oldStart + "-" + oldEnd + "," 7796 + newStart + "-" + newEnd + what); 7797 ims.mContentChanged = true; 7798 } 7799 } 7800 } 7801 7802 if (mSpellChecker != null && newStart < 0 && what instanceof SpellCheckSpan) { 7803 mSpellChecker.removeSpellCheckSpan((SpellCheckSpan) what); 7804 } 7805 } 7806 7807 /** 7808 * Create new SpellCheckSpans on the modified region. 7809 */ 7810 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) { 7811 if (isTextEditable() && isSuggestionsEnabled() && !(this instanceof ExtractEditText)) { 7812 if (mSpellChecker == null && createSpellChecker) { 7813 mSpellChecker = new SpellChecker(this); 7814 } 7815 if (mSpellChecker != null) { 7816 mSpellChecker.spellCheck(start, end); 7817 } 7818 } 7819 } 7820 7821 /** 7822 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related 7823 * pop-up should be displayed. 7824 */ 7825 private class EasyEditSpanController { 7826 7827 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs 7828 7829 private EasyEditPopupWindow mPopupWindow; 7830 7831 private EasyEditSpan mEasyEditSpan; 7832 7833 private Runnable mHidePopup; 7834 7835 private void hide() { 7836 if (mPopupWindow != null) { 7837 mPopupWindow.hide(); 7838 TextView.this.removeCallbacks(mHidePopup); 7839 } 7840 removeSpans(mText); 7841 mEasyEditSpan = null; 7842 } 7843 7844 /** 7845 * Monitors the changes in the text. 7846 * 7847 * <p>{@link ChangeWatcher#onSpanAdded(Spannable, Object, int, int)} cannot be used, 7848 * as the notifications are not sent when a spannable (with spans) is inserted. 7849 */ 7850 public void onTextChange(CharSequence buffer) { 7851 adjustSpans(mText); 7852 7853 if (getWindowVisibility() != View.VISIBLE) { 7854 // The window is not visible yet, ignore the text change. 7855 return; 7856 } 7857 7858 if (mLayout == null) { 7859 // The view has not been layout yet, ignore the text change 7860 return; 7861 } 7862 7863 InputMethodManager imm = InputMethodManager.peekInstance(); 7864 if (!(TextView.this instanceof ExtractEditText) 7865 && imm != null && imm.isFullscreenMode()) { 7866 // The input is in extract mode. We do not have to handle the easy edit in the 7867 // original TextView, as the ExtractEditText will do 7868 return; 7869 } 7870 7871 // Remove the current easy edit span, as the text changed, and remove the pop-up 7872 // (if any) 7873 if (mEasyEditSpan != null) { 7874 if (mText instanceof Spannable) { 7875 ((Spannable) mText).removeSpan(mEasyEditSpan); 7876 } 7877 mEasyEditSpan = null; 7878 } 7879 if (mPopupWindow != null && mPopupWindow.isShowing()) { 7880 mPopupWindow.hide(); 7881 } 7882 7883 // Display the new easy edit span (if any). 7884 if (buffer instanceof Spanned) { 7885 mEasyEditSpan = getSpan((Spanned) buffer); 7886 if (mEasyEditSpan != null) { 7887 if (mPopupWindow == null) { 7888 mPopupWindow = new EasyEditPopupWindow(); 7889 mHidePopup = new Runnable() { 7890 @Override 7891 public void run() { 7892 hide(); 7893 } 7894 }; 7895 } 7896 mPopupWindow.show(mEasyEditSpan); 7897 TextView.this.removeCallbacks(mHidePopup); 7898 TextView.this.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS); 7899 } 7900 } 7901 } 7902 7903 /** 7904 * Adjusts the spans by removing all of them except the last one. 7905 */ 7906 private void adjustSpans(CharSequence buffer) { 7907 // This method enforces that only one easy edit span is attached to the text. 7908 // A better way to enforce this would be to listen for onSpanAdded, but this method 7909 // cannot be used in this scenario as no notification is triggered when a text with 7910 // spans is inserted into a text. 7911 if (buffer instanceof Spannable) { 7912 Spannable spannable = (Spannable) buffer; 7913 EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(), 7914 EasyEditSpan.class); 7915 for (int i = 0; i < spans.length - 1; i++) { 7916 spannable.removeSpan(spans[i]); 7917 } 7918 } 7919 } 7920 7921 /** 7922 * Removes all the {@link EasyEditSpan} currently attached. 7923 */ 7924 private void removeSpans(CharSequence buffer) { 7925 if (buffer instanceof Spannable) { 7926 Spannable spannable = (Spannable) buffer; 7927 EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(), 7928 EasyEditSpan.class); 7929 for (int i = 0; i < spans.length; i++) { 7930 spannable.removeSpan(spans[i]); 7931 } 7932 } 7933 } 7934 7935 private EasyEditSpan getSpan(Spanned spanned) { 7936 EasyEditSpan[] easyEditSpans = spanned.getSpans(0, spanned.length(), 7937 EasyEditSpan.class); 7938 if (easyEditSpans.length == 0) { 7939 return null; 7940 } else { 7941 return easyEditSpans[0]; 7942 } 7943 } 7944 } 7945 7946 /** 7947 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled 7948 * by {@link EasyEditSpanController}. 7949 */ 7950 private class EasyEditPopupWindow extends PinnedPopupWindow 7951 implements OnClickListener { 7952 private static final int POPUP_TEXT_LAYOUT = 7953 com.android.internal.R.layout.text_edit_action_popup_text; 7954 private TextView mDeleteTextView; 7955 private EasyEditSpan mEasyEditSpan; 7956 7957 @Override 7958 protected void createPopupWindow() { 7959 mPopupWindow = new PopupWindow(TextView.this.mContext, null, 7960 com.android.internal.R.attr.textSelectHandleWindowStyle); 7961 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 7962 mPopupWindow.setClippingEnabled(true); 7963 } 7964 7965 @Override 7966 protected void initContentView() { 7967 LinearLayout linearLayout = new LinearLayout(TextView.this.getContext()); 7968 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 7969 mContentView = linearLayout; 7970 mContentView.setBackgroundResource( 7971 com.android.internal.R.drawable.text_edit_side_paste_window); 7972 7973 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 7974 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 7975 7976 LayoutParams wrapContent = new LayoutParams( 7977 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 7978 7979 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 7980 mDeleteTextView.setLayoutParams(wrapContent); 7981 mDeleteTextView.setText(com.android.internal.R.string.delete); 7982 mDeleteTextView.setOnClickListener(this); 7983 mContentView.addView(mDeleteTextView); 7984 } 7985 7986 public void show(EasyEditSpan easyEditSpan) { 7987 mEasyEditSpan = easyEditSpan; 7988 super.show(); 7989 } 7990 7991 @Override 7992 public void onClick(View view) { 7993 if (view == mDeleteTextView) { 7994 Editable editable = (Editable) mText; 7995 int start = editable.getSpanStart(mEasyEditSpan); 7996 int end = editable.getSpanEnd(mEasyEditSpan); 7997 if (start >= 0 && end >= 0) { 7998 deleteText_internal(start, end); 7999 } 8000 } 8001 } 8002 8003 @Override 8004 protected int getTextOffset() { 8005 // Place the pop-up at the end of the span 8006 Editable editable = (Editable) mText; 8007 return editable.getSpanEnd(mEasyEditSpan); 8008 } 8009 8010 @Override 8011 protected int getVerticalLocalPosition(int line) { 8012 return mLayout.getLineBottom(line); 8013 } 8014 8015 @Override 8016 protected int clipVertically(int positionY) { 8017 // As we display the pop-up below the span, no vertical clipping is required. 8018 return positionY; 8019 } 8020 } 8021 8022 private class ChangeWatcher implements TextWatcher, SpanWatcher { 8023 8024 private CharSequence mBeforeText; 8025 8026 private EasyEditSpanController mEasyEditSpanController; 8027 8028 private ChangeWatcher() { 8029 mEasyEditSpanController = new EasyEditSpanController(); 8030 } 8031 8032 public void beforeTextChanged(CharSequence buffer, int start, 8033 int before, int after) { 8034 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 8035 + " before=" + before + " after=" + after + ": " + buffer); 8036 8037 if (AccessibilityManager.getInstance(mContext).isEnabled() 8038 && !isPasswordInputType(mInputType) 8039 && !hasPasswordTransformationMethod()) { 8040 mBeforeText = buffer.toString(); 8041 } 8042 8043 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 8044 } 8045 8046 public void onTextChanged(CharSequence buffer, int start, 8047 int before, int after) { 8048 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 8049 + " before=" + before + " after=" + after + ": " + buffer); 8050 TextView.this.handleTextChanged(buffer, start, before, after); 8051 8052 mEasyEditSpanController.onTextChange(buffer); 8053 8054 if (AccessibilityManager.getInstance(mContext).isEnabled() && 8055 (isFocused() || isSelected() && isShown())) { 8056 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 8057 mBeforeText = null; 8058 } 8059 } 8060 8061 public void afterTextChanged(Editable buffer) { 8062 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 8063 TextView.this.sendAfterTextChanged(buffer); 8064 8065 if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { 8066 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 8067 } 8068 } 8069 8070 public void onSpanChanged(Spannable buf, 8071 Object what, int s, int e, int st, int en) { 8072 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 8073 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 8074 TextView.this.spanChange(buf, what, s, st, e, en); 8075 } 8076 8077 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 8078 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 8079 + " what=" + what + ": " + buf); 8080 TextView.this.spanChange(buf, what, -1, s, -1, e); 8081 } 8082 8083 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 8084 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 8085 + " what=" + what + ": " + buf); 8086 TextView.this.spanChange(buf, what, s, -1, e, -1); 8087 } 8088 8089 private void hideControllers() { 8090 mEasyEditSpanController.hide(); 8091 } 8092 } 8093 8094 /** 8095 * @hide 8096 */ 8097 @Override 8098 public void dispatchFinishTemporaryDetach() { 8099 mDispatchTemporaryDetach = true; 8100 super.dispatchFinishTemporaryDetach(); 8101 mDispatchTemporaryDetach = false; 8102 } 8103 8104 @Override 8105 public void onStartTemporaryDetach() { 8106 super.onStartTemporaryDetach(); 8107 // Only track when onStartTemporaryDetach() is called directly, 8108 // usually because this instance is an editable field in a list 8109 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 8110 8111 // Because of View recycling in ListView, there is no easy way to know when a TextView with 8112 // selection becomes visible again. Until a better solution is found, stop text selection 8113 // mode (if any) as soon as this TextView is recycled. 8114 hideControllers(); 8115 } 8116 8117 @Override 8118 public void onFinishTemporaryDetach() { 8119 super.onFinishTemporaryDetach(); 8120 // Only track when onStartTemporaryDetach() is called directly, 8121 // usually because this instance is an editable field in a list 8122 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 8123 } 8124 8125 @Override 8126 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 8127 if (mTemporaryDetach) { 8128 // If we are temporarily in the detach state, then do nothing. 8129 super.onFocusChanged(focused, direction, previouslyFocusedRect); 8130 return; 8131 } 8132 8133 mShowCursor = SystemClock.uptimeMillis(); 8134 8135 ensureEndedBatchEdit(); 8136 8137 if (focused) { 8138 int selStart = getSelectionStart(); 8139 int selEnd = getSelectionEnd(); 8140 8141 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 8142 // mode for these, unless there was a specific selection already started. 8143 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 8144 selEnd == mText.length(); 8145 mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted; 8146 8147 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 8148 // If a tap was used to give focus to that view, move cursor at tap position. 8149 // Has to be done before onTakeFocus, which can be overloaded. 8150 final int lastTapPosition = getLastTapPosition(); 8151 if (lastTapPosition >= 0) { 8152 Selection.setSelection((Spannable) mText, lastTapPosition); 8153 } 8154 8155 if (mMovement != null) { 8156 mMovement.onTakeFocus(this, (Spannable) mText, direction); 8157 } 8158 8159 // The DecorView does not have focus when the 'Done' ExtractEditText button is 8160 // pressed. Since it is the ViewAncestor's mView, it requests focus before 8161 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 8162 // This special case ensure that we keep current selection in that case. 8163 // It would be better to know why the DecorView does not have focus at that time. 8164 if (((this instanceof ExtractEditText) || mSelectionMoved) && 8165 selStart >= 0 && selEnd >= 0) { 8166 /* 8167 * Someone intentionally set the selection, so let them 8168 * do whatever it is that they wanted to do instead of 8169 * the default on-focus behavior. We reset the selection 8170 * here instead of just skipping the onTakeFocus() call 8171 * because some movement methods do something other than 8172 * just setting the selection in theirs and we still 8173 * need to go through that path. 8174 */ 8175 Selection.setSelection((Spannable) mText, selStart, selEnd); 8176 } 8177 8178 if (mSelectAllOnFocus) { 8179 selectAll(); 8180 } 8181 8182 mTouchFocusSelected = true; 8183 } 8184 8185 mFrozenWithFocus = false; 8186 mSelectionMoved = false; 8187 8188 if (mText instanceof Spannable) { 8189 Spannable sp = (Spannable) mText; 8190 MetaKeyKeyListener.resetMetaState(sp); 8191 } 8192 8193 makeBlink(); 8194 8195 if (mError != null) { 8196 showError(); 8197 } 8198 } else { 8199 if (mError != null) { 8200 hideError(); 8201 } 8202 // Don't leave us in the middle of a batch edit. 8203 onEndBatchEdit(); 8204 8205 if (this instanceof ExtractEditText) { 8206 // terminateTextSelectionMode removes selection, which we want to keep when 8207 // ExtractEditText goes out of focus. 8208 final int selStart = getSelectionStart(); 8209 final int selEnd = getSelectionEnd(); 8210 hideControllers(); 8211 Selection.setSelection((Spannable) mText, selStart, selEnd); 8212 } else { 8213 hideControllers(); 8214 downgradeEasyCorrectionSpans(); 8215 } 8216 8217 // No need to create the controller 8218 if (mSelectionModifierCursorController != null) { 8219 mSelectionModifierCursorController.resetTouchOffsets(); 8220 } 8221 } 8222 8223 startStopMarquee(focused); 8224 8225 if (mTransformation != null) { 8226 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 8227 } 8228 8229 super.onFocusChanged(focused, direction, previouslyFocusedRect); 8230 } 8231 8232 private int getLastTapPosition() { 8233 // No need to create the controller at that point, no last tap position saved 8234 if (mSelectionModifierCursorController != null) { 8235 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 8236 if (lastTapPosition >= 0) { 8237 // Safety check, should not be possible. 8238 if (lastTapPosition > mText.length()) { 8239 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 8240 + mText.length() + ")"); 8241 lastTapPosition = mText.length(); 8242 } 8243 return lastTapPosition; 8244 } 8245 } 8246 8247 return -1; 8248 } 8249 8250 @Override 8251 public void onWindowFocusChanged(boolean hasWindowFocus) { 8252 super.onWindowFocusChanged(hasWindowFocus); 8253 8254 if (hasWindowFocus) { 8255 if (mBlink != null) { 8256 mBlink.uncancel(); 8257 makeBlink(); 8258 } 8259 } else { 8260 if (mBlink != null) { 8261 mBlink.cancel(); 8262 } 8263 // Don't leave us in the middle of a batch edit. 8264 onEndBatchEdit(); 8265 if (mInputContentType != null) { 8266 mInputContentType.enterDown = false; 8267 } 8268 8269 hideControllers(); 8270 if (mSuggestionsPopupWindow != null) { 8271 mSuggestionsPopupWindow.onParentLostFocus(); 8272 } 8273 } 8274 8275 startStopMarquee(hasWindowFocus); 8276 } 8277 8278 @Override 8279 protected void onVisibilityChanged(View changedView, int visibility) { 8280 super.onVisibilityChanged(changedView, visibility); 8281 if (visibility != VISIBLE) { 8282 hideControllers(); 8283 } 8284 } 8285 8286 /** 8287 * Use {@link BaseInputConnection#removeComposingSpans 8288 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 8289 * state from this text view. 8290 */ 8291 public void clearComposingText() { 8292 if (mText instanceof Spannable) { 8293 BaseInputConnection.removeComposingSpans((Spannable)mText); 8294 } 8295 } 8296 8297 @Override 8298 public void setSelected(boolean selected) { 8299 boolean wasSelected = isSelected(); 8300 8301 super.setSelected(selected); 8302 8303 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 8304 if (selected) { 8305 startMarquee(); 8306 } else { 8307 stopMarquee(); 8308 } 8309 } 8310 } 8311 8312 @Override 8313 public boolean onTouchEvent(MotionEvent event) { 8314 final int action = event.getActionMasked(); 8315 8316 if (hasSelectionController()) { 8317 getSelectionController().onTouchEvent(event); 8318 } 8319 8320 if (mShowSuggestionRunnable != null) { 8321 removeCallbacks(mShowSuggestionRunnable); 8322 } 8323 8324 if (action == MotionEvent.ACTION_DOWN) { 8325 mLastDownPositionX = event.getX(); 8326 mLastDownPositionY = event.getY(); 8327 8328 // Reset this state; it will be re-set if super.onTouchEvent 8329 // causes focus to move to the view. 8330 mTouchFocusSelected = false; 8331 mIgnoreActionUpEvent = false; 8332 } 8333 8334 final boolean superResult = super.onTouchEvent(event); 8335 8336 /* 8337 * Don't handle the release after a long press, because it will 8338 * move the selection away from whatever the menu action was 8339 * trying to affect. 8340 */ 8341 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 8342 mDiscardNextActionUp = false; 8343 return superResult; 8344 } 8345 8346 final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) && 8347 !mIgnoreActionUpEvent && isFocused(); 8348 8349 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 8350 && mText instanceof Spannable && mLayout != null) { 8351 boolean handled = false; 8352 8353 if (mMovement != null) { 8354 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 8355 } 8356 8357 if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable) { 8358 // The LinkMovementMethod which should handle taps on links has not been installed 8359 // on non editable text that support text selection. 8360 // We reproduce its behavior here to open links for these. 8361 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 8362 getSelectionEnd(), ClickableSpan.class); 8363 8364 if (links.length > 0) { 8365 links[0].onClick(this); 8366 handled = true; 8367 } 8368 } 8369 8370 if (touchIsFinished && (isTextEditable() || mTextIsSelectable)) { 8371 // Show the IME, except when selecting in read-only text. 8372 final InputMethodManager imm = InputMethodManager.peekInstance(); 8373 viewClicked(imm); 8374 if (!mTextIsSelectable) { 8375 handled |= imm != null && imm.showSoftInput(this, 0); 8376 } 8377 8378 boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect(); 8379 hideControllers(); 8380 if (!selectAllGotFocus && mText.length() > 0) { 8381 // Move cursor 8382 final int offset = getOffsetForPosition(event.getX(), event.getY()); 8383 Selection.setSelection((Spannable) mText, offset); 8384 if (mSpellChecker != null) { 8385 // When the cursor moves, the word that was typed may need spell check 8386 mSpellChecker.onSelectionChanged(); 8387 } 8388 if (!extractedTextModeWillBeStarted()) { 8389 if (isCursorInsideEasyCorrectionSpan()) { 8390 if (mShowSuggestionRunnable == null) { 8391 mShowSuggestionRunnable = new Runnable() { 8392 public void run() { 8393 showSuggestions(); 8394 } 8395 }; 8396 } 8397 postDelayed(mShowSuggestionRunnable, 8398 ViewConfiguration.getDoubleTapTimeout()); 8399 } else if (hasInsertionController()) { 8400 getInsertionController().show(); 8401 } 8402 } 8403 } 8404 8405 handled = true; 8406 } 8407 8408 if (handled) { 8409 return true; 8410 } 8411 } 8412 8413 return superResult; 8414 } 8415 8416 /** 8417 * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}. 8418 */ 8419 private boolean isCursorInsideSuggestionSpan() { 8420 if (!(mText instanceof Spannable)) return false; 8421 8422 SuggestionSpan[] suggestionSpans = ((Spannable) mText).getSpans(getSelectionStart(), 8423 getSelectionEnd(), SuggestionSpan.class); 8424 return (suggestionSpans.length > 0); 8425 } 8426 8427 /** 8428 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with 8429 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set. 8430 */ 8431 private boolean isCursorInsideEasyCorrectionSpan() { 8432 Spannable spannable = (Spannable) mText; 8433 SuggestionSpan[] suggestionSpans = spannable.getSpans(getSelectionStart(), 8434 getSelectionEnd(), SuggestionSpan.class); 8435 for (int i = 0; i < suggestionSpans.length; i++) { 8436 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) { 8437 return true; 8438 } 8439 } 8440 return false; 8441 } 8442 8443 /** 8444 * Downgrades to simple suggestions all the easy correction spans that are not a spell check 8445 * span. 8446 */ 8447 private void downgradeEasyCorrectionSpans() { 8448 if (mText instanceof Spannable) { 8449 Spannable spannable = (Spannable) mText; 8450 SuggestionSpan[] suggestionSpans = spannable.getSpans(0, 8451 spannable.length(), SuggestionSpan.class); 8452 for (int i = 0; i < suggestionSpans.length; i++) { 8453 int flags = suggestionSpans[i].getFlags(); 8454 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 8455 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) { 8456 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 8457 suggestionSpans[i].setFlags(flags); 8458 } 8459 } 8460 } 8461 } 8462 8463 @Override 8464 public boolean onGenericMotionEvent(MotionEvent event) { 8465 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 8466 try { 8467 if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { 8468 return true; 8469 } 8470 } catch (AbstractMethodError ex) { 8471 // onGenericMotionEvent was added to the MovementMethod interface in API 12. 8472 // Ignore its absence in case third party applications implemented the 8473 // interface directly. 8474 } 8475 } 8476 return super.onGenericMotionEvent(event); 8477 } 8478 8479 private void prepareCursorControllers() { 8480 boolean windowSupportsHandles = false; 8481 8482 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 8483 if (params instanceof WindowManager.LayoutParams) { 8484 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 8485 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 8486 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 8487 } 8488 8489 mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null; 8490 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 8491 mLayout != null; 8492 8493 if (!mInsertionControllerEnabled) { 8494 hideInsertionPointCursorController(); 8495 if (mInsertionPointCursorController != null) { 8496 mInsertionPointCursorController.onDetached(); 8497 mInsertionPointCursorController = null; 8498 } 8499 } 8500 8501 if (!mSelectionControllerEnabled) { 8502 stopSelectionActionMode(); 8503 if (mSelectionModifierCursorController != null) { 8504 mSelectionModifierCursorController.onDetached(); 8505 mSelectionModifierCursorController = null; 8506 } 8507 } 8508 } 8509 8510 /** 8511 * @return True iff this TextView contains a text that can be edited, or if this is 8512 * a selectable TextView. 8513 */ 8514 private boolean isTextEditable() { 8515 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 8516 } 8517 8518 /** 8519 * Returns true, only while processing a touch gesture, if the initial 8520 * touch down event caused focus to move to the text view and as a result 8521 * its selection changed. Only valid while processing the touch gesture 8522 * of interest. 8523 */ 8524 public boolean didTouchFocusSelect() { 8525 return mTouchFocusSelected; 8526 } 8527 8528 @Override 8529 public void cancelLongPress() { 8530 super.cancelLongPress(); 8531 mIgnoreActionUpEvent = true; 8532 } 8533 8534 @Override 8535 public boolean onTrackballEvent(MotionEvent event) { 8536 if (mMovement != null && mText instanceof Spannable && 8537 mLayout != null) { 8538 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 8539 return true; 8540 } 8541 } 8542 8543 return super.onTrackballEvent(event); 8544 } 8545 8546 public void setScroller(Scroller s) { 8547 mScroller = s; 8548 } 8549 8550 private static class Blink extends Handler implements Runnable { 8551 private final WeakReference<TextView> mView; 8552 private boolean mCancelled; 8553 8554 public Blink(TextView v) { 8555 mView = new WeakReference<TextView>(v); 8556 } 8557 8558 public void run() { 8559 if (mCancelled) { 8560 return; 8561 } 8562 8563 removeCallbacks(Blink.this); 8564 8565 TextView tv = mView.get(); 8566 8567 if (tv != null && tv.shouldBlink()) { 8568 if (tv.mLayout != null) { 8569 tv.invalidateCursorPath(); 8570 } 8571 8572 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 8573 } 8574 } 8575 8576 void cancel() { 8577 if (!mCancelled) { 8578 removeCallbacks(Blink.this); 8579 mCancelled = true; 8580 } 8581 } 8582 8583 void uncancel() { 8584 mCancelled = false; 8585 } 8586 } 8587 8588 /** 8589 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 8590 */ 8591 private boolean shouldBlink() { 8592 if (!isCursorVisible() || !isFocused()) return false; 8593 8594 final int start = getSelectionStart(); 8595 if (start < 0) return false; 8596 8597 final int end = getSelectionEnd(); 8598 if (end < 0) return false; 8599 8600 return start == end; 8601 } 8602 8603 private void makeBlink() { 8604 if (shouldBlink()) { 8605 mShowCursor = SystemClock.uptimeMillis(); 8606 if (mBlink == null) mBlink = new Blink(this); 8607 mBlink.removeCallbacks(mBlink); 8608 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 8609 } else { 8610 if (mBlink != null) mBlink.removeCallbacks(mBlink); 8611 } 8612 } 8613 8614 @Override 8615 protected float getLeftFadingEdgeStrength() { 8616 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8617 if (mEllipsize == TextUtils.TruncateAt.MARQUEE && 8618 mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 8619 if (mMarquee != null && !mMarquee.isStopped()) { 8620 final Marquee marquee = mMarquee; 8621 if (marquee.shouldDrawLeftFade()) { 8622 return marquee.mScroll / getHorizontalFadingEdgeLength(); 8623 } else { 8624 return 0.0f; 8625 } 8626 } else if (getLineCount() == 1) { 8627 final int layoutDirection = getResolvedLayoutDirection(); 8628 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8629 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8630 case Gravity.LEFT: 8631 return 0.0f; 8632 case Gravity.RIGHT: 8633 return (mLayout.getLineRight(0) - (mRight - mLeft) - 8634 getCompoundPaddingLeft() - getCompoundPaddingRight() - 8635 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 8636 case Gravity.CENTER_HORIZONTAL: 8637 return 0.0f; 8638 } 8639 } 8640 } 8641 return super.getLeftFadingEdgeStrength(); 8642 } 8643 8644 @Override 8645 protected float getRightFadingEdgeStrength() { 8646 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8647 if (mEllipsize == TextUtils.TruncateAt.MARQUEE && 8648 mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 8649 if (mMarquee != null && !mMarquee.isStopped()) { 8650 final Marquee marquee = mMarquee; 8651 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 8652 } else if (getLineCount() == 1) { 8653 final int layoutDirection = getResolvedLayoutDirection(); 8654 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8655 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8656 case Gravity.LEFT: 8657 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 8658 getCompoundPaddingRight(); 8659 final float lineWidth = mLayout.getLineWidth(0); 8660 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 8661 case Gravity.RIGHT: 8662 return 0.0f; 8663 case Gravity.CENTER_HORIZONTAL: 8664 case Gravity.FILL_HORIZONTAL: 8665 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 8666 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 8667 getHorizontalFadingEdgeLength(); 8668 } 8669 } 8670 } 8671 return super.getRightFadingEdgeStrength(); 8672 } 8673 8674 @Override 8675 protected int computeHorizontalScrollRange() { 8676 if (mLayout != null) { 8677 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 8678 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 8679 } 8680 8681 return super.computeHorizontalScrollRange(); 8682 } 8683 8684 @Override 8685 protected int computeVerticalScrollRange() { 8686 if (mLayout != null) 8687 return mLayout.getHeight(); 8688 8689 return super.computeVerticalScrollRange(); 8690 } 8691 8692 @Override 8693 protected int computeVerticalScrollExtent() { 8694 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 8695 } 8696 8697 @Override 8698 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 8699 super.findViewsWithText(outViews, searched, flags); 8700 if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0 8701 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) { 8702 String searchedLowerCase = searched.toString().toLowerCase(); 8703 String textLowerCase = mText.toString().toLowerCase(); 8704 if (textLowerCase.contains(searchedLowerCase)) { 8705 outViews.add(this); 8706 } 8707 } 8708 } 8709 8710 public enum BufferType { 8711 NORMAL, SPANNABLE, EDITABLE, 8712 } 8713 8714 /** 8715 * Returns the TextView_textColor attribute from the 8716 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 8717 * from the TextView_textAppearance attribute, if TextView_textColor 8718 * was not set directly. 8719 */ 8720 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 8721 ColorStateList colors; 8722 colors = attrs.getColorStateList(com.android.internal.R.styleable. 8723 TextView_textColor); 8724 8725 if (colors == null) { 8726 int ap = attrs.getResourceId(com.android.internal.R.styleable. 8727 TextView_textAppearance, -1); 8728 if (ap != -1) { 8729 TypedArray appearance; 8730 appearance = context.obtainStyledAttributes(ap, 8731 com.android.internal.R.styleable.TextAppearance); 8732 colors = appearance.getColorStateList(com.android.internal.R.styleable. 8733 TextAppearance_textColor); 8734 appearance.recycle(); 8735 } 8736 } 8737 8738 return colors; 8739 } 8740 8741 /** 8742 * Returns the default color from the TextView_textColor attribute 8743 * from the AttributeSet, if set, or the default color from the 8744 * TextAppearance_textColor from the TextView_textAppearance attribute, 8745 * if TextView_textColor was not set directly. 8746 */ 8747 public static int getTextColor(Context context, 8748 TypedArray attrs, 8749 int def) { 8750 ColorStateList colors = getTextColors(context, attrs); 8751 8752 if (colors == null) { 8753 return def; 8754 } else { 8755 return colors.getDefaultColor(); 8756 } 8757 } 8758 8759 @Override 8760 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8761 final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; 8762 if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { 8763 switch (keyCode) { 8764 case KeyEvent.KEYCODE_A: 8765 if (canSelectText()) { 8766 return onTextContextMenuItem(ID_SELECT_ALL); 8767 } 8768 break; 8769 case KeyEvent.KEYCODE_X: 8770 if (canCut()) { 8771 return onTextContextMenuItem(ID_CUT); 8772 } 8773 break; 8774 case KeyEvent.KEYCODE_C: 8775 if (canCopy()) { 8776 return onTextContextMenuItem(ID_COPY); 8777 } 8778 break; 8779 case KeyEvent.KEYCODE_V: 8780 if (canPaste()) { 8781 return onTextContextMenuItem(ID_PASTE); 8782 } 8783 break; 8784 } 8785 } 8786 return super.onKeyShortcut(keyCode, event); 8787 } 8788 8789 /** 8790 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 8791 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 8792 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 8793 */ 8794 private boolean canSelectText() { 8795 return hasSelectionController() && mText.length() != 0; 8796 } 8797 8798 /** 8799 * Test based on the <i>intrinsic</i> charateristics of the TextView. 8800 * The text must be spannable and the movement method must allow for arbitary selection. 8801 * 8802 * See also {@link #canSelectText()}. 8803 */ 8804 private boolean textCanBeSelected() { 8805 // prepareCursorController() relies on this method. 8806 // If you change this condition, make sure prepareCursorController is called anywhere 8807 // the value of this condition might be changed. 8808 if (mMovement == null || !mMovement.canSelectArbitrarily()) return false; 8809 return isTextEditable() || (mTextIsSelectable && mText instanceof Spannable && isEnabled()); 8810 } 8811 8812 private boolean canCut() { 8813 if (hasPasswordTransformationMethod()) { 8814 return false; 8815 } 8816 8817 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 8818 return true; 8819 } 8820 8821 return false; 8822 } 8823 8824 private boolean canCopy() { 8825 if (hasPasswordTransformationMethod()) { 8826 return false; 8827 } 8828 8829 if (mText.length() > 0 && hasSelection()) { 8830 return true; 8831 } 8832 8833 return false; 8834 } 8835 8836 private boolean canPaste() { 8837 return (mText instanceof Editable && 8838 mInput != null && 8839 getSelectionStart() >= 0 && 8840 getSelectionEnd() >= 0 && 8841 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 8842 hasPrimaryClip()); 8843 } 8844 8845 private static long packRangeInLong(int start, int end) { 8846 return (((long) start) << 32) | end; 8847 } 8848 8849 private static int extractRangeStartFromLong(long range) { 8850 return (int) (range >>> 32); 8851 } 8852 8853 private static int extractRangeEndFromLong(long range) { 8854 return (int) (range & 0x00000000FFFFFFFFL); 8855 } 8856 8857 private boolean selectAll() { 8858 final int length = mText.length(); 8859 Selection.setSelection((Spannable) mText, 0, length); 8860 return length > 0; 8861 } 8862 8863 /** 8864 * Adjusts selection to the word under last touch offset. 8865 * Return true if the operation was successfully performed. 8866 */ 8867 private boolean selectCurrentWord() { 8868 if (!canSelectText()) { 8869 return false; 8870 } 8871 8872 if (hasPasswordTransformationMethod()) { 8873 // Always select all on a password field. 8874 // Cut/copy menu entries are not available for passwords, but being able to select all 8875 // is however useful to delete or paste to replace the entire content. 8876 return selectAll(); 8877 } 8878 8879 int klass = mInputType & InputType.TYPE_MASK_CLASS; 8880 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 8881 8882 // Specific text field types: select the entire text for these 8883 if (klass == InputType.TYPE_CLASS_NUMBER || 8884 klass == InputType.TYPE_CLASS_PHONE || 8885 klass == InputType.TYPE_CLASS_DATETIME || 8886 variation == InputType.TYPE_TEXT_VARIATION_URI || 8887 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 8888 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 8889 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 8890 return selectAll(); 8891 } 8892 8893 long lastTouchOffsets = getLastTouchOffsets(); 8894 final int minOffset = extractRangeStartFromLong(lastTouchOffsets); 8895 final int maxOffset = extractRangeEndFromLong(lastTouchOffsets); 8896 8897 // Safety check in case standard touch event handling has been bypassed 8898 if (minOffset < 0 || minOffset >= mText.length()) return false; 8899 if (maxOffset < 0 || maxOffset >= mText.length()) return false; 8900 8901 int selectionStart, selectionEnd; 8902 8903 // If a URLSpan (web address, email, phone...) is found at that position, select it. 8904 URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class); 8905 if (urlSpans.length >= 1) { 8906 URLSpan urlSpan = urlSpans[0]; 8907 selectionStart = ((Spanned) mText).getSpanStart(urlSpan); 8908 selectionEnd = ((Spanned) mText).getSpanEnd(urlSpan); 8909 } else { 8910 final WordIterator wordIterator = getWordIterator(); 8911 wordIterator.setCharSequence(mText, minOffset, maxOffset); 8912 8913 selectionStart = wordIterator.getBeginning(minOffset); 8914 selectionEnd = wordIterator.getEnd(maxOffset); 8915 8916 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE || 8917 selectionStart == selectionEnd) { 8918 // Possible when the word iterator does not properly handle the text's language 8919 long range = getCharRange(minOffset); 8920 selectionStart = extractRangeStartFromLong(range); 8921 selectionEnd = extractRangeEndFromLong(range); 8922 } 8923 } 8924 8925 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8926 return selectionEnd > selectionStart; 8927 } 8928 8929 /** 8930 * This is a temporary method. Future versions may support multi-locale text. 8931 * 8932 * @return The locale that should be used for a word iterator and a spell checker 8933 * in this TextView, based on the current spell checker settings, 8934 * the current IME's locale, or the system default locale. 8935 * @hide 8936 */ 8937 public Locale getTextServicesLocale() { 8938 Locale locale = Locale.getDefault(); 8939 final TextServicesManager textServicesManager = (TextServicesManager) 8940 mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); 8941 final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true); 8942 if (subtype != null) { 8943 locale = new Locale(subtype.getLocale()); 8944 } 8945 return locale; 8946 } 8947 8948 void onLocaleChanged() { 8949 // Will be re-created on demand in getWordIterator with the proper new locale 8950 mWordIterator = null; 8951 } 8952 8953 /** 8954 * @hide 8955 */ 8956 public WordIterator getWordIterator() { 8957 if (mWordIterator == null) { 8958 mWordIterator = new WordIterator(getTextServicesLocale()); 8959 } 8960 return mWordIterator; 8961 } 8962 8963 private long getCharRange(int offset) { 8964 final int textLength = mText.length(); 8965 if (offset + 1 < textLength) { 8966 final char currentChar = mText.charAt(offset); 8967 final char nextChar = mText.charAt(offset + 1); 8968 if (Character.isSurrogatePair(currentChar, nextChar)) { 8969 return packRangeInLong(offset, offset + 2); 8970 } 8971 } 8972 if (offset < textLength) { 8973 return packRangeInLong(offset, offset + 1); 8974 } 8975 if (offset - 2 >= 0) { 8976 final char previousChar = mText.charAt(offset - 1); 8977 final char previousPreviousChar = mText.charAt(offset - 2); 8978 if (Character.isSurrogatePair(previousPreviousChar, previousChar)) { 8979 return packRangeInLong(offset - 2, offset); 8980 } 8981 } 8982 if (offset - 1 >= 0) { 8983 return packRangeInLong(offset - 1, offset); 8984 } 8985 return packRangeInLong(offset, offset); 8986 } 8987 8988 private long getLastTouchOffsets() { 8989 SelectionModifierCursorController selectionController = getSelectionController(); 8990 final int minOffset = selectionController.getMinTouchOffset(); 8991 final int maxOffset = selectionController.getMaxTouchOffset(); 8992 return packRangeInLong(minOffset, maxOffset); 8993 } 8994 8995 @Override 8996 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 8997 super.onPopulateAccessibilityEvent(event); 8998 8999 final boolean isPassword = hasPasswordTransformationMethod(); 9000 if (!isPassword) { 9001 CharSequence text = getTextForAccessibility(); 9002 if (!TextUtils.isEmpty(text)) { 9003 event.getText().add(text); 9004 } 9005 } 9006 } 9007 9008 @Override 9009 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 9010 super.onInitializeAccessibilityEvent(event); 9011 9012 event.setClassName(TextView.class.getName()); 9013 final boolean isPassword = hasPasswordTransformationMethod(); 9014 event.setPassword(isPassword); 9015 9016 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { 9017 event.setFromIndex(Selection.getSelectionStart(mText)); 9018 event.setToIndex(Selection.getSelectionEnd(mText)); 9019 event.setItemCount(mText.length()); 9020 } 9021 } 9022 9023 @Override 9024 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 9025 super.onInitializeAccessibilityNodeInfo(info); 9026 9027 info.setClassName(TextView.class.getName()); 9028 final boolean isPassword = hasPasswordTransformationMethod(); 9029 info.setPassword(isPassword); 9030 9031 if (!isPassword) { 9032 info.setText(getTextForAccessibility()); 9033 } 9034 } 9035 9036 @Override 9037 public void sendAccessibilityEvent(int eventType) { 9038 // Do not send scroll events since first they are not interesting for 9039 // accessibility and second such events a generated too frequently. 9040 // For details see the implementation of bringTextIntoView(). 9041 if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) { 9042 return; 9043 } 9044 super.sendAccessibilityEvent(eventType); 9045 } 9046 9047 /** 9048 * Gets the text reported for accessibility purposes. It is the 9049 * text if not empty or the hint. 9050 * 9051 * @return The accessibility text. 9052 */ 9053 private CharSequence getTextForAccessibility() { 9054 CharSequence text = getText(); 9055 if (TextUtils.isEmpty(text)) { 9056 text = getHint(); 9057 } 9058 return text; 9059 } 9060 9061 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 9062 int fromIndex, int removedCount, int addedCount) { 9063 AccessibilityEvent event = 9064 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 9065 event.setFromIndex(fromIndex); 9066 event.setRemovedCount(removedCount); 9067 event.setAddedCount(addedCount); 9068 event.setBeforeText(beforeText); 9069 sendAccessibilityEventUnchecked(event); 9070 } 9071 9072 /** 9073 * Returns whether this text view is a current input method target. The 9074 * default implementation just checks with {@link InputMethodManager}. 9075 */ 9076 public boolean isInputMethodTarget() { 9077 InputMethodManager imm = InputMethodManager.peekInstance(); 9078 return imm != null && imm.isActive(this); 9079 } 9080 9081 // Selection context mode 9082 private static final int ID_SELECT_ALL = android.R.id.selectAll; 9083 private static final int ID_CUT = android.R.id.cut; 9084 private static final int ID_COPY = android.R.id.copy; 9085 private static final int ID_PASTE = android.R.id.paste; 9086 9087 /** 9088 * Called when a context menu option for the text view is selected. Currently 9089 * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut}, 9090 * {@link android.R.id#copy} or {@link android.R.id#paste}. 9091 * 9092 * @return true if the context menu item action was performed. 9093 */ 9094 public boolean onTextContextMenuItem(int id) { 9095 int min = 0; 9096 int max = mText.length(); 9097 9098 if (isFocused()) { 9099 final int selStart = getSelectionStart(); 9100 final int selEnd = getSelectionEnd(); 9101 9102 min = Math.max(0, Math.min(selStart, selEnd)); 9103 max = Math.max(0, Math.max(selStart, selEnd)); 9104 } 9105 9106 switch (id) { 9107 case ID_SELECT_ALL: 9108 // This does not enter text selection mode. Text is highlighted, so that it can be 9109 // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. 9110 selectAll(); 9111 return true; 9112 9113 case ID_PASTE: 9114 paste(min, max); 9115 return true; 9116 9117 case ID_CUT: 9118 setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max))); 9119 deleteText_internal(min, max); 9120 stopSelectionActionMode(); 9121 return true; 9122 9123 case ID_COPY: 9124 setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max))); 9125 stopSelectionActionMode(); 9126 return true; 9127 } 9128 return false; 9129 } 9130 9131 private CharSequence getTransformedText(int start, int end) { 9132 return removeSuggestionSpans(mTransformed.subSequence(start, end)); 9133 } 9134 9135 /** 9136 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 9137 * by [min, max] when replacing this region by paste. 9138 * Note that if there were two spaces (or more) at that position before, they are kept. We just 9139 * make sure we do not add an extra one from the paste content. 9140 */ 9141 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 9142 if (paste.length() > 0) { 9143 if (min > 0) { 9144 final char charBefore = mTransformed.charAt(min - 1); 9145 final char charAfter = paste.charAt(0); 9146 9147 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 9148 // Two spaces at beginning of paste: remove one 9149 final int originalLength = mText.length(); 9150 deleteText_internal(min - 1, min); 9151 // Due to filters, there is no guarantee that exactly one character was 9152 // removed: count instead. 9153 final int delta = mText.length() - originalLength; 9154 min += delta; 9155 max += delta; 9156 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 9157 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 9158 // No space at beginning of paste: add one 9159 final int originalLength = mText.length(); 9160 replaceText_internal(min, min, " "); 9161 // Taking possible filters into account as above. 9162 final int delta = mText.length() - originalLength; 9163 min += delta; 9164 max += delta; 9165 } 9166 } 9167 9168 if (max < mText.length()) { 9169 final char charBefore = paste.charAt(paste.length() - 1); 9170 final char charAfter = mTransformed.charAt(max); 9171 9172 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 9173 // Two spaces at end of paste: remove one 9174 deleteText_internal(max, max + 1); 9175 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 9176 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 9177 // No space at end of paste: add one 9178 replaceText_internal(max, max, " "); 9179 } 9180 } 9181 } 9182 9183 return packRangeInLong(min, max); 9184 } 9185 9186 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 9187 TextView shadowView = (TextView) inflate(mContext, 9188 com.android.internal.R.layout.text_drag_thumbnail, null); 9189 9190 if (shadowView == null) { 9191 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 9192 } 9193 9194 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 9195 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 9196 } 9197 shadowView.setText(text); 9198 shadowView.setTextColor(getTextColors()); 9199 9200 shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 9201 shadowView.setGravity(Gravity.CENTER); 9202 9203 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 9204 ViewGroup.LayoutParams.WRAP_CONTENT)); 9205 9206 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 9207 shadowView.measure(size, size); 9208 9209 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 9210 shadowView.invalidate(); 9211 return new DragShadowBuilder(shadowView); 9212 } 9213 9214 private static class DragLocalState { 9215 public TextView sourceTextView; 9216 public int start, end; 9217 9218 public DragLocalState(TextView sourceTextView, int start, int end) { 9219 this.sourceTextView = sourceTextView; 9220 this.start = start; 9221 this.end = end; 9222 } 9223 } 9224 9225 @Override 9226 public boolean performLongClick() { 9227 boolean handled = false; 9228 boolean vibrate = true; 9229 9230 if (super.performLongClick()) { 9231 handled = true; 9232 } 9233 9234 // Long press in empty space moves cursor and shows the Paste affordance if available. 9235 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 9236 mInsertionControllerEnabled) { 9237 final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY); 9238 stopSelectionActionMode(); 9239 Selection.setSelection((Spannable) mText, offset); 9240 getInsertionController().showWithActionPopup(); 9241 handled = true; 9242 vibrate = false; 9243 } 9244 9245 if (!handled && mSelectionActionMode != null) { 9246 if (touchPositionIsInSelection()) { 9247 // Start a drag 9248 final int start = getSelectionStart(); 9249 final int end = getSelectionEnd(); 9250 CharSequence selectedText = getTransformedText(start, end); 9251 ClipData data = ClipData.newPlainText(null, selectedText); 9252 DragLocalState localState = new DragLocalState(this, start, end); 9253 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 9254 stopSelectionActionMode(); 9255 } else { 9256 getSelectionController().hide(); 9257 selectCurrentWord(); 9258 getSelectionController().show(); 9259 } 9260 handled = true; 9261 } 9262 9263 // Start a new selection 9264 if (!handled) { 9265 vibrate = handled = startSelectionActionMode(); 9266 } 9267 9268 if (vibrate) { 9269 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 9270 } 9271 9272 if (handled) { 9273 mDiscardNextActionUp = true; 9274 } 9275 9276 return handled; 9277 } 9278 9279 private boolean touchPositionIsInSelection() { 9280 int selectionStart = getSelectionStart(); 9281 int selectionEnd = getSelectionEnd(); 9282 9283 if (selectionStart == selectionEnd) { 9284 return false; 9285 } 9286 9287 if (selectionStart > selectionEnd) { 9288 int tmp = selectionStart; 9289 selectionStart = selectionEnd; 9290 selectionEnd = tmp; 9291 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 9292 } 9293 9294 SelectionModifierCursorController selectionController = getSelectionController(); 9295 int minOffset = selectionController.getMinTouchOffset(); 9296 int maxOffset = selectionController.getMaxTouchOffset(); 9297 9298 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 9299 } 9300 9301 private PositionListener getPositionListener() { 9302 if (mPositionListener == null) { 9303 mPositionListener = new PositionListener(); 9304 } 9305 return mPositionListener; 9306 } 9307 9308 private interface TextViewPositionListener { 9309 public void updatePosition(int parentPositionX, int parentPositionY, 9310 boolean parentPositionChanged, boolean parentScrolled); 9311 } 9312 9313 private class PositionListener implements ViewTreeObserver.OnPreDrawListener { 9314 // 3 handles 9315 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others) 9316 private final int MAXIMUM_NUMBER_OF_LISTENERS = 6; 9317 private TextViewPositionListener[] mPositionListeners = 9318 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS]; 9319 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS]; 9320 private boolean mPositionHasChanged = true; 9321 // Absolute position of the TextView with respect to its parent window 9322 private int mPositionX, mPositionY; 9323 private int mNumberOfListeners; 9324 private boolean mScrollHasChanged; 9325 9326 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) { 9327 if (mNumberOfListeners == 0) { 9328 updatePosition(); 9329 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9330 vto.addOnPreDrawListener(this); 9331 } 9332 9333 int emptySlotIndex = -1; 9334 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 9335 TextViewPositionListener listener = mPositionListeners[i]; 9336 if (listener == positionListener) { 9337 return; 9338 } else if (emptySlotIndex < 0 && listener == null) { 9339 emptySlotIndex = i; 9340 } 9341 } 9342 9343 mPositionListeners[emptySlotIndex] = positionListener; 9344 mCanMove[emptySlotIndex] = canMove; 9345 mNumberOfListeners++; 9346 } 9347 9348 public void removeSubscriber(TextViewPositionListener positionListener) { 9349 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 9350 if (mPositionListeners[i] == positionListener) { 9351 mPositionListeners[i] = null; 9352 mNumberOfListeners--; 9353 break; 9354 } 9355 } 9356 9357 if (mNumberOfListeners == 0) { 9358 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9359 vto.removeOnPreDrawListener(this); 9360 } 9361 } 9362 9363 public int getPositionX() { 9364 return mPositionX; 9365 } 9366 9367 public int getPositionY() { 9368 return mPositionY; 9369 } 9370 9371 @Override 9372 public boolean onPreDraw() { 9373 updatePosition(); 9374 9375 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 9376 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) { 9377 TextViewPositionListener positionListener = mPositionListeners[i]; 9378 if (positionListener != null) { 9379 positionListener.updatePosition(mPositionX, mPositionY, 9380 mPositionHasChanged, mScrollHasChanged); 9381 } 9382 } 9383 } 9384 9385 mScrollHasChanged = false; 9386 return true; 9387 } 9388 9389 private void updatePosition() { 9390 TextView.this.getLocationInWindow(mTempCoords); 9391 9392 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY; 9393 9394 mPositionX = mTempCoords[0]; 9395 mPositionY = mTempCoords[1]; 9396 } 9397 9398 public void onScrollChanged() { 9399 mScrollHasChanged = true; 9400 } 9401 } 9402 9403 private boolean isPositionVisible(int positionX, int positionY) { 9404 synchronized (sTmpPosition) { 9405 final float[] position = sTmpPosition; 9406 position[0] = positionX; 9407 position[1] = positionY; 9408 View view = this; 9409 9410 while (view != null) { 9411 if (view != this) { 9412 // Local scroll is already taken into account in positionX/Y 9413 position[0] -= view.getScrollX(); 9414 position[1] -= view.getScrollY(); 9415 } 9416 9417 if (position[0] < 0 || position[1] < 0 || 9418 position[0] > view.getWidth() || position[1] > view.getHeight()) { 9419 return false; 9420 } 9421 9422 if (!view.getMatrix().isIdentity()) { 9423 view.getMatrix().mapPoints(position); 9424 } 9425 9426 position[0] += view.getLeft(); 9427 position[1] += view.getTop(); 9428 9429 final ViewParent parent = view.getParent(); 9430 if (parent instanceof View) { 9431 view = (View) parent; 9432 } else { 9433 // We've reached the ViewRoot, stop iterating 9434 view = null; 9435 } 9436 } 9437 } 9438 9439 // We've been able to walk up the view hierarchy and the position was never clipped 9440 return true; 9441 } 9442 9443 private boolean isOffsetVisible(int offset) { 9444 final int line = mLayout.getLineForOffset(offset); 9445 final int lineBottom = mLayout.getLineBottom(line); 9446 final int primaryHorizontal = (int) mLayout.getPrimaryHorizontal(offset); 9447 return isPositionVisible(primaryHorizontal + viewportToContentHorizontalOffset(), 9448 lineBottom + viewportToContentVerticalOffset()); 9449 } 9450 9451 @Override 9452 protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { 9453 super.onScrollChanged(horiz, vert, oldHoriz, oldVert); 9454 if (mPositionListener != null) { 9455 mPositionListener.onScrollChanged(); 9456 } 9457 } 9458 9459 private abstract class PinnedPopupWindow implements TextViewPositionListener { 9460 protected PopupWindow mPopupWindow; 9461 protected ViewGroup mContentView; 9462 int mPositionX, mPositionY; 9463 9464 protected abstract void createPopupWindow(); 9465 protected abstract void initContentView(); 9466 protected abstract int getTextOffset(); 9467 protected abstract int getVerticalLocalPosition(int line); 9468 protected abstract int clipVertically(int positionY); 9469 9470 public PinnedPopupWindow() { 9471 createPopupWindow(); 9472 9473 mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 9474 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 9475 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 9476 9477 initContentView(); 9478 9479 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 9480 ViewGroup.LayoutParams.WRAP_CONTENT); 9481 mContentView.setLayoutParams(wrapContent); 9482 9483 mPopupWindow.setContentView(mContentView); 9484 } 9485 9486 public void show() { 9487 TextView.this.getPositionListener().addSubscriber(this, false /* offset is fixed */); 9488 9489 computeLocalPosition(); 9490 9491 final PositionListener positionListener = TextView.this.getPositionListener(); 9492 updatePosition(positionListener.getPositionX(), positionListener.getPositionY()); 9493 } 9494 9495 protected void measureContent() { 9496 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9497 mContentView.measure( 9498 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, 9499 View.MeasureSpec.AT_MOST), 9500 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, 9501 View.MeasureSpec.AT_MOST)); 9502 } 9503 9504 /* The popup window will be horizontally centered on the getTextOffset() and vertically 9505 * positioned according to viewportToContentHorizontalOffset. 9506 * 9507 * This method assumes that mContentView has properly been measured from its content. */ 9508 private void computeLocalPosition() { 9509 measureContent(); 9510 final int width = mContentView.getMeasuredWidth(); 9511 final int offset = getTextOffset(); 9512 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f); 9513 mPositionX += viewportToContentHorizontalOffset(); 9514 9515 final int line = mLayout.getLineForOffset(offset); 9516 mPositionY = getVerticalLocalPosition(line); 9517 mPositionY += viewportToContentVerticalOffset(); 9518 } 9519 9520 private void updatePosition(int parentPositionX, int parentPositionY) { 9521 int positionX = parentPositionX + mPositionX; 9522 int positionY = parentPositionY + mPositionY; 9523 9524 positionY = clipVertically(positionY); 9525 9526 // Horizontal clipping 9527 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9528 final int width = mContentView.getMeasuredWidth(); 9529 positionX = Math.min(displayMetrics.widthPixels - width, positionX); 9530 positionX = Math.max(0, positionX); 9531 9532 if (isShowing()) { 9533 mPopupWindow.update(positionX, positionY, -1, -1); 9534 } else { 9535 mPopupWindow.showAtLocation(TextView.this, Gravity.NO_GRAVITY, 9536 positionX, positionY); 9537 } 9538 } 9539 9540 public void hide() { 9541 mPopupWindow.dismiss(); 9542 TextView.this.getPositionListener().removeSubscriber(this); 9543 } 9544 9545 @Override 9546 public void updatePosition(int parentPositionX, int parentPositionY, 9547 boolean parentPositionChanged, boolean parentScrolled) { 9548 // Either parentPositionChanged or parentScrolled is true, check if still visible 9549 if (isShowing() && isOffsetVisible(getTextOffset())) { 9550 if (parentScrolled) computeLocalPosition(); 9551 updatePosition(parentPositionX, parentPositionY); 9552 } else { 9553 hide(); 9554 } 9555 } 9556 9557 public boolean isShowing() { 9558 return mPopupWindow.isShowing(); 9559 } 9560 } 9561 9562 private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener { 9563 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE; 9564 private static final int ADD_TO_DICTIONARY = -1; 9565 private static final int DELETE_TEXT = -2; 9566 private SuggestionInfo[] mSuggestionInfos; 9567 private int mNumberOfSuggestions; 9568 private boolean mCursorWasVisibleBeforeSuggestions; 9569 private boolean mIsShowingUp = false; 9570 private SuggestionAdapter mSuggestionsAdapter; 9571 private final Comparator<SuggestionSpan> mSuggestionSpanComparator; 9572 private final HashMap<SuggestionSpan, Integer> mSpansLengths; 9573 9574 private class CustomPopupWindow extends PopupWindow { 9575 public CustomPopupWindow(Context context, int defStyle) { 9576 super(context, null, defStyle); 9577 } 9578 9579 @Override 9580 public void dismiss() { 9581 super.dismiss(); 9582 9583 TextView.this.getPositionListener().removeSubscriber(SuggestionsPopupWindow.this); 9584 9585 // Safe cast since show() checks that mText is an Editable 9586 ((Spannable) mText).removeSpan(mSuggestionRangeSpan); 9587 9588 setCursorVisible(mCursorWasVisibleBeforeSuggestions); 9589 if (hasInsertionController()) { 9590 getInsertionController().show(); 9591 } 9592 } 9593 } 9594 9595 public SuggestionsPopupWindow() { 9596 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 9597 mSuggestionSpanComparator = new SuggestionSpanComparator(); 9598 mSpansLengths = new HashMap<SuggestionSpan, Integer>(); 9599 } 9600 9601 @Override 9602 protected void createPopupWindow() { 9603 mPopupWindow = new CustomPopupWindow(TextView.this.mContext, 9604 com.android.internal.R.attr.textSuggestionsWindowStyle); 9605 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 9606 mPopupWindow.setFocusable(true); 9607 mPopupWindow.setClippingEnabled(false); 9608 } 9609 9610 @Override 9611 protected void initContentView() { 9612 ListView listView = new ListView(TextView.this.getContext()); 9613 mSuggestionsAdapter = new SuggestionAdapter(); 9614 listView.setAdapter(mSuggestionsAdapter); 9615 listView.setOnItemClickListener(this); 9616 mContentView = listView; 9617 9618 // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete 9619 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2]; 9620 for (int i = 0; i < mSuggestionInfos.length; i++) { 9621 mSuggestionInfos[i] = new SuggestionInfo(); 9622 } 9623 } 9624 9625 public boolean isShowingUp() { 9626 return mIsShowingUp; 9627 } 9628 9629 public void onParentLostFocus() { 9630 mIsShowingUp = false; 9631 } 9632 9633 private class SuggestionInfo { 9634 int suggestionStart, suggestionEnd; // range of actual suggestion within text 9635 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 9636 int suggestionIndex; // the index of this suggestion inside suggestionSpan 9637 SpannableStringBuilder text = new SpannableStringBuilder(); 9638 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext, 9639 android.R.style.TextAppearance_SuggestionHighlight); 9640 } 9641 9642 private class SuggestionAdapter extends BaseAdapter { 9643 private LayoutInflater mInflater = (LayoutInflater) TextView.this.mContext. 9644 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 9645 9646 @Override 9647 public int getCount() { 9648 return mNumberOfSuggestions; 9649 } 9650 9651 @Override 9652 public Object getItem(int position) { 9653 return mSuggestionInfos[position]; 9654 } 9655 9656 @Override 9657 public long getItemId(int position) { 9658 return position; 9659 } 9660 9661 @Override 9662 public View getView(int position, View convertView, ViewGroup parent) { 9663 TextView textView = (TextView) convertView; 9664 9665 if (textView == null) { 9666 textView = (TextView) mInflater.inflate(mTextEditSuggestionItemLayout, parent, 9667 false); 9668 } 9669 9670 final SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 9671 textView.setText(suggestionInfo.text); 9672 9673 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) { 9674 textView.setCompoundDrawablesWithIntrinsicBounds( 9675 com.android.internal.R.drawable.ic_suggestions_add, 0, 0, 0); 9676 } else if (suggestionInfo.suggestionIndex == DELETE_TEXT) { 9677 textView.setCompoundDrawablesWithIntrinsicBounds( 9678 com.android.internal.R.drawable.ic_suggestions_delete, 0, 0, 0); 9679 } else { 9680 textView.setCompoundDrawables(null, null, null, null); 9681 } 9682 9683 return textView; 9684 } 9685 } 9686 9687 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> { 9688 public int compare(SuggestionSpan span1, SuggestionSpan span2) { 9689 final int flag1 = span1.getFlags(); 9690 final int flag2 = span2.getFlags(); 9691 if (flag1 != flag2) { 9692 // The order here should match what is used in updateDrawState 9693 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 9694 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 9695 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0; 9696 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0; 9697 if (easy1 && !misspelled1) return -1; 9698 if (easy2 && !misspelled2) return 1; 9699 if (misspelled1) return -1; 9700 if (misspelled2) return 1; 9701 } 9702 9703 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue(); 9704 } 9705 } 9706 9707 /** 9708 * Returns the suggestion spans that cover the current cursor position. The suggestion 9709 * spans are sorted according to the length of text that they are attached to. 9710 */ 9711 private SuggestionSpan[] getSuggestionSpans() { 9712 int pos = TextView.this.getSelectionStart(); 9713 Spannable spannable = (Spannable) TextView.this.mText; 9714 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 9715 9716 mSpansLengths.clear(); 9717 for (SuggestionSpan suggestionSpan : suggestionSpans) { 9718 int start = spannable.getSpanStart(suggestionSpan); 9719 int end = spannable.getSpanEnd(suggestionSpan); 9720 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start)); 9721 } 9722 9723 // The suggestions are sorted according to their types (easy correction first, then 9724 // misspelled) and to the length of the text that they cover (shorter first). 9725 Arrays.sort(suggestionSpans, mSuggestionSpanComparator); 9726 return suggestionSpans; 9727 } 9728 9729 @Override 9730 public void show() { 9731 if (!(mText instanceof Editable)) return; 9732 9733 if (updateSuggestions()) { 9734 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 9735 setCursorVisible(false); 9736 mIsShowingUp = true; 9737 super.show(); 9738 } 9739 } 9740 9741 @Override 9742 protected void measureContent() { 9743 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9744 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec( 9745 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST); 9746 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec( 9747 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST); 9748 9749 int width = 0; 9750 View view = null; 9751 for (int i = 0; i < mNumberOfSuggestions; i++) { 9752 view = mSuggestionsAdapter.getView(i, view, mContentView); 9753 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT; 9754 view.measure(horizontalMeasure, verticalMeasure); 9755 width = Math.max(width, view.getMeasuredWidth()); 9756 } 9757 9758 // Enforce the width based on actual text widths 9759 mContentView.measure( 9760 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), 9761 verticalMeasure); 9762 9763 Drawable popupBackground = mPopupWindow.getBackground(); 9764 if (popupBackground != null) { 9765 if (mTempRect == null) mTempRect = new Rect(); 9766 popupBackground.getPadding(mTempRect); 9767 width += mTempRect.left + mTempRect.right; 9768 } 9769 mPopupWindow.setWidth(width); 9770 } 9771 9772 @Override 9773 protected int getTextOffset() { 9774 return getSelectionStart(); 9775 } 9776 9777 @Override 9778 protected int getVerticalLocalPosition(int line) { 9779 return mLayout.getLineBottom(line); 9780 } 9781 9782 @Override 9783 protected int clipVertically(int positionY) { 9784 final int height = mContentView.getMeasuredHeight(); 9785 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9786 return Math.min(positionY, displayMetrics.heightPixels - height); 9787 } 9788 9789 @Override 9790 public void hide() { 9791 super.hide(); 9792 } 9793 9794 private boolean updateSuggestions() { 9795 Spannable spannable = (Spannable) TextView.this.mText; 9796 SuggestionSpan[] suggestionSpans = getSuggestionSpans(); 9797 9798 final int nbSpans = suggestionSpans.length; 9799 // Suggestions are shown after a delay: the underlying spans may have been removed 9800 if (nbSpans == 0) return false; 9801 9802 mNumberOfSuggestions = 0; 9803 int spanUnionStart = mText.length(); 9804 int spanUnionEnd = 0; 9805 9806 SuggestionSpan misspelledSpan = null; 9807 int underlineColor = 0; 9808 9809 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 9810 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 9811 final int spanStart = spannable.getSpanStart(suggestionSpan); 9812 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 9813 spanUnionStart = Math.min(spanStart, spanUnionStart); 9814 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 9815 9816 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) { 9817 misspelledSpan = suggestionSpan; 9818 } 9819 9820 // The first span dictates the background color of the highlighted text 9821 if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor(); 9822 9823 String[] suggestions = suggestionSpan.getSuggestions(); 9824 int nbSuggestions = suggestions.length; 9825 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 9826 String suggestion = suggestions[suggestionIndex]; 9827 9828 boolean suggestionIsDuplicate = false; 9829 for (int i = 0; i < mNumberOfSuggestions; i++) { 9830 if (mSuggestionInfos[i].text.toString().equals(suggestion)) { 9831 SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan; 9832 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan); 9833 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan); 9834 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) { 9835 suggestionIsDuplicate = true; 9836 break; 9837 } 9838 } 9839 } 9840 9841 if (!suggestionIsDuplicate) { 9842 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 9843 suggestionInfo.suggestionSpan = suggestionSpan; 9844 suggestionInfo.suggestionIndex = suggestionIndex; 9845 suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion); 9846 9847 mNumberOfSuggestions++; 9848 9849 if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) { 9850 // Also end outer for loop 9851 spanIndex = nbSpans; 9852 break; 9853 } 9854 } 9855 } 9856 } 9857 9858 for (int i = 0; i < mNumberOfSuggestions; i++) { 9859 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd); 9860 } 9861 9862 // Add "Add to dictionary" item if there is a span with the misspelled flag 9863 if (misspelledSpan != null) { 9864 final int misspelledStart = spannable.getSpanStart(misspelledSpan); 9865 final int misspelledEnd = spannable.getSpanEnd(misspelledSpan); 9866 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) { 9867 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 9868 suggestionInfo.suggestionSpan = misspelledSpan; 9869 suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY; 9870 suggestionInfo.text.replace(0, suggestionInfo.text.length(), 9871 getContext().getString(com.android.internal.R.string.addToDictionary)); 9872 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 9873 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9874 9875 mNumberOfSuggestions++; 9876 } 9877 } 9878 9879 // Delete item 9880 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 9881 suggestionInfo.suggestionSpan = null; 9882 suggestionInfo.suggestionIndex = DELETE_TEXT; 9883 suggestionInfo.text.replace(0, suggestionInfo.text.length(), 9884 getContext().getString(com.android.internal.R.string.deleteText)); 9885 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 9886 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9887 mNumberOfSuggestions++; 9888 9889 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 9890 if (underlineColor == 0) { 9891 // Fallback on the default highlight color when the first span does not provide one 9892 mSuggestionRangeSpan.setBackgroundColor(mHighlightColor); 9893 } else { 9894 final float BACKGROUND_TRANSPARENCY = 0.4f; 9895 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY); 9896 mSuggestionRangeSpan.setBackgroundColor( 9897 (underlineColor & 0x00FFFFFF) + (newAlpha << 24)); 9898 } 9899 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 9900 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9901 9902 mSuggestionsAdapter.notifyDataSetChanged(); 9903 return true; 9904 } 9905 9906 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart, 9907 int unionEnd) { 9908 final Spannable text = (Spannable) mText; 9909 final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan); 9910 final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan); 9911 9912 // Adjust the start/end of the suggestion span 9913 suggestionInfo.suggestionStart = spanStart - unionStart; 9914 suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart 9915 + suggestionInfo.text.length(); 9916 9917 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 9918 suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9919 9920 // Add the text before and after the span. 9921 final String textAsString = text.toString(); 9922 suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart)); 9923 suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd)); 9924 } 9925 9926 @Override 9927 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 9928 Editable editable = (Editable) mText; 9929 SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 9930 9931 if (suggestionInfo.suggestionIndex == DELETE_TEXT) { 9932 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan); 9933 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan); 9934 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) { 9935 // Do not leave two adjacent spaces after deletion, or one at beginning of text 9936 if (spanUnionEnd < editable.length() && 9937 Character.isSpaceChar(editable.charAt(spanUnionEnd)) && 9938 (spanUnionStart == 0 || 9939 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) { 9940 spanUnionEnd = spanUnionEnd + 1; 9941 } 9942 deleteText_internal(spanUnionStart, spanUnionEnd); 9943 } 9944 hide(); 9945 return; 9946 } 9947 9948 final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan); 9949 final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan); 9950 if (spanStart < 0 || spanEnd <= spanStart) { 9951 // Span has been removed 9952 hide(); 9953 return; 9954 } 9955 final String originalText = mText.toString().substring(spanStart, spanEnd); 9956 9957 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) { 9958 Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT); 9959 intent.putExtra("word", originalText); 9960 intent.putExtra("locale", getTextServicesLocale().toString()); 9961 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 9962 getContext().startActivity(intent); 9963 // There is no way to know if the word was indeed added. Re-check. 9964 // TODO The ExtractEditText should remove the span in the original text instead 9965 editable.removeSpan(suggestionInfo.suggestionSpan); 9966 updateSpellCheckSpans(spanStart, spanEnd, false); 9967 } else { 9968 // SuggestionSpans are removed by replace: save them before 9969 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 9970 SuggestionSpan.class); 9971 final int length = suggestionSpans.length; 9972 int[] suggestionSpansStarts = new int[length]; 9973 int[] suggestionSpansEnds = new int[length]; 9974 int[] suggestionSpansFlags = new int[length]; 9975 for (int i = 0; i < length; i++) { 9976 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 9977 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 9978 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 9979 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 9980 9981 // Remove potential misspelled flags 9982 int suggestionSpanFlags = suggestionSpan.getFlags(); 9983 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) { 9984 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED; 9985 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 9986 suggestionSpan.setFlags(suggestionSpanFlags); 9987 } 9988 } 9989 9990 final int suggestionStart = suggestionInfo.suggestionStart; 9991 final int suggestionEnd = suggestionInfo.suggestionEnd; 9992 final String suggestion = suggestionInfo.text.subSequence( 9993 suggestionStart, suggestionEnd).toString(); 9994 replaceText_internal(spanStart, spanEnd, suggestion); 9995 9996 // Notify source IME of the suggestion pick. Do this before swaping texts. 9997 if (!TextUtils.isEmpty( 9998 suggestionInfo.suggestionSpan.getNotificationTargetClassName())) { 9999 InputMethodManager imm = InputMethodManager.peekInstance(); 10000 if (imm != null) { 10001 imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText, 10002 suggestionInfo.suggestionIndex); 10003 } 10004 } 10005 10006 // Swap text content between actual text and Suggestion span 10007 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 10008 suggestions[suggestionInfo.suggestionIndex] = originalText; 10009 10010 // Restore previous SuggestionSpans 10011 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 10012 for (int i = 0; i < length; i++) { 10013 // Only spans that include the modified region make sense after replacement 10014 // Spans partially included in the replaced region are removed, there is no 10015 // way to assign them a valid range after replacement 10016 if (suggestionSpansStarts[i] <= spanStart && 10017 suggestionSpansEnds[i] >= spanEnd) { 10018 setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i], 10019 suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]); 10020 } 10021 } 10022 10023 // Move cursor at the end of the replaced word 10024 final int newCursorPosition = spanEnd + lengthDifference; 10025 setCursorPosition_internal(newCursorPosition, newCursorPosition); 10026 } 10027 10028 hide(); 10029 } 10030 } 10031 10032 /** 10033 * Removes the suggestion spans. 10034 */ 10035 CharSequence removeSuggestionSpans(CharSequence text) { 10036 if (text instanceof Spanned) { 10037 Spannable spannable; 10038 if (text instanceof Spannable) { 10039 spannable = (Spannable) text; 10040 } else { 10041 spannable = new SpannableString(text); 10042 text = spannable; 10043 } 10044 10045 SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class); 10046 for (int i = 0; i < spans.length; i++) { 10047 spannable.removeSpan(spans[i]); 10048 } 10049 } 10050 return text; 10051 } 10052 10053 void showSuggestions() { 10054 if (mSuggestionsPopupWindow == null) { 10055 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 10056 } 10057 hideControllers(); 10058 mSuggestionsPopupWindow.show(); 10059 } 10060 10061 boolean areSuggestionsShown() { 10062 return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing(); 10063 } 10064 10065 /** 10066 * Return whether or not suggestions are enabled on this TextView. The suggestions are generated 10067 * by the IME or by the spell checker as the user types. This is done by adding 10068 * {@link SuggestionSpan}s to the text. 10069 * 10070 * When suggestions are enabled (default), this list of suggestions will be displayed when the 10071 * user asks for them on these parts of the text. This value depends on the inputType of this 10072 * TextView. 10073 * 10074 * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}. 10075 * 10076 * In addition, the type variation must be one of 10077 * {@link InputType#TYPE_TEXT_VARIATION_NORMAL}, 10078 * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, 10079 * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, 10080 * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or 10081 * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. 10082 * 10083 * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set. 10084 * 10085 * @return true if the suggestions popup window is enabled, based on the inputType. 10086 */ 10087 public boolean isSuggestionsEnabled() { 10088 if ((mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) return false; 10089 if ((mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false; 10090 10091 final int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 10092 return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL || 10093 variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT || 10094 variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE || 10095 variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE || 10096 variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT); 10097 } 10098 10099 /** 10100 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 10101 * selection is initiated in this View. 10102 * 10103 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 10104 * Paste actions, depending on what this View supports. 10105 * 10106 * A custom implementation can add new entries in the default menu in its 10107 * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The 10108 * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and 10109 * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} 10110 * or {@link android.R.id#paste} ids as parameters. 10111 * 10112 * Returning false from 10113 * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent 10114 * the action mode from being started. 10115 * 10116 * Action click events should be handled by the custom implementation of 10117 * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 10118 * 10119 * Note that text selection mode is not started when a TextView receives focus and the 10120 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 10121 * that case, to allow for quick replacement. 10122 */ 10123 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 10124 mCustomSelectionActionModeCallback = actionModeCallback; 10125 } 10126 10127 /** 10128 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 10129 * 10130 * @return The current custom selection callback. 10131 */ 10132 public ActionMode.Callback getCustomSelectionActionModeCallback() { 10133 return mCustomSelectionActionModeCallback; 10134 } 10135 10136 /** 10137 * 10138 * @return true if the selection mode was actually started. 10139 */ 10140 private boolean startSelectionActionMode() { 10141 if (mSelectionActionMode != null) { 10142 // Selection action mode is already started 10143 return false; 10144 } 10145 10146 if (!canSelectText() || !requestFocus()) { 10147 Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled."); 10148 return false; 10149 } 10150 10151 if (!hasSelection()) { 10152 // There may already be a selection on device rotation 10153 if (!selectCurrentWord()) { 10154 // No word found under cursor or text selection not permitted. 10155 return false; 10156 } 10157 } 10158 10159 boolean willExtract = extractedTextModeWillBeStarted(); 10160 10161 // Do not start the action mode when extracted text will show up full screen, which would 10162 // immediately hide the newly created action bar and would be visually distracting. 10163 if (!willExtract) { 10164 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 10165 mSelectionActionMode = startActionMode(actionModeCallback); 10166 } 10167 10168 final boolean selectionStarted = mSelectionActionMode != null || willExtract; 10169 if (selectionStarted && !mTextIsSelectable) { 10170 // Show the IME to be able to replace text, except when selecting non editable text. 10171 final InputMethodManager imm = InputMethodManager.peekInstance(); 10172 if (imm != null) { 10173 imm.showSoftInput(this, 0, null); 10174 } 10175 } 10176 10177 return selectionStarted; 10178 } 10179 10180 private boolean extractedTextModeWillBeStarted() { 10181 if (!(this instanceof ExtractEditText)) { 10182 final InputMethodManager imm = InputMethodManager.peekInstance(); 10183 return imm != null && imm.isFullscreenMode(); 10184 } 10185 return false; 10186 } 10187 10188 /** 10189 * @hide 10190 */ 10191 protected void stopSelectionActionMode() { 10192 if (mSelectionActionMode != null) { 10193 // This will hide the mSelectionModifierCursorController 10194 mSelectionActionMode.finish(); 10195 } 10196 } 10197 10198 /** 10199 * Paste clipboard content between min and max positions. 10200 */ 10201 private void paste(int min, int max) { 10202 ClipboardManager clipboard = 10203 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 10204 ClipData clip = clipboard.getPrimaryClip(); 10205 if (clip != null) { 10206 boolean didFirst = false; 10207 for (int i=0; i<clip.getItemCount(); i++) { 10208 CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); 10209 if (paste != null) { 10210 if (!didFirst) { 10211 long minMax = prepareSpacesAroundPaste(min, max, paste); 10212 min = extractRangeStartFromLong(minMax); 10213 max = extractRangeEndFromLong(minMax); 10214 Selection.setSelection((Spannable) mText, max); 10215 ((Editable) mText).replace(min, max, paste); 10216 didFirst = true; 10217 } else { 10218 ((Editable) mText).insert(getSelectionEnd(), "\n"); 10219 ((Editable) mText).insert(getSelectionEnd(), paste); 10220 } 10221 } 10222 } 10223 stopSelectionActionMode(); 10224 sLastCutOrCopyTime = 0; 10225 } 10226 } 10227 10228 private void setPrimaryClip(ClipData clip) { 10229 ClipboardManager clipboard = (ClipboardManager) getContext(). 10230 getSystemService(Context.CLIPBOARD_SERVICE); 10231 clipboard.setPrimaryClip(clip); 10232 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 10233 } 10234 10235 /** 10236 * An ActionMode Callback class that is used to provide actions while in text selection mode. 10237 * 10238 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 10239 * on which of these this TextView supports. 10240 */ 10241 private class SelectionActionModeCallback implements ActionMode.Callback { 10242 10243 @Override 10244 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 10245 TypedArray styledAttributes = mContext.obtainStyledAttributes( 10246 com.android.internal.R.styleable.SelectionModeDrawables); 10247 10248 boolean allowText = getContext().getResources().getBoolean( 10249 com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon); 10250 10251 mode.setTitle(allowText ? 10252 mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null); 10253 mode.setSubtitle(null); 10254 10255 int selectAllIconId = 0; // No icon by default 10256 if (!allowText) { 10257 // Provide an icon, text will not be displayed on smaller screens. 10258 selectAllIconId = styledAttributes.getResourceId( 10259 R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0); 10260 } 10261 10262 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 10263 setIcon(selectAllIconId). 10264 setAlphabeticShortcut('a'). 10265 setShowAsAction( 10266 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10267 10268 if (canCut()) { 10269 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 10270 setIcon(styledAttributes.getResourceId( 10271 R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)). 10272 setAlphabeticShortcut('x'). 10273 setShowAsAction( 10274 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10275 } 10276 10277 if (canCopy()) { 10278 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 10279 setIcon(styledAttributes.getResourceId( 10280 R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)). 10281 setAlphabeticShortcut('c'). 10282 setShowAsAction( 10283 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10284 } 10285 10286 if (canPaste()) { 10287 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 10288 setIcon(styledAttributes.getResourceId( 10289 R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)). 10290 setAlphabeticShortcut('v'). 10291 setShowAsAction( 10292 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10293 } 10294 10295 styledAttributes.recycle(); 10296 10297 if (mCustomSelectionActionModeCallback != null) { 10298 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 10299 // The custom mode can choose to cancel the action mode 10300 return false; 10301 } 10302 } 10303 10304 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 10305 getSelectionController().show(); 10306 return true; 10307 } else { 10308 return false; 10309 } 10310 } 10311 10312 @Override 10313 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 10314 if (mCustomSelectionActionModeCallback != null) { 10315 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 10316 } 10317 return true; 10318 } 10319 10320 @Override 10321 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 10322 if (mCustomSelectionActionModeCallback != null && 10323 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 10324 return true; 10325 } 10326 return onTextContextMenuItem(item.getItemId()); 10327 } 10328 10329 @Override 10330 public void onDestroyActionMode(ActionMode mode) { 10331 if (mCustomSelectionActionModeCallback != null) { 10332 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 10333 } 10334 Selection.setSelection((Spannable) mText, getSelectionEnd()); 10335 10336 if (mSelectionModifierCursorController != null) { 10337 mSelectionModifierCursorController.hide(); 10338 } 10339 10340 mSelectionActionMode = null; 10341 } 10342 } 10343 10344 private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener { 10345 private static final int POPUP_TEXT_LAYOUT = 10346 com.android.internal.R.layout.text_edit_action_popup_text; 10347 private TextView mPasteTextView; 10348 private TextView mReplaceTextView; 10349 10350 @Override 10351 protected void createPopupWindow() { 10352 mPopupWindow = new PopupWindow(TextView.this.mContext, null, 10353 com.android.internal.R.attr.textSelectHandleWindowStyle); 10354 mPopupWindow.setClippingEnabled(true); 10355 } 10356 10357 @Override 10358 protected void initContentView() { 10359 LinearLayout linearLayout = new LinearLayout(TextView.this.getContext()); 10360 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 10361 mContentView = linearLayout; 10362 mContentView.setBackgroundResource( 10363 com.android.internal.R.drawable.text_edit_paste_window); 10364 10365 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 10366 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 10367 10368 LayoutParams wrapContent = new LayoutParams( 10369 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 10370 10371 mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 10372 mPasteTextView.setLayoutParams(wrapContent); 10373 mContentView.addView(mPasteTextView); 10374 mPasteTextView.setText(com.android.internal.R.string.paste); 10375 mPasteTextView.setOnClickListener(this); 10376 10377 mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 10378 mReplaceTextView.setLayoutParams(wrapContent); 10379 mContentView.addView(mReplaceTextView); 10380 mReplaceTextView.setText(com.android.internal.R.string.replace); 10381 mReplaceTextView.setOnClickListener(this); 10382 } 10383 10384 @Override 10385 public void show() { 10386 boolean canPaste = canPaste(); 10387 boolean canSuggest = isSuggestionsEnabled() && isCursorInsideSuggestionSpan(); 10388 mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE); 10389 mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE); 10390 10391 if (!canPaste && !canSuggest) return; 10392 10393 super.show(); 10394 } 10395 10396 @Override 10397 public void onClick(View view) { 10398 if (view == mPasteTextView && canPaste()) { 10399 onTextContextMenuItem(ID_PASTE); 10400 hide(); 10401 } else if (view == mReplaceTextView) { 10402 final int middle = (getSelectionStart() + getSelectionEnd()) / 2; 10403 stopSelectionActionMode(); 10404 Selection.setSelection((Spannable) mText, middle); 10405 showSuggestions(); 10406 } 10407 } 10408 10409 @Override 10410 protected int getTextOffset() { 10411 return (getSelectionStart() + getSelectionEnd()) / 2; 10412 } 10413 10414 @Override 10415 protected int getVerticalLocalPosition(int line) { 10416 return mLayout.getLineTop(line) - mContentView.getMeasuredHeight(); 10417 } 10418 10419 @Override 10420 protected int clipVertically(int positionY) { 10421 if (positionY < 0) { 10422 final int offset = getTextOffset(); 10423 final int line = mLayout.getLineForOffset(offset); 10424 positionY += mLayout.getLineBottom(line) - mLayout.getLineTop(line); 10425 positionY += mContentView.getMeasuredHeight(); 10426 10427 // Assumes insertion and selection handles share the same height 10428 final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes); 10429 positionY += handle.getIntrinsicHeight(); 10430 } 10431 10432 return positionY; 10433 } 10434 } 10435 10436 private abstract class HandleView extends View implements TextViewPositionListener { 10437 protected Drawable mDrawable; 10438 protected Drawable mDrawableLtr; 10439 protected Drawable mDrawableRtl; 10440 private final PopupWindow mContainer; 10441 // Position with respect to the parent TextView 10442 private int mPositionX, mPositionY; 10443 private boolean mIsDragging; 10444 // Offset from touch position to mPosition 10445 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 10446 protected int mHotspotX; 10447 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 10448 private float mTouchOffsetY; 10449 // Where the touch position should be on the handle to ensure a maximum cursor visibility 10450 private float mIdealVerticalOffset; 10451 // Parent's (TextView) previous position in window 10452 private int mLastParentX, mLastParentY; 10453 // Transient action popup window for Paste and Replace actions 10454 protected ActionPopupWindow mActionPopupWindow; 10455 // Previous text character offset 10456 private int mPreviousOffset = -1; 10457 // Previous text character offset 10458 private boolean mPositionHasChanged = true; 10459 // Used to delay the appearance of the action popup window 10460 private Runnable mActionPopupShower; 10461 10462 public HandleView(Drawable drawableLtr, Drawable drawableRtl) { 10463 super(TextView.this.mContext); 10464 mContainer = new PopupWindow(TextView.this.mContext, null, 10465 com.android.internal.R.attr.textSelectHandleWindowStyle); 10466 mContainer.setSplitTouchEnabled(true); 10467 mContainer.setClippingEnabled(false); 10468 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 10469 mContainer.setContentView(this); 10470 10471 mDrawableLtr = drawableLtr; 10472 mDrawableRtl = drawableRtl; 10473 10474 updateDrawable(); 10475 10476 final int handleHeight = mDrawable.getIntrinsicHeight(); 10477 mTouchOffsetY = -0.3f * handleHeight; 10478 mIdealVerticalOffset = 0.7f * handleHeight; 10479 } 10480 10481 protected void updateDrawable() { 10482 final int offset = getCurrentCursorOffset(); 10483 final boolean isRtlCharAtOffset = mLayout.isRtlCharAt(offset); 10484 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr; 10485 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset); 10486 } 10487 10488 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun); 10489 10490 // Touch-up filter: number of previous positions remembered 10491 private static final int HISTORY_SIZE = 5; 10492 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 10493 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 10494 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 10495 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 10496 private int mPreviousOffsetIndex = 0; 10497 private int mNumberPreviousOffsets = 0; 10498 10499 private void startTouchUpFilter(int offset) { 10500 mNumberPreviousOffsets = 0; 10501 addPositionToTouchUpFilter(offset); 10502 } 10503 10504 private void addPositionToTouchUpFilter(int offset) { 10505 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 10506 mPreviousOffsets[mPreviousOffsetIndex] = offset; 10507 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 10508 mNumberPreviousOffsets++; 10509 } 10510 10511 private void filterOnTouchUp() { 10512 final long now = SystemClock.uptimeMillis(); 10513 int i = 0; 10514 int index = mPreviousOffsetIndex; 10515 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 10516 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 10517 i++; 10518 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 10519 } 10520 10521 if (i > 0 && i < iMax && 10522 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 10523 positionAtCursorOffset(mPreviousOffsets[index], false); 10524 } 10525 } 10526 10527 public boolean offsetHasBeenChanged() { 10528 return mNumberPreviousOffsets > 1; 10529 } 10530 10531 @Override 10532 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 10533 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 10534 } 10535 10536 public void show() { 10537 if (isShowing()) return; 10538 10539 getPositionListener().addSubscriber(this, true /* local position may change */); 10540 10541 // Make sure the offset is always considered new, even when focusing at same position 10542 mPreviousOffset = -1; 10543 positionAtCursorOffset(getCurrentCursorOffset(), false); 10544 10545 hideActionPopupWindow(); 10546 } 10547 10548 protected void dismiss() { 10549 mIsDragging = false; 10550 mContainer.dismiss(); 10551 onDetached(); 10552 } 10553 10554 public void hide() { 10555 dismiss(); 10556 10557 TextView.this.getPositionListener().removeSubscriber(this); 10558 } 10559 10560 void showActionPopupWindow(int delay) { 10561 if (mActionPopupWindow == null) { 10562 mActionPopupWindow = new ActionPopupWindow(); 10563 } 10564 if (mActionPopupShower == null) { 10565 mActionPopupShower = new Runnable() { 10566 public void run() { 10567 mActionPopupWindow.show(); 10568 } 10569 }; 10570 } else { 10571 TextView.this.removeCallbacks(mActionPopupShower); 10572 } 10573 TextView.this.postDelayed(mActionPopupShower, delay); 10574 } 10575 10576 protected void hideActionPopupWindow() { 10577 if (mActionPopupShower != null) { 10578 TextView.this.removeCallbacks(mActionPopupShower); 10579 } 10580 if (mActionPopupWindow != null) { 10581 mActionPopupWindow.hide(); 10582 } 10583 } 10584 10585 public boolean isShowing() { 10586 return mContainer.isShowing(); 10587 } 10588 10589 private boolean isVisible() { 10590 // Always show a dragging handle. 10591 if (mIsDragging) { 10592 return true; 10593 } 10594 10595 if (isInBatchEditMode()) { 10596 return false; 10597 } 10598 10599 return TextView.this.isPositionVisible(mPositionX + mHotspotX, mPositionY); 10600 } 10601 10602 public abstract int getCurrentCursorOffset(); 10603 10604 protected abstract void updateSelection(int offset); 10605 10606 public abstract void updatePosition(float x, float y); 10607 10608 protected void positionAtCursorOffset(int offset, boolean parentScrolled) { 10609 // A HandleView relies on the layout, which may be nulled by external methods 10610 if (mLayout == null) { 10611 // Will update controllers' state, hiding them and stopping selection mode if needed 10612 prepareCursorControllers(); 10613 return; 10614 } 10615 10616 if (offset != mPreviousOffset || parentScrolled) { 10617 updateSelection(offset); 10618 addPositionToTouchUpFilter(offset); 10619 final int line = mLayout.getLineForOffset(offset); 10620 10621 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 10622 mPositionY = mLayout.getLineBottom(line); 10623 10624 // Take TextView's padding and scroll into account. 10625 mPositionX += viewportToContentHorizontalOffset(); 10626 mPositionY += viewportToContentVerticalOffset(); 10627 10628 mPreviousOffset = offset; 10629 mPositionHasChanged = true; 10630 } 10631 } 10632 10633 public void updatePosition(int parentPositionX, int parentPositionY, 10634 boolean parentPositionChanged, boolean parentScrolled) { 10635 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled); 10636 if (parentPositionChanged || mPositionHasChanged) { 10637 if (mIsDragging) { 10638 // Update touchToWindow offset in case of parent scrolling while dragging 10639 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) { 10640 mTouchToWindowOffsetX += parentPositionX - mLastParentX; 10641 mTouchToWindowOffsetY += parentPositionY - mLastParentY; 10642 mLastParentX = parentPositionX; 10643 mLastParentY = parentPositionY; 10644 } 10645 10646 onHandleMoved(); 10647 } 10648 10649 if (isVisible()) { 10650 final int positionX = parentPositionX + mPositionX; 10651 final int positionY = parentPositionY + mPositionY; 10652 if (isShowing()) { 10653 mContainer.update(positionX, positionY, -1, -1); 10654 } else { 10655 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, 10656 positionX, positionY); 10657 } 10658 } else { 10659 if (isShowing()) { 10660 dismiss(); 10661 } 10662 } 10663 10664 mPositionHasChanged = false; 10665 } 10666 } 10667 10668 @Override 10669 protected void onDraw(Canvas c) { 10670 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10671 mDrawable.draw(c); 10672 } 10673 10674 @Override 10675 public boolean onTouchEvent(MotionEvent ev) { 10676 switch (ev.getActionMasked()) { 10677 case MotionEvent.ACTION_DOWN: { 10678 startTouchUpFilter(getCurrentCursorOffset()); 10679 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 10680 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 10681 10682 final PositionListener positionListener = getPositionListener(); 10683 mLastParentX = positionListener.getPositionX(); 10684 mLastParentY = positionListener.getPositionY(); 10685 mIsDragging = true; 10686 break; 10687 } 10688 10689 case MotionEvent.ACTION_MOVE: { 10690 final float rawX = ev.getRawX(); 10691 final float rawY = ev.getRawY(); 10692 10693 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 10694 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 10695 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 10696 float newVerticalOffset; 10697 if (previousVerticalOffset < mIdealVerticalOffset) { 10698 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 10699 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 10700 } else { 10701 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 10702 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 10703 } 10704 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 10705 10706 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 10707 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 10708 10709 updatePosition(newPosX, newPosY); 10710 break; 10711 } 10712 10713 case MotionEvent.ACTION_UP: 10714 filterOnTouchUp(); 10715 mIsDragging = false; 10716 break; 10717 10718 case MotionEvent.ACTION_CANCEL: 10719 mIsDragging = false; 10720 break; 10721 } 10722 return true; 10723 } 10724 10725 public boolean isDragging() { 10726 return mIsDragging; 10727 } 10728 10729 void onHandleMoved() { 10730 hideActionPopupWindow(); 10731 } 10732 10733 public void onDetached() { 10734 hideActionPopupWindow(); 10735 } 10736 } 10737 10738 private class InsertionHandleView extends HandleView { 10739 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000; 10740 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 10741 10742 // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow 10743 private float mDownPositionX, mDownPositionY; 10744 private Runnable mHider; 10745 10746 public InsertionHandleView(Drawable drawable) { 10747 super(drawable, drawable); 10748 } 10749 10750 @Override 10751 public void show() { 10752 super.show(); 10753 10754 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 10755 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 10756 showActionPopupWindow(0); 10757 } 10758 10759 hideAfterDelay(); 10760 } 10761 10762 public void showWithActionPopup() { 10763 show(); 10764 showActionPopupWindow(0); 10765 } 10766 10767 private void hideAfterDelay() { 10768 removeHiderCallback(); 10769 if (mHider == null) { 10770 mHider = new Runnable() { 10771 public void run() { 10772 hide(); 10773 } 10774 }; 10775 } 10776 TextView.this.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT); 10777 } 10778 10779 private void removeHiderCallback() { 10780 if (mHider != null) { 10781 TextView.this.removeCallbacks(mHider); 10782 } 10783 } 10784 10785 @Override 10786 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 10787 return drawable.getIntrinsicWidth() / 2; 10788 } 10789 10790 @Override 10791 public boolean onTouchEvent(MotionEvent ev) { 10792 final boolean result = super.onTouchEvent(ev); 10793 10794 switch (ev.getActionMasked()) { 10795 case MotionEvent.ACTION_DOWN: 10796 mDownPositionX = ev.getRawX(); 10797 mDownPositionY = ev.getRawY(); 10798 break; 10799 10800 case MotionEvent.ACTION_UP: 10801 if (!offsetHasBeenChanged()) { 10802 final float deltaX = mDownPositionX - ev.getRawX(); 10803 final float deltaY = mDownPositionY - ev.getRawY(); 10804 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 10805 10806 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 10807 TextView.this.getContext()); 10808 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 10809 10810 if (distanceSquared < touchSlop * touchSlop) { 10811 if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) { 10812 // Tapping on the handle dismisses the displayed action popup 10813 mActionPopupWindow.hide(); 10814 } else { 10815 showWithActionPopup(); 10816 } 10817 } 10818 } 10819 hideAfterDelay(); 10820 break; 10821 10822 case MotionEvent.ACTION_CANCEL: 10823 hideAfterDelay(); 10824 break; 10825 10826 default: 10827 break; 10828 } 10829 10830 return result; 10831 } 10832 10833 @Override 10834 public int getCurrentCursorOffset() { 10835 return TextView.this.getSelectionStart(); 10836 } 10837 10838 @Override 10839 public void updateSelection(int offset) { 10840 Selection.setSelection((Spannable) mText, offset); 10841 } 10842 10843 @Override 10844 public void updatePosition(float x, float y) { 10845 positionAtCursorOffset(getOffsetForPosition(x, y), false); 10846 } 10847 10848 @Override 10849 void onHandleMoved() { 10850 super.onHandleMoved(); 10851 removeHiderCallback(); 10852 } 10853 10854 @Override 10855 public void onDetached() { 10856 super.onDetached(); 10857 removeHiderCallback(); 10858 } 10859 } 10860 10861 private class SelectionStartHandleView extends HandleView { 10862 10863 public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) { 10864 super(drawableLtr, drawableRtl); 10865 } 10866 10867 @Override 10868 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 10869 if (isRtlRun) { 10870 return drawable.getIntrinsicWidth() / 4; 10871 } else { 10872 return (drawable.getIntrinsicWidth() * 3) / 4; 10873 } 10874 } 10875 10876 @Override 10877 public int getCurrentCursorOffset() { 10878 return TextView.this.getSelectionStart(); 10879 } 10880 10881 @Override 10882 public void updateSelection(int offset) { 10883 Selection.setSelection((Spannable) mText, offset, getSelectionEnd()); 10884 updateDrawable(); 10885 } 10886 10887 @Override 10888 public void updatePosition(float x, float y) { 10889 int offset = getOffsetForPosition(x, y); 10890 10891 // Handles can not cross and selection is at least one character 10892 final int selectionEnd = getSelectionEnd(); 10893 if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1); 10894 10895 positionAtCursorOffset(offset, false); 10896 } 10897 10898 public ActionPopupWindow getActionPopupWindow() { 10899 return mActionPopupWindow; 10900 } 10901 } 10902 10903 private class SelectionEndHandleView extends HandleView { 10904 10905 public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) { 10906 super(drawableLtr, drawableRtl); 10907 } 10908 10909 @Override 10910 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 10911 if (isRtlRun) { 10912 return (drawable.getIntrinsicWidth() * 3) / 4; 10913 } else { 10914 return drawable.getIntrinsicWidth() / 4; 10915 } 10916 } 10917 10918 @Override 10919 public int getCurrentCursorOffset() { 10920 return TextView.this.getSelectionEnd(); 10921 } 10922 10923 @Override 10924 public void updateSelection(int offset) { 10925 Selection.setSelection((Spannable) mText, getSelectionStart(), offset); 10926 updateDrawable(); 10927 } 10928 10929 @Override 10930 public void updatePosition(float x, float y) { 10931 int offset = getOffsetForPosition(x, y); 10932 10933 // Handles can not cross and selection is at least one character 10934 final int selectionStart = getSelectionStart(); 10935 if (offset <= selectionStart) offset = Math.min(selectionStart + 1, mText.length()); 10936 10937 positionAtCursorOffset(offset, false); 10938 } 10939 10940 public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) { 10941 mActionPopupWindow = actionPopupWindow; 10942 } 10943 } 10944 10945 /** 10946 * A CursorController instance can be used to control a cursor in the text. 10947 * It is not used outside of {@link TextView}. 10948 * @hide 10949 */ 10950 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 10951 /** 10952 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 10953 * See also {@link #hide()}. 10954 */ 10955 public void show(); 10956 10957 /** 10958 * Hide the cursor controller from screen. 10959 * See also {@link #show()}. 10960 */ 10961 public void hide(); 10962 10963 /** 10964 * Called when the view is detached from window. Perform house keeping task, such as 10965 * stopping Runnable thread that would otherwise keep a reference on the context, thus 10966 * preventing the activity from being recycled. 10967 */ 10968 public void onDetached(); 10969 } 10970 10971 private class InsertionPointCursorController implements CursorController { 10972 private InsertionHandleView mHandle; 10973 10974 public void show() { 10975 getHandle().show(); 10976 } 10977 10978 public void showWithActionPopup() { 10979 getHandle().showWithActionPopup(); 10980 } 10981 10982 public void hide() { 10983 if (mHandle != null) { 10984 mHandle.hide(); 10985 } 10986 } 10987 10988 public void onTouchModeChanged(boolean isInTouchMode) { 10989 if (!isInTouchMode) { 10990 hide(); 10991 } 10992 } 10993 10994 private InsertionHandleView getHandle() { 10995 if (mSelectHandleCenter == null) { 10996 mSelectHandleCenter = mContext.getResources().getDrawable( 10997 mTextSelectHandleRes); 10998 } 10999 if (mHandle == null) { 11000 mHandle = new InsertionHandleView(mSelectHandleCenter); 11001 } 11002 return mHandle; 11003 } 11004 11005 @Override 11006 public void onDetached() { 11007 final ViewTreeObserver observer = getViewTreeObserver(); 11008 observer.removeOnTouchModeChangeListener(this); 11009 11010 if (mHandle != null) mHandle.onDetached(); 11011 } 11012 } 11013 11014 private class SelectionModifierCursorController implements CursorController { 11015 private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds 11016 // The cursor controller handles, lazily created when shown. 11017 private SelectionStartHandleView mStartHandle; 11018 private SelectionEndHandleView mEndHandle; 11019 // The offsets of that last touch down event. Remembered to start selection there. 11020 private int mMinTouchOffset, mMaxTouchOffset; 11021 11022 // Double tap detection 11023 private long mPreviousTapUpTime = 0; 11024 private float mDownPositionX, mDownPositionY; 11025 private boolean mGestureStayedInTapRegion; 11026 11027 SelectionModifierCursorController() { 11028 resetTouchOffsets(); 11029 } 11030 11031 public void show() { 11032 if (isInBatchEditMode()) { 11033 return; 11034 } 11035 initDrawables(); 11036 initHandles(); 11037 hideInsertionPointCursorController(); 11038 } 11039 11040 private void initDrawables() { 11041 if (mSelectHandleLeft == null) { 11042 mSelectHandleLeft = mContext.getResources().getDrawable( 11043 mTextSelectHandleLeftRes); 11044 } 11045 if (mSelectHandleRight == null) { 11046 mSelectHandleRight = mContext.getResources().getDrawable( 11047 mTextSelectHandleRightRes); 11048 } 11049 } 11050 11051 private void initHandles() { 11052 // Lazy object creation has to be done before updatePosition() is called. 11053 if (mStartHandle == null) { 11054 mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight); 11055 } 11056 if (mEndHandle == null) { 11057 mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft); 11058 } 11059 11060 mStartHandle.show(); 11061 mEndHandle.show(); 11062 11063 // Make sure both left and right handles share the same ActionPopupWindow (so that 11064 // moving any of the handles hides the action popup). 11065 mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION); 11066 mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow()); 11067 11068 hideInsertionPointCursorController(); 11069 } 11070 11071 public void hide() { 11072 if (mStartHandle != null) mStartHandle.hide(); 11073 if (mEndHandle != null) mEndHandle.hide(); 11074 } 11075 11076 public void onTouchEvent(MotionEvent event) { 11077 // This is done even when the View does not have focus, so that long presses can start 11078 // selection and tap can move cursor from this tap position. 11079 switch (event.getActionMasked()) { 11080 case MotionEvent.ACTION_DOWN: 11081 final float x = event.getX(); 11082 final float y = event.getY(); 11083 11084 // Remember finger down position, to be able to start selection from there 11085 mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y); 11086 11087 // Double tap detection 11088 if (mGestureStayedInTapRegion) { 11089 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 11090 if (duration <= ViewConfiguration.getDoubleTapTimeout()) { 11091 final float deltaX = x - mDownPositionX; 11092 final float deltaY = y - mDownPositionY; 11093 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 11094 11095 ViewConfiguration viewConfiguration = ViewConfiguration.get( 11096 TextView.this.getContext()); 11097 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop(); 11098 boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop; 11099 11100 if (stayedInArea && isPositionOnText(x, y)) { 11101 startSelectionActionMode(); 11102 mDiscardNextActionUp = true; 11103 } 11104 } 11105 } 11106 11107 mDownPositionX = x; 11108 mDownPositionY = y; 11109 mGestureStayedInTapRegion = true; 11110 break; 11111 11112 case MotionEvent.ACTION_POINTER_DOWN: 11113 case MotionEvent.ACTION_POINTER_UP: 11114 // Handle multi-point gestures. Keep min and max offset positions. 11115 // Only activated for devices that correctly handle multi-touch. 11116 if (mContext.getPackageManager().hasSystemFeature( 11117 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 11118 updateMinAndMaxOffsets(event); 11119 } 11120 break; 11121 11122 case MotionEvent.ACTION_MOVE: 11123 if (mGestureStayedInTapRegion) { 11124 final float deltaX = event.getX() - mDownPositionX; 11125 final float deltaY = event.getY() - mDownPositionY; 11126 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 11127 11128 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 11129 TextView.this.getContext()); 11130 int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop(); 11131 11132 if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) { 11133 mGestureStayedInTapRegion = false; 11134 } 11135 } 11136 break; 11137 11138 case MotionEvent.ACTION_UP: 11139 mPreviousTapUpTime = SystemClock.uptimeMillis(); 11140 break; 11141 } 11142 } 11143 11144 /** 11145 * @param event 11146 */ 11147 private void updateMinAndMaxOffsets(MotionEvent event) { 11148 int pointerCount = event.getPointerCount(); 11149 for (int index = 0; index < pointerCount; index++) { 11150 int offset = getOffsetForPosition(event.getX(index), event.getY(index)); 11151 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 11152 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 11153 } 11154 } 11155 11156 public int getMinTouchOffset() { 11157 return mMinTouchOffset; 11158 } 11159 11160 public int getMaxTouchOffset() { 11161 return mMaxTouchOffset; 11162 } 11163 11164 public void resetTouchOffsets() { 11165 mMinTouchOffset = mMaxTouchOffset = -1; 11166 } 11167 11168 /** 11169 * @return true iff this controller is currently used to move the selection start. 11170 */ 11171 public boolean isSelectionStartDragged() { 11172 return mStartHandle != null && mStartHandle.isDragging(); 11173 } 11174 11175 public void onTouchModeChanged(boolean isInTouchMode) { 11176 if (!isInTouchMode) { 11177 hide(); 11178 } 11179 } 11180 11181 @Override 11182 public void onDetached() { 11183 final ViewTreeObserver observer = getViewTreeObserver(); 11184 observer.removeOnTouchModeChangeListener(this); 11185 11186 if (mStartHandle != null) mStartHandle.onDetached(); 11187 if (mEndHandle != null) mEndHandle.onDetached(); 11188 } 11189 } 11190 11191 private void hideInsertionPointCursorController() { 11192 // No need to create the controller to hide it. 11193 if (mInsertionPointCursorController != null) { 11194 mInsertionPointCursorController.hide(); 11195 } 11196 } 11197 11198 /** 11199 * Hides the insertion controller and stops text selection mode, hiding the selection controller 11200 */ 11201 private void hideControllers() { 11202 hideCursorControllers(); 11203 hideSpanControllers(); 11204 } 11205 11206 private void hideSpanControllers() { 11207 if (mChangeWatcher != null) { 11208 mChangeWatcher.hideControllers(); 11209 } 11210 } 11211 11212 private void hideCursorControllers() { 11213 if (mSuggestionsPopupWindow != null && !mSuggestionsPopupWindow.isShowingUp()) { 11214 // Should be done before hide insertion point controller since it triggers a show of it 11215 mSuggestionsPopupWindow.hide(); 11216 } 11217 hideInsertionPointCursorController(); 11218 stopSelectionActionMode(); 11219 } 11220 11221 /** 11222 * Get the character offset closest to the specified absolute position. A typical use case is to 11223 * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. 11224 * 11225 * @param x The horizontal absolute position of a point on screen 11226 * @param y The vertical absolute position of a point on screen 11227 * @return the character offset for the character whose position is closest to the specified 11228 * position. Returns -1 if there is no layout. 11229 */ 11230 public int getOffsetForPosition(float x, float y) { 11231 if (getLayout() == null) return -1; 11232 final int line = getLineAtCoordinate(y); 11233 final int offset = getOffsetAtCoordinate(line, x); 11234 return offset; 11235 } 11236 11237 private float convertToLocalHorizontalCoordinate(float x) { 11238 x -= getTotalPaddingLeft(); 11239 // Clamp the position to inside of the view. 11240 x = Math.max(0.0f, x); 11241 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 11242 x += getScrollX(); 11243 return x; 11244 } 11245 11246 private int getLineAtCoordinate(float y) { 11247 y -= getTotalPaddingTop(); 11248 // Clamp the position to inside of the view. 11249 y = Math.max(0.0f, y); 11250 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 11251 y += getScrollY(); 11252 return getLayout().getLineForVertical((int) y); 11253 } 11254 11255 private int getOffsetAtCoordinate(int line, float x) { 11256 x = convertToLocalHorizontalCoordinate(x); 11257 return getLayout().getOffsetForHorizontal(line, x); 11258 } 11259 11260 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 11261 * in the view. Returns false when the position is in the empty space of left/right of text. 11262 */ 11263 private boolean isPositionOnText(float x, float y) { 11264 if (getLayout() == null) return false; 11265 11266 final int line = getLineAtCoordinate(y); 11267 x = convertToLocalHorizontalCoordinate(x); 11268 11269 if (x < getLayout().getLineLeft(line)) return false; 11270 if (x > getLayout().getLineRight(line)) return false; 11271 return true; 11272 } 11273 11274 @Override 11275 public boolean onDragEvent(DragEvent event) { 11276 switch (event.getAction()) { 11277 case DragEvent.ACTION_DRAG_STARTED: 11278 return hasInsertionController(); 11279 11280 case DragEvent.ACTION_DRAG_ENTERED: 11281 TextView.this.requestFocus(); 11282 return true; 11283 11284 case DragEvent.ACTION_DRAG_LOCATION: 11285 final int offset = getOffsetForPosition(event.getX(), event.getY()); 11286 Selection.setSelection((Spannable)mText, offset); 11287 return true; 11288 11289 case DragEvent.ACTION_DROP: 11290 onDrop(event); 11291 return true; 11292 11293 case DragEvent.ACTION_DRAG_ENDED: 11294 case DragEvent.ACTION_DRAG_EXITED: 11295 default: 11296 return true; 11297 } 11298 } 11299 11300 private void onDrop(DragEvent event) { 11301 StringBuilder content = new StringBuilder(""); 11302 ClipData clipData = event.getClipData(); 11303 final int itemCount = clipData.getItemCount(); 11304 for (int i=0; i < itemCount; i++) { 11305 Item item = clipData.getItemAt(i); 11306 content.append(item.coerceToText(TextView.this.mContext)); 11307 } 11308 11309 final int offset = getOffsetForPosition(event.getX(), event.getY()); 11310 11311 Object localState = event.getLocalState(); 11312 DragLocalState dragLocalState = null; 11313 if (localState instanceof DragLocalState) { 11314 dragLocalState = (DragLocalState) localState; 11315 } 11316 boolean dragDropIntoItself = dragLocalState != null && 11317 dragLocalState.sourceTextView == this; 11318 11319 if (dragDropIntoItself) { 11320 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 11321 // A drop inside the original selection discards the drop. 11322 return; 11323 } 11324 } 11325 11326 final int originalLength = mText.length(); 11327 long minMax = prepareSpacesAroundPaste(offset, offset, content); 11328 int min = extractRangeStartFromLong(minMax); 11329 int max = extractRangeEndFromLong(minMax); 11330 11331 Selection.setSelection((Spannable) mText, max); 11332 replaceText_internal(min, max, content); 11333 11334 if (dragDropIntoItself) { 11335 int dragSourceStart = dragLocalState.start; 11336 int dragSourceEnd = dragLocalState.end; 11337 if (max <= dragSourceStart) { 11338 // Inserting text before selection has shifted positions 11339 final int shift = mText.length() - originalLength; 11340 dragSourceStart += shift; 11341 dragSourceEnd += shift; 11342 } 11343 11344 // Delete original selection 11345 deleteText_internal(dragSourceStart, dragSourceEnd); 11346 11347 // Make sure we do not leave two adjacent spaces. 11348 if ((dragSourceStart == 0 || 11349 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 11350 (dragSourceStart == mText.length() || 11351 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 11352 final int pos = dragSourceStart == mText.length() ? 11353 dragSourceStart - 1 : dragSourceStart; 11354 deleteText_internal(pos, pos + 1); 11355 } 11356 } 11357 } 11358 11359 /** 11360 * @return True if this view supports insertion handles. 11361 */ 11362 boolean hasInsertionController() { 11363 return mInsertionControllerEnabled; 11364 } 11365 11366 /** 11367 * @return True if this view supports selection handles. 11368 */ 11369 boolean hasSelectionController() { 11370 return mSelectionControllerEnabled; 11371 } 11372 11373 InsertionPointCursorController getInsertionController() { 11374 if (!mInsertionControllerEnabled) { 11375 return null; 11376 } 11377 11378 if (mInsertionPointCursorController == null) { 11379 mInsertionPointCursorController = new InsertionPointCursorController(); 11380 11381 final ViewTreeObserver observer = getViewTreeObserver(); 11382 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 11383 } 11384 11385 return mInsertionPointCursorController; 11386 } 11387 11388 SelectionModifierCursorController getSelectionController() { 11389 if (!mSelectionControllerEnabled) { 11390 return null; 11391 } 11392 11393 if (mSelectionModifierCursorController == null) { 11394 mSelectionModifierCursorController = new SelectionModifierCursorController(); 11395 11396 final ViewTreeObserver observer = getViewTreeObserver(); 11397 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 11398 } 11399 11400 return mSelectionModifierCursorController; 11401 } 11402 11403 boolean isInBatchEditMode() { 11404 final InputMethodState ims = mInputMethodState; 11405 if (ims != null) { 11406 return ims.mBatchEditNesting > 0; 11407 } 11408 return mInBatchEditControllers; 11409 } 11410 11411 @Override 11412 public void onResolveTextDirection() { 11413 if (hasPasswordTransformationMethod()) { 11414 mTextDir = TextDirectionHeuristics.LOCALE; 11415 return; 11416 } 11417 11418 // Always need to resolve layout direction first 11419 final boolean defaultIsRtl = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 11420 11421 // Now, we can select the heuristic 11422 int textDir = getResolvedTextDirection(); 11423 switch (textDir) { 11424 default: 11425 case TEXT_DIRECTION_FIRST_STRONG: 11426 mTextDir = (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL : 11427 TextDirectionHeuristics.FIRSTSTRONG_LTR); 11428 break; 11429 case TEXT_DIRECTION_ANY_RTL: 11430 mTextDir = TextDirectionHeuristics.ANYRTL_LTR; 11431 break; 11432 case TEXT_DIRECTION_LTR: 11433 mTextDir = TextDirectionHeuristics.LTR; 11434 break; 11435 case TEXT_DIRECTION_RTL: 11436 mTextDir = TextDirectionHeuristics.RTL; 11437 break; 11438 case TEXT_DIRECTION_LOCALE: 11439 mTextDir = TextDirectionHeuristics.LOCALE; 11440 break; 11441 } 11442 } 11443 11444 /** 11445 * Subclasses will need to override this method to implement their own way of resolving 11446 * drawables depending on the layout direction. 11447 * 11448 * A call to the super method will be required from the subclasses implementation. 11449 */ 11450 protected void resolveDrawables() { 11451 // No need to resolve twice 11452 if (mResolvedDrawables) { 11453 return; 11454 } 11455 // No drawable to resolve 11456 if (mDrawables == null) { 11457 return; 11458 } 11459 // No relative drawable to resolve 11460 if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) { 11461 mResolvedDrawables = true; 11462 return; 11463 } 11464 11465 Drawables dr = mDrawables; 11466 switch(getResolvedLayoutDirection()) { 11467 case LAYOUT_DIRECTION_RTL: 11468 if (dr.mDrawableStart != null) { 11469 dr.mDrawableRight = dr.mDrawableStart; 11470 11471 dr.mDrawableSizeRight = dr.mDrawableSizeStart; 11472 dr.mDrawableHeightRight = dr.mDrawableHeightStart; 11473 } 11474 if (dr.mDrawableEnd != null) { 11475 dr.mDrawableLeft = dr.mDrawableEnd; 11476 11477 dr.mDrawableSizeLeft = dr.mDrawableSizeEnd; 11478 dr.mDrawableHeightLeft = dr.mDrawableHeightEnd; 11479 } 11480 break; 11481 11482 case LAYOUT_DIRECTION_LTR: 11483 default: 11484 if (dr.mDrawableStart != null) { 11485 dr.mDrawableLeft = dr.mDrawableStart; 11486 11487 dr.mDrawableSizeLeft = dr.mDrawableSizeStart; 11488 dr.mDrawableHeightLeft = dr.mDrawableHeightStart; 11489 } 11490 if (dr.mDrawableEnd != null) { 11491 dr.mDrawableRight = dr.mDrawableEnd; 11492 11493 dr.mDrawableSizeRight = dr.mDrawableSizeEnd; 11494 dr.mDrawableHeightRight = dr.mDrawableHeightEnd; 11495 } 11496 break; 11497 } 11498 mResolvedDrawables = true; 11499 } 11500 11501 protected void resetResolvedDrawables() { 11502 mResolvedDrawables = false; 11503 } 11504 11505 /** 11506 * @hide 11507 */ 11508 protected void viewClicked(InputMethodManager imm) { 11509 if (imm != null) { 11510 imm.viewClicked(this); 11511 } 11512 } 11513 11514 /** 11515 * Deletes the range of text [start, end[. 11516 * @hide 11517 */ 11518 protected void deleteText_internal(int start, int end) { 11519 ((Editable) mText).delete(start, end); 11520 } 11521 11522 /** 11523 * Replaces the range of text [start, end[ by replacement text 11524 * @hide 11525 */ 11526 protected void replaceText_internal(int start, int end, CharSequence text) { 11527 ((Editable) mText).replace(start, end, text); 11528 } 11529 11530 /** 11531 * Sets a span on the specified range of text 11532 * @hide 11533 */ 11534 protected void setSpan_internal(Object span, int start, int end, int flags) { 11535 ((Editable) mText).setSpan(span, start, end, flags); 11536 } 11537 11538 /** 11539 * Moves the cursor to the specified offset position in text 11540 * @hide 11541 */ 11542 protected void setCursorPosition_internal(int start, int end) { 11543 Selection.setSelection(((Editable) mText), start, end); 11544 } 11545 11546 @ViewDebug.ExportedProperty(category = "text") 11547 private CharSequence mText; 11548 private CharSequence mTransformed; 11549 private BufferType mBufferType = BufferType.NORMAL; 11550 11551 private int mInputType = EditorInfo.TYPE_NULL; 11552 private CharSequence mHint; 11553 private Layout mHintLayout; 11554 11555 private KeyListener mInput; 11556 11557 private MovementMethod mMovement; 11558 private TransformationMethod mTransformation; 11559 private boolean mAllowTransformationLengthChange; 11560 private ChangeWatcher mChangeWatcher; 11561 11562 private ArrayList<TextWatcher> mListeners = null; 11563 11564 // display attributes 11565 private final TextPaint mTextPaint; 11566 private boolean mUserSetTextScaleX; 11567 private final Paint mHighlightPaint; 11568 private int mHighlightColor = 0x6633B5E5; 11569 private Layout mLayout; 11570 11571 private long mShowCursor; 11572 private Blink mBlink; 11573 private boolean mCursorVisible = true; 11574 11575 // Cursor Controllers. 11576 private InsertionPointCursorController mInsertionPointCursorController; 11577 private SelectionModifierCursorController mSelectionModifierCursorController; 11578 private ActionMode mSelectionActionMode; 11579 private boolean mInsertionControllerEnabled; 11580 private boolean mSelectionControllerEnabled; 11581 private boolean mInBatchEditControllers; 11582 11583 private boolean mSelectAllOnFocus = false; 11584 11585 private int mGravity = Gravity.TOP | Gravity.START; 11586 private boolean mHorizontallyScrolling; 11587 11588 private int mAutoLinkMask; 11589 private boolean mLinksClickable = true; 11590 11591 private float mSpacingMult = 1.0f; 11592 private float mSpacingAdd = 0.0f; 11593 private boolean mTextIsSelectable = false; 11594 11595 private static final int LINES = 1; 11596 private static final int EMS = LINES; 11597 private static final int PIXELS = 2; 11598 11599 private int mMaximum = Integer.MAX_VALUE; 11600 private int mMaxMode = LINES; 11601 private int mMinimum = 0; 11602 private int mMinMode = LINES; 11603 11604 private int mOldMaximum = mMaximum; 11605 private int mOldMaxMode = mMaxMode; 11606 11607 private int mMaxWidth = Integer.MAX_VALUE; 11608 private int mMaxWidthMode = PIXELS; 11609 private int mMinWidth = 0; 11610 private int mMinWidthMode = PIXELS; 11611 11612 private boolean mSingleLine; 11613 private int mDesiredHeightAtMeasure = -1; 11614 private boolean mIncludePad = true; 11615 11616 // tmp primitives, so we don't alloc them on each draw 11617 private Path mHighlightPath; 11618 private boolean mHighlightPathBogus = true; 11619 private static final RectF sTempRect = new RectF(); 11620 private static final float[] sTmpPosition = new float[2]; 11621 11622 // XXX should be much larger 11623 private static final int VERY_WIDE = 1024*1024; 11624 11625 private static final int BLINK = 500; 11626 11627 private static final int ANIMATED_SCROLL_GAP = 250; 11628 private long mLastScroll; 11629 private Scroller mScroller = null; 11630 11631 private BoringLayout.Metrics mBoring; 11632 private BoringLayout.Metrics mHintBoring; 11633 11634 private BoringLayout mSavedLayout, mSavedHintLayout; 11635 11636 private TextDirectionHeuristic mTextDir = null; 11637 11638 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 11639 private InputFilter[] mFilters = NO_FILTERS; 11640 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 11641 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 11642 // System wide time for last cut or copy action. 11643 private static long sLastCutOrCopyTime; 11644 // Used to highlight a word when it is corrected by the IME 11645 private CorrectionHighlighter mCorrectionHighlighter; 11646 // New state used to change background based on whether this TextView is multiline. 11647 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 11648} 11649