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