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