TextView.java revision 6d3d5057b445069e73fd06adbc11fa412e7c48c3
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 Handler h = getHandler(); 3811 if (h != null) { 3812 long eventTime = SystemClock.uptimeMillis(); 3813 h.sendMessage(h.obtainMessage(ViewRootImpl.DISPATCH_KEY_FROM_IME, 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 h.sendMessage(h.obtainMessage(ViewRootImpl.DISPATCH_KEY_FROM_IME, 3820 new KeyEvent(SystemClock.uptimeMillis(), eventTime, 3821 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 3822 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3823 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3824 | KeyEvent.FLAG_EDITOR_ACTION))); 3825 } 3826 } 3827 3828 /** 3829 * Set the private content type of the text, which is the 3830 * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} 3831 * field that will be filled in when creating an input connection. 3832 * 3833 * @see #getPrivateImeOptions() 3834 * @see EditorInfo#privateImeOptions 3835 * @attr ref android.R.styleable#TextView_privateImeOptions 3836 */ 3837 public void setPrivateImeOptions(String type) { 3838 if (mInputContentType == null) mInputContentType = new InputContentType(); 3839 mInputContentType.privateImeOptions = type; 3840 } 3841 3842 /** 3843 * Get the private type of the content. 3844 * 3845 * @see #setPrivateImeOptions(String) 3846 * @see EditorInfo#privateImeOptions 3847 */ 3848 public String getPrivateImeOptions() { 3849 return mInputContentType != null 3850 ? mInputContentType.privateImeOptions : null; 3851 } 3852 3853 /** 3854 * Set the extra input data of the text, which is the 3855 * {@link EditorInfo#extras TextBoxAttribute.extras} 3856 * Bundle that will be filled in when creating an input connection. The 3857 * given integer is the resource ID of an XML resource holding an 3858 * {@link android.R.styleable#InputExtras <input-extras>} XML tree. 3859 * 3860 * @see #getInputExtras(boolean) 3861 * @see EditorInfo#extras 3862 * @attr ref android.R.styleable#TextView_editorExtras 3863 */ 3864 public void setInputExtras(int xmlResId) 3865 throws XmlPullParserException, IOException { 3866 XmlResourceParser parser = getResources().getXml(xmlResId); 3867 if (mInputContentType == null) mInputContentType = new InputContentType(); 3868 mInputContentType.extras = new Bundle(); 3869 getResources().parseBundleExtras(parser, mInputContentType.extras); 3870 } 3871 3872 /** 3873 * Retrieve the input extras currently associated with the text view, which 3874 * can be viewed as well as modified. 3875 * 3876 * @param create If true, the extras will be created if they don't already 3877 * exist. Otherwise, null will be returned if none have been created. 3878 * @see #setInputExtras(int) 3879 * @see EditorInfo#extras 3880 * @attr ref android.R.styleable#TextView_editorExtras 3881 */ 3882 public Bundle getInputExtras(boolean create) { 3883 if (mInputContentType == null) { 3884 if (!create) return null; 3885 mInputContentType = new InputContentType(); 3886 } 3887 if (mInputContentType.extras == null) { 3888 if (!create) return null; 3889 mInputContentType.extras = new Bundle(); 3890 } 3891 return mInputContentType.extras; 3892 } 3893 3894 /** 3895 * Returns the error message that was set to be displayed with 3896 * {@link #setError}, or <code>null</code> if no error was set 3897 * or if it the error was cleared by the widget after user input. 3898 */ 3899 public CharSequence getError() { 3900 return mError; 3901 } 3902 3903 /** 3904 * Sets the right-hand compound drawable of the TextView to the "error" 3905 * icon and sets an error message that will be displayed in a popup when 3906 * the TextView has focus. The icon and error message will be reset to 3907 * null when any key events cause changes to the TextView's text. If the 3908 * <code>error</code> is <code>null</code>, the error message and icon 3909 * will be cleared. 3910 */ 3911 @android.view.RemotableViewMethod 3912 public void setError(CharSequence error) { 3913 if (error == null) { 3914 setError(null, null); 3915 } else { 3916 Drawable dr = getContext().getResources(). 3917 getDrawable(com.android.internal.R.drawable.indicator_input_error); 3918 3919 dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); 3920 setError(error, dr); 3921 } 3922 } 3923 3924 /** 3925 * Sets the right-hand compound drawable of the TextView to the specified 3926 * icon and sets an error message that will be displayed in a popup when 3927 * the TextView has focus. The icon and error message will be reset to 3928 * null when any key events cause changes to the TextView's text. The 3929 * drawable must already have had {@link Drawable#setBounds} set on it. 3930 * If the <code>error</code> is <code>null</code>, the error message will 3931 * be cleared (and you should provide a <code>null</code> icon as well). 3932 */ 3933 public void setError(CharSequence error, Drawable icon) { 3934 error = TextUtils.stringOrSpannedString(error); 3935 3936 mError = error; 3937 mErrorWasChanged = true; 3938 final Drawables dr = mDrawables; 3939 if (dr != null) { 3940 switch (getResolvedLayoutDirection()) { 3941 default: 3942 case LAYOUT_DIRECTION_LTR: 3943 setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon, 3944 dr.mDrawableBottom); 3945 break; 3946 case LAYOUT_DIRECTION_RTL: 3947 setCompoundDrawables(icon, dr.mDrawableTop, dr.mDrawableRight, 3948 dr.mDrawableBottom); 3949 break; 3950 } 3951 } else { 3952 setCompoundDrawables(null, null, icon, null); 3953 } 3954 3955 if (error == null) { 3956 if (mPopup != null) { 3957 if (mPopup.isShowing()) { 3958 mPopup.dismiss(); 3959 } 3960 3961 mPopup = null; 3962 } 3963 } else { 3964 if (isFocused()) { 3965 showError(); 3966 } 3967 } 3968 } 3969 3970 private void showError() { 3971 if (getWindowToken() == null) { 3972 mShowErrorAfterAttach = true; 3973 return; 3974 } 3975 3976 if (mPopup == null) { 3977 LayoutInflater inflater = LayoutInflater.from(getContext()); 3978 final TextView err = (TextView) inflater.inflate( 3979 com.android.internal.R.layout.textview_hint, null); 3980 3981 final float scale = getResources().getDisplayMetrics().density; 3982 mPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f)); 3983 mPopup.setFocusable(false); 3984 // The user is entering text, so the input method is needed. We 3985 // don't want the popup to be displayed on top of it. 3986 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 3987 } 3988 3989 TextView tv = (TextView) mPopup.getContentView(); 3990 chooseSize(mPopup, mError, tv); 3991 tv.setText(mError); 3992 3993 mPopup.showAsDropDown(this, getErrorX(), getErrorY()); 3994 mPopup.fixDirection(mPopup.isAboveAnchor()); 3995 } 3996 3997 private static class ErrorPopup extends PopupWindow { 3998 private boolean mAbove = false; 3999 private final TextView mView; 4000 private int mPopupInlineErrorBackgroundId = 0; 4001 private int mPopupInlineErrorAboveBackgroundId = 0; 4002 4003 ErrorPopup(TextView v, int width, int height) { 4004 super(v, width, height); 4005 mView = v; 4006 // Make sure the TextView has a background set as it will be used the first time it is 4007 // shown and positionned. Initialized with below background, which should have 4008 // dimensions identical to the above version for this to work (and is more likely). 4009 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 4010 com.android.internal.R.styleable.Theme_errorMessageBackground); 4011 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 4012 } 4013 4014 void fixDirection(boolean above) { 4015 mAbove = above; 4016 4017 if (above) { 4018 mPopupInlineErrorAboveBackgroundId = 4019 getResourceId(mPopupInlineErrorAboveBackgroundId, 4020 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 4021 } else { 4022 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 4023 com.android.internal.R.styleable.Theme_errorMessageBackground); 4024 } 4025 4026 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 4027 mPopupInlineErrorBackgroundId); 4028 } 4029 4030 private int getResourceId(int currentId, int index) { 4031 if (currentId == 0) { 4032 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 4033 R.styleable.Theme); 4034 currentId = styledAttributes.getResourceId(index, 0); 4035 styledAttributes.recycle(); 4036 } 4037 return currentId; 4038 } 4039 4040 @Override 4041 public void update(int x, int y, int w, int h, boolean force) { 4042 super.update(x, y, w, h, force); 4043 4044 boolean above = isAboveAnchor(); 4045 if (above != mAbove) { 4046 fixDirection(above); 4047 } 4048 } 4049 } 4050 4051 /** 4052 * Returns the Y offset to make the pointy top of the error point 4053 * at the middle of the error icon. 4054 */ 4055 private int getErrorX() { 4056 /* 4057 * The "25" is the distance between the point and the right edge 4058 * of the background 4059 */ 4060 final float scale = getResources().getDisplayMetrics().density; 4061 4062 final Drawables dr = mDrawables; 4063 return getWidth() - mPopup.getWidth() - getPaddingRight() - 4064 (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f); 4065 } 4066 4067 /** 4068 * Returns the Y offset to make the pointy top of the error point 4069 * at the bottom of the error icon. 4070 */ 4071 private int getErrorY() { 4072 /* 4073 * Compound, not extended, because the icon is not clipped 4074 * if the text height is smaller. 4075 */ 4076 final int compoundPaddingTop = getCompoundPaddingTop(); 4077 int vspace = mBottom - mTop - getCompoundPaddingBottom() - compoundPaddingTop; 4078 4079 final Drawables dr = mDrawables; 4080 int icontop = compoundPaddingTop + 4081 (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2; 4082 4083 /* 4084 * The "2" is the distance between the point and the top edge 4085 * of the background. 4086 */ 4087 final float scale = getResources().getDisplayMetrics().density; 4088 return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - getHeight() - 4089 (int) (2 * scale + 0.5f); 4090 } 4091 4092 private void hideError() { 4093 if (mPopup != null) { 4094 if (mPopup.isShowing()) { 4095 mPopup.dismiss(); 4096 } 4097 } 4098 4099 mShowErrorAfterAttach = false; 4100 } 4101 4102 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { 4103 int wid = tv.getPaddingLeft() + tv.getPaddingRight(); 4104 int ht = tv.getPaddingTop() + tv.getPaddingBottom(); 4105 4106 int defaultWidthInPixels = getResources().getDimensionPixelSize( 4107 com.android.internal.R.dimen.textview_error_popup_default_width); 4108 Layout l = new StaticLayout(text, tv.getPaint(), defaultWidthInPixels, 4109 Layout.Alignment.ALIGN_NORMAL, 1, 0, true); 4110 float max = 0; 4111 for (int i = 0; i < l.getLineCount(); i++) { 4112 max = Math.max(max, l.getLineWidth(i)); 4113 } 4114 4115 /* 4116 * Now set the popup size to be big enough for the text plus the border capped 4117 * to DEFAULT_MAX_POPUP_WIDTH 4118 */ 4119 pop.setWidth(wid + (int) Math.ceil(max)); 4120 pop.setHeight(ht + l.getHeight()); 4121 } 4122 4123 4124 @Override 4125 protected boolean setFrame(int l, int t, int r, int b) { 4126 boolean result = super.setFrame(l, t, r, b); 4127 4128 if (mPopup != null) { 4129 TextView tv = (TextView) mPopup.getContentView(); 4130 chooseSize(mPopup, mError, tv); 4131 mPopup.update(this, getErrorX(), getErrorY(), 4132 mPopup.getWidth(), mPopup.getHeight()); 4133 } 4134 4135 restartMarqueeIfNeeded(); 4136 4137 return result; 4138 } 4139 4140 private void restartMarqueeIfNeeded() { 4141 if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 4142 mRestartMarquee = false; 4143 startMarquee(); 4144 } 4145 } 4146 4147 /** 4148 * Sets the list of input filters that will be used if the buffer is 4149 * Editable. Has no effect otherwise. 4150 * 4151 * @attr ref android.R.styleable#TextView_maxLength 4152 */ 4153 public void setFilters(InputFilter[] filters) { 4154 if (filters == null) { 4155 throw new IllegalArgumentException(); 4156 } 4157 4158 mFilters = filters; 4159 4160 if (mText instanceof Editable) { 4161 setFilters((Editable) mText, filters); 4162 } 4163 } 4164 4165 /** 4166 * Sets the list of input filters on the specified Editable, 4167 * and includes mInput in the list if it is an InputFilter. 4168 */ 4169 private void setFilters(Editable e, InputFilter[] filters) { 4170 if (mInput instanceof InputFilter) { 4171 InputFilter[] nf = new InputFilter[filters.length + 1]; 4172 4173 System.arraycopy(filters, 0, nf, 0, filters.length); 4174 nf[filters.length] = (InputFilter) mInput; 4175 4176 e.setFilters(nf); 4177 } else { 4178 e.setFilters(filters); 4179 } 4180 } 4181 4182 /** 4183 * Returns the current list of input filters. 4184 */ 4185 public InputFilter[] getFilters() { 4186 return mFilters; 4187 } 4188 4189 ///////////////////////////////////////////////////////////////////////// 4190 4191 private int getVerticalOffset(boolean forceNormal) { 4192 int voffset = 0; 4193 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 4194 4195 Layout l = mLayout; 4196 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 4197 l = mHintLayout; 4198 } 4199 4200 if (gravity != Gravity.TOP) { 4201 int boxht; 4202 4203 if (l == mHintLayout) { 4204 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 4205 getCompoundPaddingBottom(); 4206 } else { 4207 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 4208 getExtendedPaddingBottom(); 4209 } 4210 int textht = l.getHeight(); 4211 4212 if (textht < boxht) { 4213 if (gravity == Gravity.BOTTOM) 4214 voffset = boxht - textht; 4215 else // (gravity == Gravity.CENTER_VERTICAL) 4216 voffset = (boxht - textht) >> 1; 4217 } 4218 } 4219 return voffset; 4220 } 4221 4222 private int getBottomVerticalOffset(boolean forceNormal) { 4223 int voffset = 0; 4224 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 4225 4226 Layout l = mLayout; 4227 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 4228 l = mHintLayout; 4229 } 4230 4231 if (gravity != Gravity.BOTTOM) { 4232 int boxht; 4233 4234 if (l == mHintLayout) { 4235 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 4236 getCompoundPaddingBottom(); 4237 } else { 4238 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 4239 getExtendedPaddingBottom(); 4240 } 4241 int textht = l.getHeight(); 4242 4243 if (textht < boxht) { 4244 if (gravity == Gravity.TOP) 4245 voffset = boxht - textht; 4246 else // (gravity == Gravity.CENTER_VERTICAL) 4247 voffset = (boxht - textht) >> 1; 4248 } 4249 } 4250 return voffset; 4251 } 4252 4253 private void invalidateCursorPath() { 4254 if (mHighlightPathBogus) { 4255 invalidateCursor(); 4256 } else { 4257 final int horizontalPadding = getCompoundPaddingLeft(); 4258 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 4259 4260 if (mCursorCount == 0) { 4261 synchronized (sTempRect) { 4262 /* 4263 * The reason for this concern about the thickness of the 4264 * cursor and doing the floor/ceil on the coordinates is that 4265 * some EditTexts (notably textfields in the Browser) have 4266 * anti-aliased text where not all the characters are 4267 * necessarily at integer-multiple locations. This should 4268 * make sure the entire cursor gets invalidated instead of 4269 * sometimes missing half a pixel. 4270 */ 4271 float thick = FloatMath.ceil(mTextPaint.getStrokeWidth()); 4272 if (thick < 1.0f) { 4273 thick = 1.0f; 4274 } 4275 4276 thick /= 2.0f; 4277 4278 mHighlightPath.computeBounds(sTempRect, false); 4279 4280 invalidate((int) FloatMath.floor(horizontalPadding + sTempRect.left - thick), 4281 (int) FloatMath.floor(verticalPadding + sTempRect.top - thick), 4282 (int) FloatMath.ceil(horizontalPadding + sTempRect.right + thick), 4283 (int) FloatMath.ceil(verticalPadding + sTempRect.bottom + thick)); 4284 } 4285 } else { 4286 for (int i = 0; i < mCursorCount; i++) { 4287 Rect bounds = mCursorDrawable[i].getBounds(); 4288 invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding, 4289 bounds.right + horizontalPadding, bounds.bottom + verticalPadding); 4290 } 4291 } 4292 } 4293 } 4294 4295 private void invalidateCursor() { 4296 int where = getSelectionEnd(); 4297 4298 invalidateCursor(where, where, where); 4299 } 4300 4301 private void invalidateCursor(int a, int b, int c) { 4302 if (a >= 0 || b >= 0 || c >= 0) { 4303 int start = Math.min(Math.min(a, b), c); 4304 int end = Math.max(Math.max(a, b), c); 4305 invalidateRegion(start, end, true /* Also invalidates blinking cursor */); 4306 } 4307 } 4308 4309 /** 4310 * Invalidates the region of text enclosed between the start and end text offsets. 4311 * 4312 * @hide 4313 */ 4314 void invalidateRegion(int start, int end, boolean invalidateCursor) { 4315 if (mLayout == null) { 4316 invalidate(); 4317 } else { 4318 int lineStart = mLayout.getLineForOffset(start); 4319 int top = mLayout.getLineTop(lineStart); 4320 4321 // This is ridiculous, but the descent from the line above 4322 // can hang down into the line we really want to redraw, 4323 // so we have to invalidate part of the line above to make 4324 // sure everything that needs to be redrawn really is. 4325 // (But not the whole line above, because that would cause 4326 // the same problem with the descenders on the line above it!) 4327 if (lineStart > 0) { 4328 top -= mLayout.getLineDescent(lineStart - 1); 4329 } 4330 4331 int lineEnd; 4332 4333 if (start == end) 4334 lineEnd = lineStart; 4335 else 4336 lineEnd = mLayout.getLineForOffset(end); 4337 4338 int bottom = mLayout.getLineBottom(lineEnd); 4339 4340 if (invalidateCursor) { 4341 for (int i = 0; i < mCursorCount; i++) { 4342 Rect bounds = mCursorDrawable[i].getBounds(); 4343 top = Math.min(top, bounds.top); 4344 bottom = Math.max(bottom, bounds.bottom); 4345 } 4346 } 4347 4348 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4349 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 4350 4351 int left, right; 4352 if (lineStart == lineEnd && !invalidateCursor) { 4353 left = (int) mLayout.getPrimaryHorizontal(start); 4354 right = (int) (mLayout.getPrimaryHorizontal(end) + 1.0); 4355 left += compoundPaddingLeft; 4356 right += compoundPaddingLeft; 4357 } else { 4358 // Rectangle bounding box when the region spans several lines 4359 left = compoundPaddingLeft; 4360 right = getWidth() - getCompoundPaddingRight(); 4361 } 4362 4363 invalidate(mScrollX + left, verticalPadding + top, 4364 mScrollX + right, verticalPadding + bottom); 4365 } 4366 } 4367 4368 private void registerForPreDraw() { 4369 if (!mPreDrawRegistered) { 4370 getViewTreeObserver().addOnPreDrawListener(this); 4371 mPreDrawRegistered = true; 4372 } 4373 } 4374 4375 /** 4376 * {@inheritDoc} 4377 */ 4378 public boolean onPreDraw() { 4379 if (mLayout == null) { 4380 assumeLayout(); 4381 } 4382 4383 boolean changed = false; 4384 4385 if (mMovement != null) { 4386 /* This code also provides auto-scrolling when a cursor is moved using a 4387 * CursorController (insertion point or selection limits). 4388 * For selection, ensure start or end is visible depending on controller's state. 4389 */ 4390 int curs = getSelectionEnd(); 4391 // Do not create the controller if it is not already created. 4392 if (mSelectionModifierCursorController != null && 4393 mSelectionModifierCursorController.isSelectionStartDragged()) { 4394 curs = getSelectionStart(); 4395 } 4396 4397 /* 4398 * TODO: This should really only keep the end in view if 4399 * it already was before the text changed. I'm not sure 4400 * of a good way to tell from here if it was. 4401 */ 4402 if (curs < 0 && 4403 (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 4404 curs = mText.length(); 4405 } 4406 4407 if (curs >= 0) { 4408 changed = bringPointIntoView(curs); 4409 } 4410 } else { 4411 changed = bringTextIntoView(); 4412 } 4413 4414 // This has to be checked here since: 4415 // - onFocusChanged cannot start it when focus is given to a view with selected text (after 4416 // a screen rotation) since layout is not yet initialized at that point. 4417 if (mCreatedWithASelection) { 4418 startSelectionActionMode(); 4419 mCreatedWithASelection = false; 4420 } 4421 4422 // Phone specific code (there is no ExtractEditText on tablets). 4423 // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can 4424 // not be set. Do the test here instead. 4425 if (this instanceof ExtractEditText && hasSelection()) { 4426 startSelectionActionMode(); 4427 } 4428 4429 getViewTreeObserver().removeOnPreDrawListener(this); 4430 mPreDrawRegistered = false; 4431 4432 return !changed; 4433 } 4434 4435 @Override 4436 protected void onAttachedToWindow() { 4437 super.onAttachedToWindow(); 4438 4439 mTemporaryDetach = false; 4440 4441 if (mShowErrorAfterAttach) { 4442 showError(); 4443 mShowErrorAfterAttach = false; 4444 } 4445 4446 final ViewTreeObserver observer = getViewTreeObserver(); 4447 // No need to create the controller. 4448 // The get method will add the listener on controller creation. 4449 if (mInsertionPointCursorController != null) { 4450 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 4451 } 4452 if (mSelectionModifierCursorController != null) { 4453 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 4454 } 4455 4456 // Resolve drawables as the layout direction has been resolved 4457 resolveDrawables(); 4458 4459 updateSpellCheckSpans(0, mText.length(), true /* create the spell checker if needed */); 4460 } 4461 4462 @Override 4463 protected void onDetachedFromWindow() { 4464 super.onDetachedFromWindow(); 4465 4466 if (mPreDrawRegistered) { 4467 getViewTreeObserver().removeOnPreDrawListener(this); 4468 mPreDrawRegistered = false; 4469 } 4470 4471 if (mError != null) { 4472 hideError(); 4473 } 4474 4475 if (mBlink != null) { 4476 mBlink.removeCallbacks(mBlink); 4477 } 4478 4479 if (mInsertionPointCursorController != null) { 4480 mInsertionPointCursorController.onDetached(); 4481 } 4482 4483 if (mSelectionModifierCursorController != null) { 4484 mSelectionModifierCursorController.onDetached(); 4485 } 4486 4487 if (mShowSuggestionRunnable != null) { 4488 removeCallbacks(mShowSuggestionRunnable); 4489 } 4490 4491 hideControllers(); 4492 4493 resetResolvedDrawables(); 4494 4495 if (mTextDisplayList != null) { 4496 mTextDisplayList.invalidate(); 4497 } 4498 4499 if (mSpellChecker != null) { 4500 mSpellChecker.closeSession(); 4501 // Forces the creation of a new SpellChecker next time this window is created. 4502 // Will handle the cases where the settings has been changed in the meantime. 4503 mSpellChecker = null; 4504 } 4505 } 4506 4507 @Override 4508 protected boolean isPaddingOffsetRequired() { 4509 return mShadowRadius != 0 || mDrawables != null; 4510 } 4511 4512 @Override 4513 protected int getLeftPaddingOffset() { 4514 return getCompoundPaddingLeft() - mPaddingLeft + 4515 (int) Math.min(0, mShadowDx - mShadowRadius); 4516 } 4517 4518 @Override 4519 protected int getTopPaddingOffset() { 4520 return (int) Math.min(0, mShadowDy - mShadowRadius); 4521 } 4522 4523 @Override 4524 protected int getBottomPaddingOffset() { 4525 return (int) Math.max(0, mShadowDy + mShadowRadius); 4526 } 4527 4528 @Override 4529 protected int getRightPaddingOffset() { 4530 return -(getCompoundPaddingRight() - mPaddingRight) + 4531 (int) Math.max(0, mShadowDx + mShadowRadius); 4532 } 4533 4534 @Override 4535 protected boolean verifyDrawable(Drawable who) { 4536 final boolean verified = super.verifyDrawable(who); 4537 if (!verified && mDrawables != null) { 4538 return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || 4539 who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom || 4540 who == mDrawables.mDrawableStart || who == mDrawables.mDrawableEnd; 4541 } 4542 return verified; 4543 } 4544 4545 @Override 4546 public void jumpDrawablesToCurrentState() { 4547 super.jumpDrawablesToCurrentState(); 4548 if (mDrawables != null) { 4549 if (mDrawables.mDrawableLeft != null) { 4550 mDrawables.mDrawableLeft.jumpToCurrentState(); 4551 } 4552 if (mDrawables.mDrawableTop != null) { 4553 mDrawables.mDrawableTop.jumpToCurrentState(); 4554 } 4555 if (mDrawables.mDrawableRight != null) { 4556 mDrawables.mDrawableRight.jumpToCurrentState(); 4557 } 4558 if (mDrawables.mDrawableBottom != null) { 4559 mDrawables.mDrawableBottom.jumpToCurrentState(); 4560 } 4561 if (mDrawables.mDrawableStart != null) { 4562 mDrawables.mDrawableStart.jumpToCurrentState(); 4563 } 4564 if (mDrawables.mDrawableEnd != null) { 4565 mDrawables.mDrawableEnd.jumpToCurrentState(); 4566 } 4567 } 4568 } 4569 4570 @Override 4571 public void invalidateDrawable(Drawable drawable) { 4572 if (verifyDrawable(drawable)) { 4573 final Rect dirty = drawable.getBounds(); 4574 int scrollX = mScrollX; 4575 int scrollY = mScrollY; 4576 4577 // IMPORTANT: The coordinates below are based on the coordinates computed 4578 // for each compound drawable in onDraw(). Make sure to update each section 4579 // accordingly. 4580 final TextView.Drawables drawables = mDrawables; 4581 if (drawables != null) { 4582 if (drawable == drawables.mDrawableLeft) { 4583 final int compoundPaddingTop = getCompoundPaddingTop(); 4584 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4585 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4586 4587 scrollX += mPaddingLeft; 4588 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 4589 } else if (drawable == drawables.mDrawableRight) { 4590 final int compoundPaddingTop = getCompoundPaddingTop(); 4591 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4592 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4593 4594 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 4595 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 4596 } else if (drawable == drawables.mDrawableTop) { 4597 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4598 final int compoundPaddingRight = getCompoundPaddingRight(); 4599 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4600 4601 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 4602 scrollY += mPaddingTop; 4603 } else if (drawable == drawables.mDrawableBottom) { 4604 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4605 final int compoundPaddingRight = getCompoundPaddingRight(); 4606 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4607 4608 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 4609 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 4610 } 4611 } 4612 4613 invalidate(dirty.left + scrollX, dirty.top + scrollY, 4614 dirty.right + scrollX, dirty.bottom + scrollY); 4615 } 4616 } 4617 4618 /** 4619 * @hide 4620 */ 4621 @Override 4622 public int getResolvedLayoutDirection(Drawable who) { 4623 if (who == null) return View.LAYOUT_DIRECTION_LTR; 4624 if (mDrawables != null) { 4625 final Drawables drawables = mDrawables; 4626 if (who == drawables.mDrawableLeft || who == drawables.mDrawableRight || 4627 who == drawables.mDrawableTop || who == drawables.mDrawableBottom || 4628 who == drawables.mDrawableStart || who == drawables.mDrawableEnd) { 4629 return getResolvedLayoutDirection(); 4630 } 4631 } 4632 return super.getResolvedLayoutDirection(who); 4633 } 4634 4635 @Override 4636 protected boolean onSetAlpha(int alpha) { 4637 // Alpha is supported if and only if the drawing can be done in one pass. 4638 // TODO text with spans with a background color currently do not respect this alpha. 4639 if (getBackground() == null) { 4640 if (mCurrentAlpha != alpha) { 4641 mCurrentAlpha = alpha; 4642 final Drawables dr = mDrawables; 4643 if (dr != null) { 4644 if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha); 4645 if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha); 4646 if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha); 4647 if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha); 4648 if (dr.mDrawableStart != null) dr.mDrawableStart.mutate().setAlpha(alpha); 4649 if (dr.mDrawableEnd != null) dr.mDrawableEnd.mutate().setAlpha(alpha); 4650 } 4651 mTextDisplayListIsValid = false; 4652 } 4653 return true; 4654 } 4655 4656 if (mCurrentAlpha != 255) { 4657 mTextDisplayListIsValid = false; 4658 } 4659 mCurrentAlpha = 255; 4660 return false; 4661 } 4662 4663 /** 4664 * When a TextView is used to display a useful piece of information to the user (such as a 4665 * contact's address), it should be made selectable, so that the user can select and copy this 4666 * content. 4667 * 4668 * Use {@link #setTextIsSelectable(boolean)} or the 4669 * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView 4670 * selectable (text is not selectable by default). 4671 * 4672 * Note that this method simply returns the state of this flag. Although this flag has to be set 4673 * in order to select text in non-editable TextView, the content of an {@link EditText} can 4674 * always be selected, independently of the value of this flag. 4675 * 4676 * @return True if the text displayed in this TextView can be selected by the user. 4677 * 4678 * @attr ref android.R.styleable#TextView_textIsSelectable 4679 */ 4680 public boolean isTextSelectable() { 4681 return mTextIsSelectable; 4682 } 4683 4684 /** 4685 * Sets whether or not (default) the content of this view is selectable by the user. 4686 * 4687 * Note that this methods affect the {@link #setFocusable(boolean)}, 4688 * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and 4689 * {@link #setLongClickable(boolean)} states and you may want to restore these if they were 4690 * customized. 4691 * 4692 * See {@link #isTextSelectable} for details. 4693 * 4694 * @param selectable Whether or not the content of this TextView should be selectable. 4695 */ 4696 public void setTextIsSelectable(boolean selectable) { 4697 if (mTextIsSelectable == selectable) return; 4698 4699 mTextIsSelectable = selectable; 4700 4701 setFocusableInTouchMode(selectable); 4702 setFocusable(selectable); 4703 setClickable(selectable); 4704 setLongClickable(selectable); 4705 4706 // mInputType is already EditorInfo.TYPE_NULL and mInput is null; 4707 4708 setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); 4709 setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL); 4710 4711 // Called by setText above, but safer in case of future code changes 4712 prepareCursorControllers(); 4713 } 4714 4715 @Override 4716 protected int[] onCreateDrawableState(int extraSpace) { 4717 final int[] drawableState; 4718 4719 if (mSingleLine) { 4720 drawableState = super.onCreateDrawableState(extraSpace); 4721 } else { 4722 drawableState = super.onCreateDrawableState(extraSpace + 1); 4723 mergeDrawableStates(drawableState, MULTILINE_STATE_SET); 4724 } 4725 4726 if (mTextIsSelectable) { 4727 // Disable pressed state, which was introduced when TextView was made clickable. 4728 // Prevents text color change. 4729 // setClickable(false) would have a similar effect, but it also disables focus changes 4730 // and long press actions, which are both needed by text selection. 4731 final int length = drawableState.length; 4732 for (int i = 0; i < length; i++) { 4733 if (drawableState[i] == R.attr.state_pressed) { 4734 final int[] nonPressedState = new int[length - 1]; 4735 System.arraycopy(drawableState, 0, nonPressedState, 0, i); 4736 System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); 4737 return nonPressedState; 4738 } 4739 } 4740 } 4741 4742 return drawableState; 4743 } 4744 4745 @Override 4746 protected void onDraw(Canvas canvas) { 4747 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return; 4748 4749 restartMarqueeIfNeeded(); 4750 4751 // Draw the background for this view 4752 super.onDraw(canvas); 4753 4754 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4755 final int compoundPaddingTop = getCompoundPaddingTop(); 4756 final int compoundPaddingRight = getCompoundPaddingRight(); 4757 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4758 final int scrollX = mScrollX; 4759 final int scrollY = mScrollY; 4760 final int right = mRight; 4761 final int left = mLeft; 4762 final int bottom = mBottom; 4763 final int top = mTop; 4764 4765 final Drawables dr = mDrawables; 4766 if (dr != null) { 4767 /* 4768 * Compound, not extended, because the icon is not clipped 4769 * if the text height is smaller. 4770 */ 4771 4772 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 4773 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 4774 4775 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4776 // Make sure to update invalidateDrawable() when changing this code. 4777 if (dr.mDrawableLeft != null) { 4778 canvas.save(); 4779 canvas.translate(scrollX + mPaddingLeft, 4780 scrollY + compoundPaddingTop + 4781 (vspace - dr.mDrawableHeightLeft) / 2); 4782 dr.mDrawableLeft.draw(canvas); 4783 canvas.restore(); 4784 } 4785 4786 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4787 // Make sure to update invalidateDrawable() when changing this code. 4788 if (dr.mDrawableRight != null) { 4789 canvas.save(); 4790 canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight, 4791 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 4792 dr.mDrawableRight.draw(canvas); 4793 canvas.restore(); 4794 } 4795 4796 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4797 // Make sure to update invalidateDrawable() when changing this code. 4798 if (dr.mDrawableTop != null) { 4799 canvas.save(); 4800 canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, 4801 scrollY + mPaddingTop); 4802 dr.mDrawableTop.draw(canvas); 4803 canvas.restore(); 4804 } 4805 4806 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4807 // Make sure to update invalidateDrawable() when changing this code. 4808 if (dr.mDrawableBottom != null) { 4809 canvas.save(); 4810 canvas.translate(scrollX + compoundPaddingLeft + 4811 (hspace - dr.mDrawableWidthBottom) / 2, 4812 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 4813 dr.mDrawableBottom.draw(canvas); 4814 canvas.restore(); 4815 } 4816 } 4817 4818 int color = mCurTextColor; 4819 4820 if (mLayout == null) { 4821 assumeLayout(); 4822 } 4823 4824 Layout layout = mLayout; 4825 int cursorcolor = color; 4826 4827 if (mHint != null && mText.length() == 0) { 4828 if (mHintTextColor != null) { 4829 color = mCurHintTextColor; 4830 } 4831 4832 layout = mHintLayout; 4833 } 4834 4835 mTextPaint.setColor(color); 4836 if (mCurrentAlpha != 255) { 4837 // If set, the alpha will override the color's alpha. Multiply the alphas. 4838 mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255); 4839 } 4840 mTextPaint.drawableState = getDrawableState(); 4841 4842 canvas.save(); 4843 /* Would be faster if we didn't have to do this. Can we chop the 4844 (displayable) text so that we don't need to do this ever? 4845 */ 4846 4847 int extendedPaddingTop = getExtendedPaddingTop(); 4848 int extendedPaddingBottom = getExtendedPaddingBottom(); 4849 4850 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4851 final int maxScrollY = mLayout.getHeight() - vspace; 4852 4853 float clipLeft = compoundPaddingLeft + scrollX; 4854 float clipTop = (scrollY == 0) ? 0 : extendedPaddingTop + scrollY; 4855 float clipRight = right - left - compoundPaddingRight + scrollX; 4856 float clipBottom = bottom - top + scrollY - 4857 ((scrollY == maxScrollY) ? 0 : extendedPaddingBottom); 4858 4859 if (mShadowRadius != 0) { 4860 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 4861 clipRight += Math.max(0, mShadowDx + mShadowRadius); 4862 4863 clipTop += Math.min(0, mShadowDy - mShadowRadius); 4864 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 4865 } 4866 4867 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 4868 4869 int voffsetText = 0; 4870 int voffsetCursor = 0; 4871 4872 // translate in by our padding 4873 { 4874 /* shortcircuit calling getVerticaOffset() */ 4875 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4876 voffsetText = getVerticalOffset(false); 4877 voffsetCursor = getVerticalOffset(true); 4878 } 4879 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 4880 } 4881 4882 final int layoutDirection = getResolvedLayoutDirection(); 4883 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 4884 if (mEllipsize == TextUtils.TruncateAt.MARQUEE && 4885 mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 4886 if (!mSingleLine && getLineCount() == 1 && canMarquee() && 4887 (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 4888 canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft - 4889 getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f); 4890 } 4891 4892 if (mMarquee != null && mMarquee.isRunning()) { 4893 canvas.translate(-mMarquee.mScroll, 0.0f); 4894 } 4895 } 4896 4897 Path highlight = null; 4898 int selStart = -1, selEnd = -1; 4899 boolean drawCursor = false; 4900 4901 // If there is no movement method, then there can be no selection. 4902 // Check that first and attempt to skip everything having to do with 4903 // the cursor. 4904 // XXX This is not strictly true -- a program could set the 4905 // selection manually if it really wanted to. 4906 if (mMovement != null && (isFocused() || isPressed())) { 4907 selStart = getSelectionStart(); 4908 selEnd = getSelectionEnd(); 4909 4910 if (selStart >= 0) { 4911 if (mHighlightPath == null) mHighlightPath = new Path(); 4912 4913 if (selStart == selEnd) { 4914 if (isCursorVisible() && 4915 (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) { 4916 if (mHighlightPathBogus) { 4917 mHighlightPath.reset(); 4918 mLayout.getCursorPath(selStart, mHighlightPath, mText); 4919 updateCursorsPositions(); 4920 mHighlightPathBogus = false; 4921 } 4922 4923 // XXX should pass to skin instead of drawing directly 4924 mHighlightPaint.setColor(cursorcolor); 4925 if (mCurrentAlpha != 255) { 4926 mHighlightPaint.setAlpha( 4927 (mCurrentAlpha * Color.alpha(cursorcolor)) / 255); 4928 } 4929 mHighlightPaint.setStyle(Paint.Style.STROKE); 4930 highlight = mHighlightPath; 4931 drawCursor = mCursorCount > 0; 4932 } 4933 } else if (textCanBeSelected()) { 4934 if (mHighlightPathBogus) { 4935 mHighlightPath.reset(); 4936 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 4937 mHighlightPathBogus = false; 4938 } 4939 4940 // XXX should pass to skin instead of drawing directly 4941 mHighlightPaint.setColor(mHighlightColor); 4942 if (mCurrentAlpha != 255) { 4943 mHighlightPaint.setAlpha( 4944 (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255); 4945 } 4946 mHighlightPaint.setStyle(Paint.Style.FILL); 4947 4948 highlight = mHighlightPath; 4949 } 4950 } 4951 } 4952 4953 final InputMethodState ims = mInputMethodState; 4954 final int cursorOffsetVertical = voffsetCursor - voffsetText; 4955 if (ims != null && ims.mBatchEditNesting == 0) { 4956 InputMethodManager imm = InputMethodManager.peekInstance(); 4957 if (imm != null) { 4958 if (imm.isActive(this)) { 4959 boolean reported = false; 4960 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4961 // We are in extract mode and the content has changed 4962 // in some way... just report complete new text to the 4963 // input method. 4964 reported = reportExtractedText(); 4965 } 4966 if (!reported && highlight != null) { 4967 int candStart = -1; 4968 int candEnd = -1; 4969 if (mText instanceof Spannable) { 4970 Spannable sp = (Spannable)mText; 4971 candStart = EditableInputConnection.getComposingSpanStart(sp); 4972 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 4973 } 4974 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 4975 } 4976 } 4977 4978 if (imm.isWatchingCursor(this) && highlight != null) { 4979 highlight.computeBounds(ims.mTmpRectF, true); 4980 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 4981 4982 canvas.getMatrix().mapPoints(ims.mTmpOffset); 4983 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 4984 4985 ims.mTmpRectF.offset(0, cursorOffsetVertical); 4986 4987 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 4988 (int)(ims.mTmpRectF.top + 0.5), 4989 (int)(ims.mTmpRectF.right + 0.5), 4990 (int)(ims.mTmpRectF.bottom + 0.5)); 4991 4992 imm.updateCursor(this, 4993 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 4994 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 4995 } 4996 } 4997 } 4998 4999 if (mCorrectionHighlighter != null) { 5000 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 5001 } 5002 5003 if (drawCursor) { 5004 drawCursor(canvas, cursorOffsetVertical); 5005 // Rely on the drawable entirely, do not draw the cursor line. 5006 // Has to be done after the IMM related code above which relies on the highlight. 5007 highlight = null; 5008 } 5009 5010 if (canHaveDisplayList() && canvas.isHardwareAccelerated()) { 5011 final int width = mRight - mLeft; 5012 final int height = mBottom - mTop; 5013 5014 if (mTextDisplayList == null || !mTextDisplayList.isValid() || 5015 !mTextDisplayListIsValid) { 5016 if (mTextDisplayList == null) { 5017 mTextDisplayList = getHardwareRenderer().createDisplayList("Text"); 5018 } 5019 5020 final HardwareCanvas hardwareCanvas = mTextDisplayList.start(); 5021 try { 5022 hardwareCanvas.setViewport(width, height); 5023 // The dirty rect should always be null for a display list 5024 hardwareCanvas.onPreDraw(null); 5025 layout.draw(hardwareCanvas, highlight, mHighlightPaint, cursorOffsetVertical); 5026 } finally { 5027 hardwareCanvas.onPostDraw(); 5028 mTextDisplayList.end(); 5029 mTextDisplayListIsValid = true; 5030 } 5031 } 5032 ((HardwareCanvas) canvas).drawDisplayList(mTextDisplayList, 5033 mScrollX + width, mScrollY + height, null); 5034 } else { 5035 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 5036 } 5037 5038 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 5039 canvas.translate((int) mMarquee.getGhostOffset(), 0.0f); 5040 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 5041 } 5042 5043 canvas.restore(); 5044 } 5045 5046 private void updateCursorsPositions() { 5047 if (mCursorDrawableRes == 0) { 5048 mCursorCount = 0; 5049 return; 5050 } 5051 5052 final int offset = getSelectionStart(); 5053 final int line = mLayout.getLineForOffset(offset); 5054 final int top = mLayout.getLineTop(line); 5055 final int bottom = mLayout.getLineTop(line + 1); 5056 5057 mCursorCount = mLayout.isLevelBoundary(offset) ? 2 : 1; 5058 5059 int middle = bottom; 5060 if (mCursorCount == 2) { 5061 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)} 5062 middle = (top + bottom) >> 1; 5063 } 5064 5065 updateCursorPosition(0, top, middle, mLayout.getPrimaryHorizontal(offset)); 5066 5067 if (mCursorCount == 2) { 5068 updateCursorPosition(1, middle, bottom, mLayout.getSecondaryHorizontal(offset)); 5069 } 5070 } 5071 5072 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) { 5073 if (mCursorDrawable[cursorIndex] == null) 5074 mCursorDrawable[cursorIndex] = mContext.getResources().getDrawable(mCursorDrawableRes); 5075 5076 if (mTempRect == null) mTempRect = new Rect(); 5077 5078 mCursorDrawable[cursorIndex].getPadding(mTempRect); 5079 final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth(); 5080 horizontal = Math.max(0.5f, horizontal - 0.5f); 5081 final int left = (int) (horizontal) - mTempRect.left; 5082 mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width, 5083 bottom + mTempRect.bottom); 5084 } 5085 5086 private void drawCursor(Canvas canvas, int cursorOffsetVertical) { 5087 final boolean translate = cursorOffsetVertical != 0; 5088 if (translate) canvas.translate(0, cursorOffsetVertical); 5089 for (int i = 0; i < mCursorCount; i++) { 5090 mCursorDrawable[i].draw(canvas); 5091 } 5092 if (translate) canvas.translate(0, -cursorOffsetVertical); 5093 } 5094 5095 @Override 5096 public void getFocusedRect(Rect r) { 5097 if (mLayout == null) { 5098 super.getFocusedRect(r); 5099 return; 5100 } 5101 5102 int selEnd = getSelectionEnd(); 5103 if (selEnd < 0) { 5104 super.getFocusedRect(r); 5105 return; 5106 } 5107 5108 int selStart = getSelectionStart(); 5109 if (selStart < 0 || selStart >= selEnd) { 5110 int line = mLayout.getLineForOffset(selEnd); 5111 r.top = mLayout.getLineTop(line); 5112 r.bottom = mLayout.getLineBottom(line); 5113 r.left = (int) mLayout.getPrimaryHorizontal(selEnd) - 2; 5114 r.right = r.left + 4; 5115 } else { 5116 int lineStart = mLayout.getLineForOffset(selStart); 5117 int lineEnd = mLayout.getLineForOffset(selEnd); 5118 r.top = mLayout.getLineTop(lineStart); 5119 r.bottom = mLayout.getLineBottom(lineEnd); 5120 if (lineStart == lineEnd) { 5121 r.left = (int) mLayout.getPrimaryHorizontal(selStart); 5122 r.right = (int) mLayout.getPrimaryHorizontal(selEnd); 5123 } else { 5124 // Selection extends across multiple lines -- the focused 5125 // rect covers the entire width. 5126 if (mHighlightPath == null) mHighlightPath = new Path(); 5127 if (mHighlightPathBogus) { 5128 mHighlightPath.reset(); 5129 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 5130 mHighlightPathBogus = false; 5131 } 5132 synchronized (sTempRect) { 5133 mHighlightPath.computeBounds(sTempRect, true); 5134 r.left = (int)sTempRect.left-1; 5135 r.right = (int)sTempRect.right+1; 5136 } 5137 } 5138 } 5139 5140 // Adjust for padding and gravity. 5141 int paddingLeft = getCompoundPaddingLeft(); 5142 int paddingTop = getExtendedPaddingTop(); 5143 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5144 paddingTop += getVerticalOffset(false); 5145 } 5146 r.offset(paddingLeft, paddingTop); 5147 } 5148 5149 /** 5150 * Return the number of lines of text, or 0 if the internal Layout has not 5151 * been built. 5152 */ 5153 public int getLineCount() { 5154 return mLayout != null ? mLayout.getLineCount() : 0; 5155 } 5156 5157 /** 5158 * Return the baseline for the specified line (0...getLineCount() - 1) 5159 * If bounds is not null, return the top, left, right, bottom extents 5160 * of the specified line in it. If the internal Layout has not been built, 5161 * return 0 and set bounds to (0, 0, 0, 0) 5162 * @param line which line to examine (0..getLineCount() - 1) 5163 * @param bounds Optional. If not null, it returns the extent of the line 5164 * @return the Y-coordinate of the baseline 5165 */ 5166 public int getLineBounds(int line, Rect bounds) { 5167 if (mLayout == null) { 5168 if (bounds != null) { 5169 bounds.set(0, 0, 0, 0); 5170 } 5171 return 0; 5172 } 5173 else { 5174 int baseline = mLayout.getLineBounds(line, bounds); 5175 5176 int voffset = getExtendedPaddingTop(); 5177 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5178 voffset += getVerticalOffset(true); 5179 } 5180 if (bounds != null) { 5181 bounds.offset(getCompoundPaddingLeft(), voffset); 5182 } 5183 return baseline + voffset; 5184 } 5185 } 5186 5187 @Override 5188 public int getBaseline() { 5189 if (mLayout == null) { 5190 return super.getBaseline(); 5191 } 5192 5193 int voffset = 0; 5194 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5195 voffset = getVerticalOffset(true); 5196 } 5197 5198 return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); 5199 } 5200 5201 /** 5202 * @hide 5203 * @param offsetRequired 5204 */ 5205 @Override 5206 protected int getFadeTop(boolean offsetRequired) { 5207 if (mLayout == null) return 0; 5208 5209 int voffset = 0; 5210 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5211 voffset = getVerticalOffset(true); 5212 } 5213 5214 if (offsetRequired) voffset += getTopPaddingOffset(); 5215 5216 return getExtendedPaddingTop() + voffset; 5217 } 5218 5219 /** 5220 * @hide 5221 * @param offsetRequired 5222 */ 5223 @Override 5224 protected int getFadeHeight(boolean offsetRequired) { 5225 return mLayout != null ? mLayout.getHeight() : 0; 5226 } 5227 5228 @Override 5229 public boolean onKeyPreIme(int keyCode, KeyEvent event) { 5230 if (keyCode == KeyEvent.KEYCODE_BACK) { 5231 boolean isInSelectionMode = mSelectionActionMode != null; 5232 5233 if (isInSelectionMode) { 5234 if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { 5235 KeyEvent.DispatcherState state = getKeyDispatcherState(); 5236 if (state != null) { 5237 state.startTracking(event, this); 5238 } 5239 return true; 5240 } else if (event.getAction() == KeyEvent.ACTION_UP) { 5241 KeyEvent.DispatcherState state = getKeyDispatcherState(); 5242 if (state != null) { 5243 state.handleUpEvent(event); 5244 } 5245 if (event.isTracking() && !event.isCanceled()) { 5246 stopSelectionActionMode(); 5247 return true; 5248 } 5249 } 5250 } 5251 } 5252 return super.onKeyPreIme(keyCode, event); 5253 } 5254 5255 @Override 5256 public boolean onKeyDown(int keyCode, KeyEvent event) { 5257 int which = doKeyDown(keyCode, event, null); 5258 if (which == 0) { 5259 // Go through default dispatching. 5260 return super.onKeyDown(keyCode, event); 5261 } 5262 5263 return true; 5264 } 5265 5266 @Override 5267 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5268 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 5269 5270 int which = doKeyDown(keyCode, down, event); 5271 if (which == 0) { 5272 // Go through default dispatching. 5273 return super.onKeyMultiple(keyCode, repeatCount, event); 5274 } 5275 if (which == -1) { 5276 // Consumed the whole thing. 5277 return true; 5278 } 5279 5280 repeatCount--; 5281 5282 // We are going to dispatch the remaining events to either the input 5283 // or movement method. To do this, we will just send a repeated stream 5284 // of down and up events until we have done the complete repeatCount. 5285 // It would be nice if those interfaces had an onKeyMultiple() method, 5286 // but adding that is a more complicated change. 5287 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 5288 if (which == 1) { 5289 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 5290 while (--repeatCount > 0) { 5291 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 5292 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 5293 } 5294 hideErrorIfUnchanged(); 5295 5296 } else if (which == 2) { 5297 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 5298 while (--repeatCount > 0) { 5299 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 5300 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 5301 } 5302 } 5303 5304 return true; 5305 } 5306 5307 /** 5308 * Returns true if pressing ENTER in this field advances focus instead 5309 * of inserting the character. This is true mostly in single-line fields, 5310 * but also in mail addresses and subjects which will display on multiple 5311 * lines but where it doesn't make sense to insert newlines. 5312 */ 5313 private boolean shouldAdvanceFocusOnEnter() { 5314 if (mInput == null) { 5315 return false; 5316 } 5317 5318 if (mSingleLine) { 5319 return true; 5320 } 5321 5322 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 5323 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 5324 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS 5325 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 5326 return true; 5327 } 5328 } 5329 5330 return false; 5331 } 5332 5333 /** 5334 * Returns true if pressing TAB in this field advances focus instead 5335 * of inserting the character. Insert tabs only in multi-line editors. 5336 */ 5337 private boolean shouldAdvanceFocusOnTab() { 5338 if (mInput != null && !mSingleLine) { 5339 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 5340 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 5341 if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE 5342 || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { 5343 return false; 5344 } 5345 } 5346 } 5347 return true; 5348 } 5349 5350 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 5351 if (!isEnabled()) { 5352 return 0; 5353 } 5354 5355 switch (keyCode) { 5356 case KeyEvent.KEYCODE_ENTER: 5357 if (event.hasNoModifiers()) { 5358 // When mInputContentType is set, we know that we are 5359 // running in a "modern" cupcake environment, so don't need 5360 // to worry about the application trying to capture 5361 // enter key events. 5362 if (mInputContentType != null) { 5363 // If there is an action listener, given them a 5364 // chance to consume the event. 5365 if (mInputContentType.onEditorActionListener != null && 5366 mInputContentType.onEditorActionListener.onEditorAction( 5367 this, EditorInfo.IME_NULL, event)) { 5368 mInputContentType.enterDown = true; 5369 // We are consuming the enter key for them. 5370 return -1; 5371 } 5372 } 5373 5374 // If our editor should move focus when enter is pressed, or 5375 // this is a generated event from an IME action button, then 5376 // don't let it be inserted into the text. 5377 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 5378 || shouldAdvanceFocusOnEnter()) { 5379 if (hasOnClickListeners()) { 5380 return 0; 5381 } 5382 return -1; 5383 } 5384 } 5385 break; 5386 5387 case KeyEvent.KEYCODE_DPAD_CENTER: 5388 if (event.hasNoModifiers()) { 5389 if (shouldAdvanceFocusOnEnter()) { 5390 return 0; 5391 } 5392 } 5393 break; 5394 5395 case KeyEvent.KEYCODE_TAB: 5396 if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 5397 if (shouldAdvanceFocusOnTab()) { 5398 return 0; 5399 } 5400 } 5401 break; 5402 5403 // Has to be done on key down (and not on key up) to correctly be intercepted. 5404 case KeyEvent.KEYCODE_BACK: 5405 if (mSelectionActionMode != null) { 5406 stopSelectionActionMode(); 5407 return -1; 5408 } 5409 break; 5410 } 5411 5412 if (mInput != null) { 5413 resetErrorChangedFlag(); 5414 5415 boolean doDown = true; 5416 if (otherEvent != null) { 5417 try { 5418 beginBatchEdit(); 5419 final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent); 5420 hideErrorIfUnchanged(); 5421 doDown = false; 5422 if (handled) { 5423 return -1; 5424 } 5425 } catch (AbstractMethodError e) { 5426 // onKeyOther was added after 1.0, so if it isn't 5427 // implemented we need to try to dispatch as a regular down. 5428 } finally { 5429 endBatchEdit(); 5430 } 5431 } 5432 5433 if (doDown) { 5434 beginBatchEdit(); 5435 final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event); 5436 endBatchEdit(); 5437 hideErrorIfUnchanged(); 5438 if (handled) return 1; 5439 } 5440 } 5441 5442 // bug 650865: sometimes we get a key event before a layout. 5443 // don't try to move around if we don't know the layout. 5444 5445 if (mMovement != null && mLayout != null) { 5446 boolean doDown = true; 5447 if (otherEvent != null) { 5448 try { 5449 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 5450 otherEvent); 5451 doDown = false; 5452 if (handled) { 5453 return -1; 5454 } 5455 } catch (AbstractMethodError e) { 5456 // onKeyOther was added after 1.0, so if it isn't 5457 // implemented we need to try to dispatch as a regular down. 5458 } 5459 } 5460 if (doDown) { 5461 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 5462 return 2; 5463 } 5464 } 5465 5466 return 0; 5467 } 5468 5469 /** 5470 * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} 5471 * can be recorded. 5472 * @hide 5473 */ 5474 public void resetErrorChangedFlag() { 5475 /* 5476 * Keep track of what the error was before doing the input 5477 * so that if an input filter changed the error, we leave 5478 * that error showing. Otherwise, we take down whatever 5479 * error was showing when the user types something. 5480 */ 5481 mErrorWasChanged = false; 5482 } 5483 5484 /** 5485 * @hide 5486 */ 5487 public void hideErrorIfUnchanged() { 5488 if (mError != null && !mErrorWasChanged) { 5489 setError(null, null); 5490 } 5491 } 5492 5493 @Override 5494 public boolean onKeyUp(int keyCode, KeyEvent event) { 5495 if (!isEnabled()) { 5496 return super.onKeyUp(keyCode, event); 5497 } 5498 5499 switch (keyCode) { 5500 case KeyEvent.KEYCODE_DPAD_CENTER: 5501 if (event.hasNoModifiers()) { 5502 /* 5503 * If there is a click listener, just call through to 5504 * super, which will invoke it. 5505 * 5506 * If there isn't a click listener, try to show the soft 5507 * input method. (It will also 5508 * call performClick(), but that won't do anything in 5509 * this case.) 5510 */ 5511 if (!hasOnClickListeners()) { 5512 if (mMovement != null && mText instanceof Editable 5513 && mLayout != null && onCheckIsTextEditor()) { 5514 InputMethodManager imm = InputMethodManager.peekInstance(); 5515 viewClicked(imm); 5516 if (imm != null) { 5517 imm.showSoftInput(this, 0); 5518 } 5519 } 5520 } 5521 } 5522 return super.onKeyUp(keyCode, event); 5523 5524 case KeyEvent.KEYCODE_ENTER: 5525 if (event.hasNoModifiers()) { 5526 if (mInputContentType != null 5527 && mInputContentType.onEditorActionListener != null 5528 && mInputContentType.enterDown) { 5529 mInputContentType.enterDown = false; 5530 if (mInputContentType.onEditorActionListener.onEditorAction( 5531 this, EditorInfo.IME_NULL, event)) { 5532 return true; 5533 } 5534 } 5535 5536 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 5537 || shouldAdvanceFocusOnEnter()) { 5538 /* 5539 * If there is a click listener, just call through to 5540 * super, which will invoke it. 5541 * 5542 * If there isn't a click listener, try to advance focus, 5543 * but still call through to super, which will reset the 5544 * pressed state and longpress state. (It will also 5545 * call performClick(), but that won't do anything in 5546 * this case.) 5547 */ 5548 if (!hasOnClickListeners()) { 5549 View v = focusSearch(FOCUS_DOWN); 5550 5551 if (v != null) { 5552 if (!v.requestFocus(FOCUS_DOWN)) { 5553 throw new IllegalStateException( 5554 "focus search returned a view " + 5555 "that wasn't able to take focus!"); 5556 } 5557 5558 /* 5559 * Return true because we handled the key; super 5560 * will return false because there was no click 5561 * listener. 5562 */ 5563 super.onKeyUp(keyCode, event); 5564 return true; 5565 } else if ((event.getFlags() 5566 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 5567 // No target for next focus, but make sure the IME 5568 // if this came from it. 5569 InputMethodManager imm = InputMethodManager.peekInstance(); 5570 if (imm != null && imm.isActive(this)) { 5571 imm.hideSoftInputFromWindow(getWindowToken(), 0); 5572 } 5573 } 5574 } 5575 } 5576 return super.onKeyUp(keyCode, event); 5577 } 5578 break; 5579 } 5580 5581 if (mInput != null) 5582 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 5583 return true; 5584 5585 if (mMovement != null && mLayout != null) 5586 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 5587 return true; 5588 5589 return super.onKeyUp(keyCode, event); 5590 } 5591 5592 @Override 5593 public boolean onCheckIsTextEditor() { 5594 return mInputType != EditorInfo.TYPE_NULL; 5595 } 5596 5597 @Override 5598 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5599 if (onCheckIsTextEditor() && isEnabled()) { 5600 if (mInputMethodState == null) { 5601 mInputMethodState = new InputMethodState(); 5602 } 5603 outAttrs.inputType = mInputType; 5604 if (mInputContentType != null) { 5605 outAttrs.imeOptions = mInputContentType.imeOptions; 5606 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 5607 outAttrs.actionLabel = mInputContentType.imeActionLabel; 5608 outAttrs.actionId = mInputContentType.imeActionId; 5609 outAttrs.extras = mInputContentType.extras; 5610 } else { 5611 outAttrs.imeOptions = EditorInfo.IME_NULL; 5612 } 5613 if (focusSearch(FOCUS_DOWN) != null) { 5614 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 5615 } 5616 if (focusSearch(FOCUS_UP) != null) { 5617 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 5618 } 5619 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 5620 == EditorInfo.IME_ACTION_UNSPECIFIED) { 5621 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 5622 // An action has not been set, but the enter key will move to 5623 // the next focus, so set the action to that. 5624 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 5625 } else { 5626 // An action has not been set, and there is no focus to move 5627 // to, so let's just supply a "done" action. 5628 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 5629 } 5630 if (!shouldAdvanceFocusOnEnter()) { 5631 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5632 } 5633 } 5634 if (isMultilineInputType(outAttrs.inputType)) { 5635 // Multi-line text editors should always show an enter key. 5636 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5637 } 5638 outAttrs.hintText = mHint; 5639 if (mText instanceof Editable) { 5640 InputConnection ic = new EditableInputConnection(this); 5641 outAttrs.initialSelStart = getSelectionStart(); 5642 outAttrs.initialSelEnd = getSelectionEnd(); 5643 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 5644 return ic; 5645 } 5646 } 5647 return null; 5648 } 5649 5650 /** 5651 * If this TextView contains editable content, extract a portion of it 5652 * based on the information in <var>request</var> in to <var>outText</var>. 5653 * @return Returns true if the text was successfully extracted, else false. 5654 */ 5655 public boolean extractText(ExtractedTextRequest request, 5656 ExtractedText outText) { 5657 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 5658 EXTRACT_UNKNOWN, outText); 5659 } 5660 5661 static final int EXTRACT_NOTHING = -2; 5662 static final int EXTRACT_UNKNOWN = -1; 5663 5664 boolean extractTextInternal(ExtractedTextRequest request, 5665 int partialStartOffset, int partialEndOffset, int delta, 5666 ExtractedText outText) { 5667 final CharSequence content = mText; 5668 if (content != null) { 5669 if (partialStartOffset != EXTRACT_NOTHING) { 5670 final int N = content.length(); 5671 if (partialStartOffset < 0) { 5672 outText.partialStartOffset = outText.partialEndOffset = -1; 5673 partialStartOffset = 0; 5674 partialEndOffset = N; 5675 } else { 5676 // Now use the delta to determine the actual amount of text 5677 // we need. 5678 partialEndOffset += delta; 5679 // Adjust offsets to ensure we contain full spans. 5680 if (content instanceof Spanned) { 5681 Spanned spanned = (Spanned)content; 5682 Object[] spans = spanned.getSpans(partialStartOffset, 5683 partialEndOffset, ParcelableSpan.class); 5684 int i = spans.length; 5685 while (i > 0) { 5686 i--; 5687 int j = spanned.getSpanStart(spans[i]); 5688 if (j < partialStartOffset) partialStartOffset = j; 5689 j = spanned.getSpanEnd(spans[i]); 5690 if (j > partialEndOffset) partialEndOffset = j; 5691 } 5692 } 5693 outText.partialStartOffset = partialStartOffset; 5694 outText.partialEndOffset = partialEndOffset - delta; 5695 5696 if (partialStartOffset > N) { 5697 partialStartOffset = N; 5698 } else if (partialStartOffset < 0) { 5699 partialStartOffset = 0; 5700 } 5701 if (partialEndOffset > N) { 5702 partialEndOffset = N; 5703 } else if (partialEndOffset < 0) { 5704 partialEndOffset = 0; 5705 } 5706 } 5707 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 5708 outText.text = content.subSequence(partialStartOffset, 5709 partialEndOffset); 5710 } else { 5711 outText.text = TextUtils.substring(content, partialStartOffset, 5712 partialEndOffset); 5713 } 5714 } else { 5715 outText.partialStartOffset = 0; 5716 outText.partialEndOffset = 0; 5717 outText.text = ""; 5718 } 5719 outText.flags = 0; 5720 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 5721 outText.flags |= ExtractedText.FLAG_SELECTING; 5722 } 5723 if (mSingleLine) { 5724 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 5725 } 5726 outText.startOffset = 0; 5727 outText.selectionStart = getSelectionStart(); 5728 outText.selectionEnd = getSelectionEnd(); 5729 return true; 5730 } 5731 return false; 5732 } 5733 5734 boolean reportExtractedText() { 5735 final InputMethodState ims = mInputMethodState; 5736 if (ims != null) { 5737 final boolean contentChanged = ims.mContentChanged; 5738 if (contentChanged || ims.mSelectionModeChanged) { 5739 ims.mContentChanged = false; 5740 ims.mSelectionModeChanged = false; 5741 final ExtractedTextRequest req = mInputMethodState.mExtracting; 5742 if (req != null) { 5743 InputMethodManager imm = InputMethodManager.peekInstance(); 5744 if (imm != null) { 5745 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 5746 + ims.mChangedStart + " end=" + ims.mChangedEnd 5747 + " delta=" + ims.mChangedDelta); 5748 if (ims.mChangedStart < 0 && !contentChanged) { 5749 ims.mChangedStart = EXTRACT_NOTHING; 5750 } 5751 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 5752 ims.mChangedDelta, ims.mTmpExtracted)) { 5753 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 5754 + ims.mTmpExtracted.partialStartOffset 5755 + " end=" + ims.mTmpExtracted.partialEndOffset 5756 + ": " + ims.mTmpExtracted.text); 5757 imm.updateExtractedText(this, req.token, 5758 mInputMethodState.mTmpExtracted); 5759 ims.mChangedStart = EXTRACT_UNKNOWN; 5760 ims.mChangedEnd = EXTRACT_UNKNOWN; 5761 ims.mChangedDelta = 0; 5762 ims.mContentChanged = false; 5763 return true; 5764 } 5765 } 5766 } 5767 } 5768 } 5769 return false; 5770 } 5771 5772 /** 5773 * This is used to remove all style-impacting spans from text before new 5774 * extracted text is being replaced into it, so that we don't have any 5775 * lingering spans applied during the replace. 5776 */ 5777 static void removeParcelableSpans(Spannable spannable, int start, int end) { 5778 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 5779 int i = spans.length; 5780 while (i > 0) { 5781 i--; 5782 spannable.removeSpan(spans[i]); 5783 } 5784 } 5785 5786 /** 5787 * Apply to this text view the given extracted text, as previously 5788 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 5789 */ 5790 public void setExtractedText(ExtractedText text) { 5791 Editable content = getEditableText(); 5792 if (text.text != null) { 5793 if (content == null) { 5794 setText(text.text, TextView.BufferType.EDITABLE); 5795 } else if (text.partialStartOffset < 0) { 5796 removeParcelableSpans(content, 0, content.length()); 5797 content.replace(0, content.length(), text.text); 5798 } else { 5799 final int N = content.length(); 5800 int start = text.partialStartOffset; 5801 if (start > N) start = N; 5802 int end = text.partialEndOffset; 5803 if (end > N) end = N; 5804 removeParcelableSpans(content, start, end); 5805 content.replace(start, end, text.text); 5806 } 5807 } 5808 5809 // Now set the selection position... make sure it is in range, to 5810 // avoid crashes. If this is a partial update, it is possible that 5811 // the underlying text may have changed, causing us problems here. 5812 // Also we just don't want to trust clients to do the right thing. 5813 Spannable sp = (Spannable)getText(); 5814 final int N = sp.length(); 5815 int start = text.selectionStart; 5816 if (start < 0) start = 0; 5817 else if (start > N) start = N; 5818 int end = text.selectionEnd; 5819 if (end < 0) end = 0; 5820 else if (end > N) end = N; 5821 Selection.setSelection(sp, start, end); 5822 5823 // Finally, update the selection mode. 5824 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 5825 MetaKeyKeyListener.startSelecting(this, sp); 5826 } else { 5827 MetaKeyKeyListener.stopSelecting(this, sp); 5828 } 5829 } 5830 5831 /** 5832 * @hide 5833 */ 5834 public void setExtracting(ExtractedTextRequest req) { 5835 if (mInputMethodState != null) { 5836 mInputMethodState.mExtracting = req; 5837 } 5838 // This would stop a possible selection mode, but no such mode is started in case 5839 // extracted mode will start. Some text is selected though, and will trigger an action mode 5840 // in the extracted view. 5841 hideControllers(); 5842 } 5843 5844 /** 5845 * Called by the framework in response to a text completion from 5846 * the current input method, provided by it calling 5847 * {@link InputConnection#commitCompletion 5848 * InputConnection.commitCompletion()}. The default implementation does 5849 * nothing; text views that are supporting auto-completion should override 5850 * this to do their desired behavior. 5851 * 5852 * @param text The auto complete text the user has selected. 5853 */ 5854 public void onCommitCompletion(CompletionInfo text) { 5855 // intentionally empty 5856 } 5857 5858 /** 5859 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 5860 * a dictionnary) from the current input method, provided by it calling 5861 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 5862 * implementation flashes the background of the corrected word to provide feedback to the user. 5863 * 5864 * @param info The auto correct info about the text that was corrected. 5865 */ 5866 public void onCommitCorrection(CorrectionInfo info) { 5867 if (mCorrectionHighlighter == null) { 5868 mCorrectionHighlighter = new CorrectionHighlighter(); 5869 } else { 5870 mCorrectionHighlighter.invalidate(false); 5871 } 5872 5873 mCorrectionHighlighter.highlight(info); 5874 } 5875 5876 private class CorrectionHighlighter { 5877 private final Path mPath = new Path(); 5878 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5879 private int mStart, mEnd; 5880 private long mFadingStartTime; 5881 private final static int FADE_OUT_DURATION = 400; 5882 5883 public CorrectionHighlighter() { 5884 mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale); 5885 mPaint.setStyle(Paint.Style.FILL); 5886 } 5887 5888 public void highlight(CorrectionInfo info) { 5889 mStart = info.getOffset(); 5890 mEnd = mStart + info.getNewText().length(); 5891 mFadingStartTime = SystemClock.uptimeMillis(); 5892 5893 if (mStart < 0 || mEnd < 0) { 5894 stopAnimation(); 5895 } 5896 } 5897 5898 public void draw(Canvas canvas, int cursorOffsetVertical) { 5899 if (updatePath() && updatePaint()) { 5900 if (cursorOffsetVertical != 0) { 5901 canvas.translate(0, cursorOffsetVertical); 5902 } 5903 5904 canvas.drawPath(mPath, mPaint); 5905 5906 if (cursorOffsetVertical != 0) { 5907 canvas.translate(0, -cursorOffsetVertical); 5908 } 5909 invalidate(true); // TODO invalidate cursor region only 5910 } else { 5911 stopAnimation(); 5912 invalidate(false); // TODO invalidate cursor region only 5913 } 5914 } 5915 5916 private boolean updatePaint() { 5917 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5918 if (duration > FADE_OUT_DURATION) return false; 5919 5920 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5921 final int highlightColorAlpha = Color.alpha(mHighlightColor); 5922 final int color = (mHighlightColor & 0x00FFFFFF) + 5923 ((int) (highlightColorAlpha * coef) << 24); 5924 mPaint.setColor(color); 5925 return true; 5926 } 5927 5928 private boolean updatePath() { 5929 final Layout layout = TextView.this.mLayout; 5930 if (layout == null) return false; 5931 5932 // Update in case text is edited while the animation is run 5933 final int length = mText.length(); 5934 int start = Math.min(length, mStart); 5935 int end = Math.min(length, mEnd); 5936 5937 mPath.reset(); 5938 TextView.this.mLayout.getSelectionPath(start, end, mPath); 5939 return true; 5940 } 5941 5942 private void invalidate(boolean delayed) { 5943 if (TextView.this.mLayout == null) return; 5944 5945 synchronized (sTempRect) { 5946 mPath.computeBounds(sTempRect, false); 5947 5948 int left = getCompoundPaddingLeft(); 5949 int top = getExtendedPaddingTop() + getVerticalOffset(true); 5950 5951 if (delayed) { 5952 TextView.this.postInvalidateDelayed(16, // 60 Hz update 5953 left + (int) sTempRect.left, top + (int) sTempRect.top, 5954 left + (int) sTempRect.right, top + (int) sTempRect.bottom); 5955 } else { 5956 TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top, 5957 (int) sTempRect.right, (int) sTempRect.bottom); 5958 } 5959 } 5960 } 5961 5962 private void stopAnimation() { 5963 TextView.this.mCorrectionHighlighter = null; 5964 } 5965 } 5966 5967 public void beginBatchEdit() { 5968 mInBatchEditControllers = true; 5969 final InputMethodState ims = mInputMethodState; 5970 if (ims != null) { 5971 int nesting = ++ims.mBatchEditNesting; 5972 if (nesting == 1) { 5973 ims.mCursorChanged = false; 5974 ims.mChangedDelta = 0; 5975 if (ims.mContentChanged) { 5976 // We already have a pending change from somewhere else, 5977 // so turn this into a full update. 5978 ims.mChangedStart = 0; 5979 ims.mChangedEnd = mText.length(); 5980 } else { 5981 ims.mChangedStart = EXTRACT_UNKNOWN; 5982 ims.mChangedEnd = EXTRACT_UNKNOWN; 5983 ims.mContentChanged = false; 5984 } 5985 onBeginBatchEdit(); 5986 } 5987 } 5988 } 5989 5990 public void endBatchEdit() { 5991 mInBatchEditControllers = false; 5992 final InputMethodState ims = mInputMethodState; 5993 if (ims != null) { 5994 int nesting = --ims.mBatchEditNesting; 5995 if (nesting == 0) { 5996 finishBatchEdit(ims); 5997 } 5998 } 5999 } 6000 6001 void ensureEndedBatchEdit() { 6002 final InputMethodState ims = mInputMethodState; 6003 if (ims != null && ims.mBatchEditNesting != 0) { 6004 ims.mBatchEditNesting = 0; 6005 finishBatchEdit(ims); 6006 } 6007 } 6008 6009 void finishBatchEdit(final InputMethodState ims) { 6010 onEndBatchEdit(); 6011 6012 if (ims.mContentChanged || ims.mSelectionModeChanged) { 6013 updateAfterEdit(); 6014 reportExtractedText(); 6015 } else if (ims.mCursorChanged) { 6016 // Cheezy way to get us to report the current cursor location. 6017 invalidateCursor(); 6018 } 6019 } 6020 6021 void updateAfterEdit() { 6022 invalidate(); 6023 int curs = getSelectionStart(); 6024 6025 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6026 registerForPreDraw(); 6027 } 6028 6029 if (curs >= 0) { 6030 mHighlightPathBogus = true; 6031 makeBlink(); 6032 bringPointIntoView(curs); 6033 } 6034 6035 checkForResize(); 6036 } 6037 6038 /** 6039 * Called by the framework in response to a request to begin a batch 6040 * of edit operations through a call to link {@link #beginBatchEdit()}. 6041 */ 6042 public void onBeginBatchEdit() { 6043 // intentionally empty 6044 } 6045 6046 /** 6047 * Called by the framework in response to a request to end a batch 6048 * of edit operations through a call to link {@link #endBatchEdit}. 6049 */ 6050 public void onEndBatchEdit() { 6051 // intentionally empty 6052 } 6053 6054 /** 6055 * Called by the framework in response to a private command from the 6056 * current method, provided by it calling 6057 * {@link InputConnection#performPrivateCommand 6058 * InputConnection.performPrivateCommand()}. 6059 * 6060 * @param action The action name of the command. 6061 * @param data Any additional data for the command. This may be null. 6062 * @return Return true if you handled the command, else false. 6063 */ 6064 public boolean onPrivateIMECommand(String action, Bundle data) { 6065 return false; 6066 } 6067 6068 private void nullLayouts() { 6069 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 6070 mSavedLayout = (BoringLayout) mLayout; 6071 } 6072 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 6073 mSavedHintLayout = (BoringLayout) mHintLayout; 6074 } 6075 6076 mSavedMarqueeModeLayout = mLayout = mHintLayout = null; 6077 6078 mBoring = mHintBoring = null; 6079 6080 // Since it depends on the value of mLayout 6081 prepareCursorControllers(); 6082 } 6083 6084 /** 6085 * Make a new Layout based on the already-measured size of the view, 6086 * on the assumption that it was measured correctly at some point. 6087 */ 6088 private void assumeLayout() { 6089 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6090 6091 if (width < 1) { 6092 width = 0; 6093 } 6094 6095 int physicalWidth = width; 6096 6097 if (mHorizontallyScrolling) { 6098 width = VERY_WIDE; 6099 } 6100 6101 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 6102 physicalWidth, false); 6103 } 6104 6105 @Override 6106 protected void resetResolvedLayoutDirection() { 6107 super.resetResolvedLayoutDirection(); 6108 6109 if (mLayoutAlignment != null && 6110 (mTextAlign == TextAlign.VIEW_START || 6111 mTextAlign == TextAlign.VIEW_END)) { 6112 mLayoutAlignment = null; 6113 } 6114 } 6115 6116 private Layout.Alignment getLayoutAlignment() { 6117 if (mLayoutAlignment == null) { 6118 Layout.Alignment alignment; 6119 TextAlign textAlign = mTextAlign; 6120 switch (textAlign) { 6121 case INHERIT: 6122 // fall through to gravity temporarily 6123 // intention is to inherit value through view hierarchy. 6124 case GRAVITY: 6125 switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) { 6126 case Gravity.START: 6127 alignment = Layout.Alignment.ALIGN_NORMAL; 6128 break; 6129 case Gravity.END: 6130 alignment = Layout.Alignment.ALIGN_OPPOSITE; 6131 break; 6132 case Gravity.LEFT: 6133 alignment = Layout.Alignment.ALIGN_LEFT; 6134 break; 6135 case Gravity.RIGHT: 6136 alignment = Layout.Alignment.ALIGN_RIGHT; 6137 break; 6138 case Gravity.CENTER_HORIZONTAL: 6139 alignment = Layout.Alignment.ALIGN_CENTER; 6140 break; 6141 default: 6142 alignment = Layout.Alignment.ALIGN_NORMAL; 6143 break; 6144 } 6145 break; 6146 case TEXT_START: 6147 alignment = Layout.Alignment.ALIGN_NORMAL; 6148 break; 6149 case TEXT_END: 6150 alignment = Layout.Alignment.ALIGN_OPPOSITE; 6151 break; 6152 case CENTER: 6153 alignment = Layout.Alignment.ALIGN_CENTER; 6154 break; 6155 case VIEW_START: 6156 alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 6157 Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; 6158 break; 6159 case VIEW_END: 6160 alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 6161 Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; 6162 break; 6163 default: 6164 alignment = Layout.Alignment.ALIGN_NORMAL; 6165 break; 6166 } 6167 mLayoutAlignment = alignment; 6168 } 6169 return mLayoutAlignment; 6170 } 6171 6172 /** 6173 * The width passed in is now the desired layout width, 6174 * not the full view width with padding. 6175 * {@hide} 6176 */ 6177 protected void makeNewLayout(int wantWidth, int hintWidth, 6178 BoringLayout.Metrics boring, 6179 BoringLayout.Metrics hintBoring, 6180 int ellipsisWidth, boolean bringIntoView) { 6181 stopMarquee(); 6182 6183 // Update "old" cached values 6184 mOldMaximum = mMaximum; 6185 mOldMaxMode = mMaxMode; 6186 6187 mHighlightPathBogus = true; 6188 6189 if (wantWidth < 0) { 6190 wantWidth = 0; 6191 } 6192 if (hintWidth < 0) { 6193 hintWidth = 0; 6194 } 6195 6196 Layout.Alignment alignment = getLayoutAlignment(); 6197 boolean shouldEllipsize = mEllipsize != null && mInput == null; 6198 final boolean switchEllipsize = mEllipsize == TruncateAt.MARQUEE && 6199 mMarqueeFadeMode != MARQUEE_FADE_NORMAL; 6200 TruncateAt effectiveEllipsize = mEllipsize; 6201 if (mEllipsize == TruncateAt.MARQUEE && 6202 mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 6203 effectiveEllipsize = TruncateAt.END_SMALL; 6204 } 6205 6206 if (mTextDir == null) { 6207 resolveTextDirection(); 6208 } 6209 6210 mLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, shouldEllipsize, 6211 effectiveEllipsize, effectiveEllipsize == mEllipsize); 6212 if (switchEllipsize) { 6213 TruncateAt oppositeEllipsize = effectiveEllipsize == TruncateAt.MARQUEE ? 6214 TruncateAt.END : TruncateAt.MARQUEE; 6215 mSavedMarqueeModeLayout = makeSingleLayout(wantWidth, boring, ellipsisWidth, alignment, 6216 shouldEllipsize, oppositeEllipsize, effectiveEllipsize != mEllipsize); 6217 } 6218 6219 shouldEllipsize = mEllipsize != null; 6220 mHintLayout = null; 6221 6222 if (mHint != null) { 6223 if (shouldEllipsize) hintWidth = wantWidth; 6224 6225 if (hintBoring == UNKNOWN_BORING) { 6226 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, 6227 mHintBoring); 6228 if (hintBoring != null) { 6229 mHintBoring = hintBoring; 6230 } 6231 } 6232 6233 if (hintBoring != null) { 6234 if (hintBoring.width <= hintWidth && 6235 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 6236 if (mSavedHintLayout != null) { 6237 mHintLayout = mSavedHintLayout. 6238 replaceOrMake(mHint, mTextPaint, 6239 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6240 hintBoring, mIncludePad); 6241 } else { 6242 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6243 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6244 hintBoring, mIncludePad); 6245 } 6246 6247 mSavedHintLayout = (BoringLayout) mHintLayout; 6248 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 6249 if (mSavedHintLayout != null) { 6250 mHintLayout = mSavedHintLayout. 6251 replaceOrMake(mHint, mTextPaint, 6252 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6253 hintBoring, mIncludePad, mEllipsize, 6254 ellipsisWidth); 6255 } else { 6256 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6257 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6258 hintBoring, mIncludePad, mEllipsize, 6259 ellipsisWidth); 6260 } 6261 } else if (shouldEllipsize) { 6262 mHintLayout = new StaticLayout(mHint, 6263 0, mHint.length(), 6264 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6265 mSpacingAdd, mIncludePad, mEllipsize, 6266 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6267 } else { 6268 mHintLayout = new StaticLayout(mHint, mTextPaint, 6269 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6270 mIncludePad); 6271 } 6272 } else if (shouldEllipsize) { 6273 mHintLayout = new StaticLayout(mHint, 6274 0, mHint.length(), 6275 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6276 mSpacingAdd, mIncludePad, mEllipsize, 6277 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6278 } else { 6279 mHintLayout = new StaticLayout(mHint, mTextPaint, 6280 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6281 mIncludePad); 6282 } 6283 } 6284 6285 if (bringIntoView) { 6286 registerForPreDraw(); 6287 } 6288 6289 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6290 if (!compressText(ellipsisWidth)) { 6291 final int height = mLayoutParams.height; 6292 // If the size of the view does not depend on the size of the text, try to 6293 // start the marquee immediately 6294 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 6295 startMarquee(); 6296 } else { 6297 // Defer the start of the marquee until we know our width (see setFrame()) 6298 mRestartMarquee = true; 6299 } 6300 } 6301 } 6302 6303 // CursorControllers need a non-null mLayout 6304 prepareCursorControllers(); 6305 } 6306 6307 private Layout makeSingleLayout(int wantWidth, BoringLayout.Metrics boring, int ellipsisWidth, 6308 Layout.Alignment alignment, boolean shouldEllipsize, TruncateAt effectiveEllipsize, 6309 boolean useSaved) { 6310 Layout result = null; 6311 if (mText instanceof Spannable) { 6312 result = new DynamicLayout(mText, mTransformed, mTextPaint, wantWidth, 6313 alignment, mTextDir, mSpacingMult, 6314 mSpacingAdd, mIncludePad, mInput == null ? effectiveEllipsize : null, 6315 ellipsisWidth); 6316 } else { 6317 if (boring == UNKNOWN_BORING) { 6318 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6319 if (boring != null) { 6320 mBoring = boring; 6321 } 6322 } 6323 6324 if (boring != null) { 6325 if (boring.width <= wantWidth && 6326 (effectiveEllipsize == null || boring.width <= ellipsisWidth)) { 6327 if (useSaved && mSavedLayout != null) { 6328 result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, 6329 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6330 boring, mIncludePad); 6331 } else { 6332 result = BoringLayout.make(mTransformed, mTextPaint, 6333 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6334 boring, mIncludePad); 6335 } 6336 6337 if (useSaved) { 6338 mSavedLayout = (BoringLayout) result; 6339 } 6340 } else if (shouldEllipsize && boring.width <= wantWidth) { 6341 if (useSaved && mSavedLayout != null) { 6342 result = mSavedLayout.replaceOrMake(mTransformed, mTextPaint, 6343 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6344 boring, mIncludePad, effectiveEllipsize, 6345 ellipsisWidth); 6346 } else { 6347 result = BoringLayout.make(mTransformed, mTextPaint, 6348 wantWidth, alignment, mSpacingMult, mSpacingAdd, 6349 boring, mIncludePad, effectiveEllipsize, 6350 ellipsisWidth); 6351 } 6352 } else if (shouldEllipsize) { 6353 result = new StaticLayout(mTransformed, 6354 0, mTransformed.length(), 6355 mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, 6356 mSpacingAdd, mIncludePad, effectiveEllipsize, 6357 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6358 } else { 6359 result = new StaticLayout(mTransformed, mTextPaint, 6360 wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6361 mIncludePad); 6362 } 6363 } else if (shouldEllipsize) { 6364 result = new StaticLayout(mTransformed, 6365 0, mTransformed.length(), 6366 mTextPaint, wantWidth, alignment, mTextDir, mSpacingMult, 6367 mSpacingAdd, mIncludePad, effectiveEllipsize, 6368 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6369 } else { 6370 result = new StaticLayout(mTransformed, mTextPaint, 6371 wantWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6372 mIncludePad); 6373 } 6374 } 6375 return result; 6376 } 6377 6378 private boolean compressText(float width) { 6379 if (isHardwareAccelerated()) return false; 6380 6381 // Only compress the text if it hasn't been compressed by the previous pass 6382 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 6383 mTextPaint.getTextScaleX() == 1.0f) { 6384 final float textWidth = mLayout.getLineWidth(0); 6385 final float overflow = (textWidth + 1.0f - width) / width; 6386 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 6387 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 6388 post(new Runnable() { 6389 public void run() { 6390 requestLayout(); 6391 } 6392 }); 6393 return true; 6394 } 6395 } 6396 6397 return false; 6398 } 6399 6400 private static int desired(Layout layout) { 6401 int n = layout.getLineCount(); 6402 CharSequence text = layout.getText(); 6403 float max = 0; 6404 6405 // if any line was wrapped, we can't use it. 6406 // but it's ok for the last line not to have a newline 6407 6408 for (int i = 0; i < n - 1; i++) { 6409 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 6410 return -1; 6411 } 6412 6413 for (int i = 0; i < n; i++) { 6414 max = Math.max(max, layout.getLineWidth(i)); 6415 } 6416 6417 return (int) FloatMath.ceil(max); 6418 } 6419 6420 /** 6421 * Set whether the TextView includes extra top and bottom padding to make 6422 * room for accents that go above the normal ascent and descent. 6423 * The default is true. 6424 * 6425 * @attr ref android.R.styleable#TextView_includeFontPadding 6426 */ 6427 public void setIncludeFontPadding(boolean includepad) { 6428 if (mIncludePad != includepad) { 6429 mIncludePad = includepad; 6430 6431 if (mLayout != null) { 6432 nullLayouts(); 6433 requestLayout(); 6434 invalidate(); 6435 } 6436 } 6437 } 6438 6439 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 6440 6441 @Override 6442 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6443 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6444 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6445 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6446 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6447 6448 int width; 6449 int height; 6450 6451 BoringLayout.Metrics boring = UNKNOWN_BORING; 6452 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 6453 6454 if (mTextDir == null) { 6455 resolveTextDirection(); 6456 } 6457 6458 int des = -1; 6459 boolean fromexisting = false; 6460 6461 if (widthMode == MeasureSpec.EXACTLY) { 6462 // Parent has told us how big to be. So be it. 6463 width = widthSize; 6464 } else { 6465 if (mLayout != null && mEllipsize == null) { 6466 des = desired(mLayout); 6467 } 6468 6469 if (des < 0) { 6470 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6471 if (boring != null) { 6472 mBoring = boring; 6473 } 6474 } else { 6475 fromexisting = true; 6476 } 6477 6478 if (boring == null || boring == UNKNOWN_BORING) { 6479 if (des < 0) { 6480 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 6481 } 6482 6483 width = des; 6484 } else { 6485 width = boring.width; 6486 } 6487 6488 final Drawables dr = mDrawables; 6489 if (dr != null) { 6490 width = Math.max(width, dr.mDrawableWidthTop); 6491 width = Math.max(width, dr.mDrawableWidthBottom); 6492 } 6493 6494 if (mHint != null) { 6495 int hintDes = -1; 6496 int hintWidth; 6497 6498 if (mHintLayout != null && mEllipsize == null) { 6499 hintDes = desired(mHintLayout); 6500 } 6501 6502 if (hintDes < 0) { 6503 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 6504 if (hintBoring != null) { 6505 mHintBoring = hintBoring; 6506 } 6507 } 6508 6509 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 6510 if (hintDes < 0) { 6511 hintDes = (int) FloatMath.ceil( 6512 Layout.getDesiredWidth(mHint, mTextPaint)); 6513 } 6514 6515 hintWidth = hintDes; 6516 } else { 6517 hintWidth = hintBoring.width; 6518 } 6519 6520 if (hintWidth > width) { 6521 width = hintWidth; 6522 } 6523 } 6524 6525 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 6526 6527 if (mMaxWidthMode == EMS) { 6528 width = Math.min(width, mMaxWidth * getLineHeight()); 6529 } else { 6530 width = Math.min(width, mMaxWidth); 6531 } 6532 6533 if (mMinWidthMode == EMS) { 6534 width = Math.max(width, mMinWidth * getLineHeight()); 6535 } else { 6536 width = Math.max(width, mMinWidth); 6537 } 6538 6539 // Check against our minimum width 6540 width = Math.max(width, getSuggestedMinimumWidth()); 6541 6542 if (widthMode == MeasureSpec.AT_MOST) { 6543 width = Math.min(widthSize, width); 6544 } 6545 } 6546 6547 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6548 int unpaddedWidth = want; 6549 6550 if (mHorizontallyScrolling) want = VERY_WIDE; 6551 6552 int hintWant = want; 6553 int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth(); 6554 6555 if (mLayout == null) { 6556 makeNewLayout(want, hintWant, boring, hintBoring, 6557 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6558 } else { 6559 final boolean layoutChanged = (mLayout.getWidth() != want) || 6560 (hintWidth != hintWant) || 6561 (mLayout.getEllipsizedWidth() != 6562 width - getCompoundPaddingLeft() - getCompoundPaddingRight()); 6563 6564 final boolean widthChanged = (mHint == null) && 6565 (mEllipsize == null) && 6566 (want > mLayout.getWidth()) && 6567 (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want)); 6568 6569 final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum); 6570 6571 if (layoutChanged || maximumChanged) { 6572 if (!maximumChanged && widthChanged) { 6573 mLayout.increaseWidthTo(want); 6574 } else { 6575 makeNewLayout(want, hintWant, boring, hintBoring, 6576 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6577 } 6578 } else { 6579 // Nothing has changed 6580 } 6581 } 6582 6583 if (heightMode == MeasureSpec.EXACTLY) { 6584 // Parent has told us how big to be. So be it. 6585 height = heightSize; 6586 mDesiredHeightAtMeasure = -1; 6587 } else { 6588 int desired = getDesiredHeight(); 6589 6590 height = desired; 6591 mDesiredHeightAtMeasure = desired; 6592 6593 if (heightMode == MeasureSpec.AT_MOST) { 6594 height = Math.min(desired, heightSize); 6595 } 6596 } 6597 6598 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 6599 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 6600 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 6601 } 6602 6603 /* 6604 * We didn't let makeNewLayout() register to bring the cursor into view, 6605 * so do it here if there is any possibility that it is needed. 6606 */ 6607 if (mMovement != null || 6608 mLayout.getWidth() > unpaddedWidth || 6609 mLayout.getHeight() > unpaddedHeight) { 6610 registerForPreDraw(); 6611 } else { 6612 scrollTo(0, 0); 6613 } 6614 6615 setMeasuredDimension(width, height); 6616 } 6617 6618 private int getDesiredHeight() { 6619 return Math.max( 6620 getDesiredHeight(mLayout, true), 6621 getDesiredHeight(mHintLayout, mEllipsize != null)); 6622 } 6623 6624 private int getDesiredHeight(Layout layout, boolean cap) { 6625 if (layout == null) { 6626 return 0; 6627 } 6628 6629 int linecount = layout.getLineCount(); 6630 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 6631 int desired = layout.getLineTop(linecount); 6632 6633 final Drawables dr = mDrawables; 6634 if (dr != null) { 6635 desired = Math.max(desired, dr.mDrawableHeightLeft); 6636 desired = Math.max(desired, dr.mDrawableHeightRight); 6637 } 6638 6639 desired += pad; 6640 6641 if (mMaxMode == LINES) { 6642 /* 6643 * Don't cap the hint to a certain number of lines. 6644 * (Do cap it, though, if we have a maximum pixel height.) 6645 */ 6646 if (cap) { 6647 if (linecount > mMaximum) { 6648 desired = layout.getLineTop(mMaximum); 6649 6650 if (dr != null) { 6651 desired = Math.max(desired, dr.mDrawableHeightLeft); 6652 desired = Math.max(desired, dr.mDrawableHeightRight); 6653 } 6654 6655 desired += pad; 6656 linecount = mMaximum; 6657 } 6658 } 6659 } else { 6660 desired = Math.min(desired, mMaximum); 6661 } 6662 6663 if (mMinMode == LINES) { 6664 if (linecount < mMinimum) { 6665 desired += getLineHeight() * (mMinimum - linecount); 6666 } 6667 } else { 6668 desired = Math.max(desired, mMinimum); 6669 } 6670 6671 // Check against our minimum height 6672 desired = Math.max(desired, getSuggestedMinimumHeight()); 6673 6674 return desired; 6675 } 6676 6677 /** 6678 * Check whether a change to the existing text layout requires a 6679 * new view layout. 6680 */ 6681 private void checkForResize() { 6682 boolean sizeChanged = false; 6683 6684 if (mLayout != null) { 6685 // Check if our width changed 6686 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 6687 sizeChanged = true; 6688 invalidate(); 6689 } 6690 6691 // Check if our height changed 6692 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 6693 int desiredHeight = getDesiredHeight(); 6694 6695 if (desiredHeight != this.getHeight()) { 6696 sizeChanged = true; 6697 } 6698 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 6699 if (mDesiredHeightAtMeasure >= 0) { 6700 int desiredHeight = getDesiredHeight(); 6701 6702 if (desiredHeight != mDesiredHeightAtMeasure) { 6703 sizeChanged = true; 6704 } 6705 } 6706 } 6707 } 6708 6709 if (sizeChanged) { 6710 requestLayout(); 6711 // caller will have already invalidated 6712 } 6713 } 6714 6715 /** 6716 * Check whether entirely new text requires a new view layout 6717 * or merely a new text layout. 6718 */ 6719 private void checkForRelayout() { 6720 // If we have a fixed width, we can just swap in a new text layout 6721 // if the text height stays the same or if the view height is fixed. 6722 6723 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 6724 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 6725 (mHint == null || mHintLayout != null) && 6726 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 6727 // Static width, so try making a new text layout. 6728 6729 int oldht = mLayout.getHeight(); 6730 int want = mLayout.getWidth(); 6731 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 6732 6733 /* 6734 * No need to bring the text into view, since the size is not 6735 * changing (unless we do the requestLayout(), in which case it 6736 * will happen at measure). 6737 */ 6738 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 6739 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 6740 false); 6741 6742 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 6743 // In a fixed-height view, so use our new text layout. 6744 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 6745 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 6746 invalidate(); 6747 return; 6748 } 6749 6750 // Dynamic height, but height has stayed the same, 6751 // so use our new text layout. 6752 if (mLayout.getHeight() == oldht && 6753 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 6754 invalidate(); 6755 return; 6756 } 6757 } 6758 6759 // We lose: the height has changed and we have a dynamic height. 6760 // Request a new view layout using our new text layout. 6761 requestLayout(); 6762 invalidate(); 6763 } else { 6764 // Dynamic width, so we have no choice but to request a new 6765 // view layout with a new text layout. 6766 nullLayouts(); 6767 requestLayout(); 6768 invalidate(); 6769 } 6770 } 6771 6772 @Override 6773 protected void onLayout(boolean changed, int left, int top, int right, int bottom) { 6774 super.onLayout(changed, left, top, right, bottom); 6775 if (changed) mTextDisplayListIsValid = false; 6776 } 6777 6778 /** 6779 * Returns true if anything changed. 6780 */ 6781 private boolean bringTextIntoView() { 6782 int line = 0; 6783 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6784 line = mLayout.getLineCount() - 1; 6785 } 6786 6787 Layout.Alignment a = mLayout.getParagraphAlignment(line); 6788 int dir = mLayout.getParagraphDirection(line); 6789 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6790 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6791 int ht = mLayout.getHeight(); 6792 6793 int scrollx, scrolly; 6794 6795 // Convert to left, center, or right alignment. 6796 if (a == Layout.Alignment.ALIGN_NORMAL) { 6797 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT : 6798 Layout.Alignment.ALIGN_RIGHT; 6799 } else if (a == Layout.Alignment.ALIGN_OPPOSITE){ 6800 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT : 6801 Layout.Alignment.ALIGN_LEFT; 6802 } 6803 6804 if (a == Layout.Alignment.ALIGN_CENTER) { 6805 /* 6806 * Keep centered if possible, or, if it is too wide to fit, 6807 * keep leading edge in view. 6808 */ 6809 6810 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6811 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6812 6813 if (right - left < hspace) { 6814 scrollx = (right + left) / 2 - hspace / 2; 6815 } else { 6816 if (dir < 0) { 6817 scrollx = right - hspace; 6818 } else { 6819 scrollx = left; 6820 } 6821 } 6822 } else if (a == Layout.Alignment.ALIGN_RIGHT) { 6823 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6824 scrollx = right - hspace; 6825 } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) 6826 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6827 } 6828 6829 if (ht < vspace) { 6830 scrolly = 0; 6831 } else { 6832 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6833 scrolly = ht - vspace; 6834 } else { 6835 scrolly = 0; 6836 } 6837 } 6838 6839 if (scrollx != mScrollX || scrolly != mScrollY) { 6840 scrollTo(scrollx, scrolly); 6841 return true; 6842 } else { 6843 return false; 6844 } 6845 } 6846 6847 /** 6848 * Move the point, specified by the offset, into the view if it is needed. 6849 * This has to be called after layout. Returns true if anything changed. 6850 */ 6851 public boolean bringPointIntoView(int offset) { 6852 boolean changed = false; 6853 6854 if (mLayout == null) return changed; 6855 6856 int line = mLayout.getLineForOffset(offset); 6857 6858 // FIXME: Is it okay to truncate this, or should we round? 6859 final int x = (int)mLayout.getPrimaryHorizontal(offset); 6860 final int top = mLayout.getLineTop(line); 6861 final int bottom = mLayout.getLineTop(line + 1); 6862 6863 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6864 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6865 int ht = mLayout.getHeight(); 6866 6867 int grav; 6868 6869 switch (mLayout.getParagraphAlignment(line)) { 6870 case ALIGN_LEFT: 6871 grav = 1; 6872 break; 6873 case ALIGN_RIGHT: 6874 grav = -1; 6875 break; 6876 case ALIGN_NORMAL: 6877 grav = mLayout.getParagraphDirection(line); 6878 break; 6879 case ALIGN_OPPOSITE: 6880 grav = -mLayout.getParagraphDirection(line); 6881 break; 6882 case ALIGN_CENTER: 6883 default: 6884 grav = 0; 6885 break; 6886 } 6887 6888 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6889 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6890 6891 int hslack = (bottom - top) / 2; 6892 int vslack = hslack; 6893 6894 if (vslack > vspace / 4) 6895 vslack = vspace / 4; 6896 if (hslack > hspace / 4) 6897 hslack = hspace / 4; 6898 6899 int hs = mScrollX; 6900 int vs = mScrollY; 6901 6902 if (top - vs < vslack) 6903 vs = top - vslack; 6904 if (bottom - vs > vspace - vslack) 6905 vs = bottom - (vspace - vslack); 6906 if (ht - vs < vspace) 6907 vs = ht - vspace; 6908 if (0 - vs > 0) 6909 vs = 0; 6910 6911 if (grav != 0) { 6912 if (x - hs < hslack) { 6913 hs = x - hslack; 6914 } 6915 if (x - hs > hspace - hslack) { 6916 hs = x - (hspace - hslack); 6917 } 6918 } 6919 6920 if (grav < 0) { 6921 if (left - hs > 0) 6922 hs = left; 6923 if (right - hs < hspace) 6924 hs = right - hspace; 6925 } else if (grav > 0) { 6926 if (right - hs < hspace) 6927 hs = right - hspace; 6928 if (left - hs > 0) 6929 hs = left; 6930 } else /* grav == 0 */ { 6931 if (right - left <= hspace) { 6932 /* 6933 * If the entire text fits, center it exactly. 6934 */ 6935 hs = left - (hspace - (right - left)) / 2; 6936 } else if (x > right - hslack) { 6937 /* 6938 * If we are near the right edge, keep the right edge 6939 * at the edge of the view. 6940 */ 6941 hs = right - hspace; 6942 } else if (x < left + hslack) { 6943 /* 6944 * If we are near the left edge, keep the left edge 6945 * at the edge of the view. 6946 */ 6947 hs = left; 6948 } else if (left > hs) { 6949 /* 6950 * Is there whitespace visible at the left? Fix it if so. 6951 */ 6952 hs = left; 6953 } else if (right < hs + hspace) { 6954 /* 6955 * Is there whitespace visible at the right? Fix it if so. 6956 */ 6957 hs = right - hspace; 6958 } else { 6959 /* 6960 * Otherwise, float as needed. 6961 */ 6962 if (x - hs < hslack) { 6963 hs = x - hslack; 6964 } 6965 if (x - hs > hspace - hslack) { 6966 hs = x - (hspace - hslack); 6967 } 6968 } 6969 } 6970 6971 if (hs != mScrollX || vs != mScrollY) { 6972 if (mScroller == null) { 6973 scrollTo(hs, vs); 6974 } else { 6975 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6976 int dx = hs - mScrollX; 6977 int dy = vs - mScrollY; 6978 6979 if (duration > ANIMATED_SCROLL_GAP) { 6980 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6981 awakenScrollBars(mScroller.getDuration()); 6982 invalidate(); 6983 } else { 6984 if (!mScroller.isFinished()) { 6985 mScroller.abortAnimation(); 6986 } 6987 6988 scrollBy(dx, dy); 6989 } 6990 6991 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6992 } 6993 6994 changed = true; 6995 } 6996 6997 if (isFocused()) { 6998 // This offsets because getInterestingRect() is in terms of viewport coordinates, but 6999 // requestRectangleOnScreen() is in terms of content coordinates. 7000 7001 if (mTempRect == null) mTempRect = new Rect(); 7002 // The offsets here are to ensure the rectangle we are using is 7003 // within our view bounds, in case the cursor is on the far left 7004 // or right. If it isn't withing the bounds, then this request 7005 // will be ignored. 7006 mTempRect.set(x - 2, top, x + 2, bottom); 7007 getInterestingRect(mTempRect, line); 7008 mTempRect.offset(mScrollX, mScrollY); 7009 7010 if (requestRectangleOnScreen(mTempRect)) { 7011 changed = true; 7012 } 7013 } 7014 7015 return changed; 7016 } 7017 7018 /** 7019 * Move the cursor, if needed, so that it is at an offset that is visible 7020 * to the user. This will not move the cursor if it represents more than 7021 * one character (a selection range). This will only work if the 7022 * TextView contains spannable text; otherwise it will do nothing. 7023 * 7024 * @return True if the cursor was actually moved, false otherwise. 7025 */ 7026 public boolean moveCursorToVisibleOffset() { 7027 if (!(mText instanceof Spannable)) { 7028 return false; 7029 } 7030 int start = getSelectionStart(); 7031 int end = getSelectionEnd(); 7032 if (start != end) { 7033 return false; 7034 } 7035 7036 // First: make sure the line is visible on screen: 7037 7038 int line = mLayout.getLineForOffset(start); 7039 7040 final int top = mLayout.getLineTop(line); 7041 final int bottom = mLayout.getLineTop(line + 1); 7042 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 7043 int vslack = (bottom - top) / 2; 7044 if (vslack > vspace / 4) 7045 vslack = vspace / 4; 7046 final int vs = mScrollY; 7047 7048 if (top < (vs+vslack)) { 7049 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 7050 } else if (bottom > (vspace+vs-vslack)) { 7051 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 7052 } 7053 7054 // Next: make sure the character is visible on screen: 7055 7056 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 7057 final int hs = mScrollX; 7058 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 7059 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 7060 7061 // line might contain bidirectional text 7062 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 7063 final int highChar = leftChar > rightChar ? leftChar : rightChar; 7064 7065 int newStart = start; 7066 if (newStart < lowChar) { 7067 newStart = lowChar; 7068 } else if (newStart > highChar) { 7069 newStart = highChar; 7070 } 7071 7072 if (newStart != start) { 7073 Selection.setSelection((Spannable)mText, newStart); 7074 return true; 7075 } 7076 7077 return false; 7078 } 7079 7080 @Override 7081 public void computeScroll() { 7082 if (mScroller != null) { 7083 if (mScroller.computeScrollOffset()) { 7084 mScrollX = mScroller.getCurrX(); 7085 mScrollY = mScroller.getCurrY(); 7086 invalidateParentCaches(); 7087 postInvalidate(); // So we draw again 7088 } 7089 } 7090 } 7091 7092 private void getInterestingRect(Rect r, int line) { 7093 convertFromViewportToContentCoordinates(r); 7094 7095 // Rectangle can can be expanded on first and last line to take 7096 // padding into account. 7097 // TODO Take left/right padding into account too? 7098 if (line == 0) r.top -= getExtendedPaddingTop(); 7099 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 7100 } 7101 7102 private void convertFromViewportToContentCoordinates(Rect r) { 7103 final int horizontalOffset = viewportToContentHorizontalOffset(); 7104 r.left += horizontalOffset; 7105 r.right += horizontalOffset; 7106 7107 final int verticalOffset = viewportToContentVerticalOffset(); 7108 r.top += verticalOffset; 7109 r.bottom += verticalOffset; 7110 } 7111 7112 private int viewportToContentHorizontalOffset() { 7113 return getCompoundPaddingLeft() - mScrollX; 7114 } 7115 7116 private int viewportToContentVerticalOffset() { 7117 int offset = getExtendedPaddingTop() - mScrollY; 7118 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 7119 offset += getVerticalOffset(false); 7120 } 7121 return offset; 7122 } 7123 7124 @Override 7125 public void debug(int depth) { 7126 super.debug(depth); 7127 7128 String output = debugIndent(depth); 7129 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 7130 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 7131 + "} "; 7132 7133 if (mText != null) { 7134 7135 output += "mText=\"" + mText + "\" "; 7136 if (mLayout != null) { 7137 output += "mLayout width=" + mLayout.getWidth() 7138 + " height=" + mLayout.getHeight(); 7139 } 7140 } else { 7141 output += "mText=NULL"; 7142 } 7143 Log.d(VIEW_LOG_TAG, output); 7144 } 7145 7146 /** 7147 * Convenience for {@link Selection#getSelectionStart}. 7148 */ 7149 @ViewDebug.ExportedProperty(category = "text") 7150 public int getSelectionStart() { 7151 return Selection.getSelectionStart(getText()); 7152 } 7153 7154 /** 7155 * Convenience for {@link Selection#getSelectionEnd}. 7156 */ 7157 @ViewDebug.ExportedProperty(category = "text") 7158 public int getSelectionEnd() { 7159 return Selection.getSelectionEnd(getText()); 7160 } 7161 7162 /** 7163 * Return true iff there is a selection inside this text view. 7164 */ 7165 public boolean hasSelection() { 7166 final int selectionStart = getSelectionStart(); 7167 final int selectionEnd = getSelectionEnd(); 7168 7169 return selectionStart >= 0 && selectionStart != selectionEnd; 7170 } 7171 7172 /** 7173 * Sets the properties of this field (lines, horizontally scrolling, 7174 * transformation method) to be for a single-line input. 7175 * 7176 * @attr ref android.R.styleable#TextView_singleLine 7177 */ 7178 public void setSingleLine() { 7179 setSingleLine(true); 7180 } 7181 7182 /** 7183 * Sets the properties of this field to transform input to ALL CAPS 7184 * display. This may use a "small caps" formatting if available. 7185 * This setting will be ignored if this field is editable or selectable. 7186 * 7187 * This call replaces the current transformation method. Disabling this 7188 * will not necessarily restore the previous behavior from before this 7189 * was enabled. 7190 * 7191 * @see #setTransformationMethod(TransformationMethod) 7192 * @attr ref android.R.styleable#TextView_textAllCaps 7193 */ 7194 public void setAllCaps(boolean allCaps) { 7195 if (allCaps) { 7196 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 7197 } else { 7198 setTransformationMethod(null); 7199 } 7200 } 7201 7202 /** 7203 * If true, sets the properties of this field (number of lines, horizontally scrolling, 7204 * transformation method) to be for a single-line input; if false, restores these to the default 7205 * conditions. 7206 * 7207 * Note that the default conditions are not necessarily those that were in effect prior this 7208 * method, and you may want to reset these properties to your custom values. 7209 * 7210 * @attr ref android.R.styleable#TextView_singleLine 7211 */ 7212 @android.view.RemotableViewMethod 7213 public void setSingleLine(boolean singleLine) { 7214 // Could be used, but may break backward compatibility. 7215 // if (mSingleLine == singleLine) return; 7216 setInputTypeSingleLine(singleLine); 7217 applySingleLine(singleLine, true, true); 7218 } 7219 7220 /** 7221 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 7222 * @param singleLine 7223 */ 7224 private void setInputTypeSingleLine(boolean singleLine) { 7225 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 7226 if (singleLine) { 7227 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7228 } else { 7229 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7230 } 7231 } 7232 } 7233 7234 private void applySingleLine(boolean singleLine, boolean applyTransformation, 7235 boolean changeMaxLines) { 7236 mSingleLine = singleLine; 7237 if (singleLine) { 7238 setLines(1); 7239 setHorizontallyScrolling(true); 7240 if (applyTransformation) { 7241 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 7242 } 7243 } else { 7244 if (changeMaxLines) { 7245 setMaxLines(Integer.MAX_VALUE); 7246 } 7247 setHorizontallyScrolling(false); 7248 if (applyTransformation) { 7249 setTransformationMethod(null); 7250 } 7251 } 7252 } 7253 7254 /** 7255 * Causes words in the text that are longer than the view is wide 7256 * to be ellipsized instead of broken in the middle. You may also 7257 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 7258 * to constrain the text to a single line. Use <code>null</code> 7259 * to turn off ellipsizing. 7260 * 7261 * If {@link #setMaxLines} has been used to set two or more lines, 7262 * {@link android.text.TextUtils.TruncateAt#END} and 7263 * {@link android.text.TextUtils.TruncateAt#MARQUEE}* are only supported 7264 * (other ellipsizing types will not do anything). 7265 * 7266 * @attr ref android.R.styleable#TextView_ellipsize 7267 */ 7268 public void setEllipsize(TextUtils.TruncateAt where) { 7269 // TruncateAt is an enum. != comparison is ok between these singleton objects. 7270 if (mEllipsize != where) { 7271 mEllipsize = where; 7272 7273 if (mLayout != null) { 7274 nullLayouts(); 7275 requestLayout(); 7276 invalidate(); 7277 } 7278 } 7279 } 7280 7281 /** 7282 * Sets how many times to repeat the marquee animation. Only applied if the 7283 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 7284 * 7285 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 7286 */ 7287 public void setMarqueeRepeatLimit(int marqueeLimit) { 7288 mMarqueeRepeatLimit = marqueeLimit; 7289 } 7290 7291 /** 7292 * Returns where, if anywhere, words that are longer than the view 7293 * is wide should be ellipsized. 7294 */ 7295 @ViewDebug.ExportedProperty 7296 public TextUtils.TruncateAt getEllipsize() { 7297 return mEllipsize; 7298 } 7299 7300 /** 7301 * Set the TextView so that when it takes focus, all the text is 7302 * selected. 7303 * 7304 * @attr ref android.R.styleable#TextView_selectAllOnFocus 7305 */ 7306 @android.view.RemotableViewMethod 7307 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 7308 mSelectAllOnFocus = selectAllOnFocus; 7309 7310 if (selectAllOnFocus && !(mText instanceof Spannable)) { 7311 setText(mText, BufferType.SPANNABLE); 7312 } 7313 } 7314 7315 /** 7316 * Set whether the cursor is visible. The default is true. 7317 * 7318 * @attr ref android.R.styleable#TextView_cursorVisible 7319 */ 7320 @android.view.RemotableViewMethod 7321 public void setCursorVisible(boolean visible) { 7322 if (mCursorVisible != visible) { 7323 mCursorVisible = visible; 7324 invalidate(); 7325 7326 makeBlink(); 7327 7328 // InsertionPointCursorController depends on mCursorVisible 7329 prepareCursorControllers(); 7330 } 7331 } 7332 7333 private boolean isCursorVisible() { 7334 return mCursorVisible && isTextEditable(); 7335 } 7336 7337 private boolean canMarquee() { 7338 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 7339 return width > 0 && (mLayout.getLineWidth(0) > width || 7340 (mMarqueeFadeMode != MARQUEE_FADE_NORMAL && mSavedMarqueeModeLayout != null && 7341 mSavedMarqueeModeLayout.getLineWidth(0) > width)); 7342 } 7343 7344 private void startMarquee() { 7345 // Do not ellipsize EditText 7346 if (mInput != null) return; 7347 7348 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 7349 return; 7350 } 7351 7352 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 7353 getLineCount() == 1 && canMarquee()) { 7354 7355 if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 7356 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_FADE; 7357 final Layout tmp = mLayout; 7358 mLayout = mSavedMarqueeModeLayout; 7359 mSavedMarqueeModeLayout = tmp; 7360 setHorizontalFadingEdgeEnabled(true); 7361 requestLayout(); 7362 invalidate(); 7363 } 7364 7365 if (mMarquee == null) mMarquee = new Marquee(this); 7366 mMarquee.start(mMarqueeRepeatLimit); 7367 } 7368 } 7369 7370 private void stopMarquee() { 7371 if (mMarquee != null && !mMarquee.isStopped()) { 7372 mMarquee.stop(); 7373 } 7374 7375 if (mMarqueeFadeMode == MARQUEE_FADE_SWITCH_SHOW_FADE) { 7376 mMarqueeFadeMode = MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS; 7377 final Layout tmp = mSavedMarqueeModeLayout; 7378 mSavedMarqueeModeLayout = mLayout; 7379 mLayout = tmp; 7380 setHorizontalFadingEdgeEnabled(false); 7381 requestLayout(); 7382 invalidate(); 7383 } 7384 } 7385 7386 private void startStopMarquee(boolean start) { 7387 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7388 if (start) { 7389 startMarquee(); 7390 } else { 7391 stopMarquee(); 7392 } 7393 } 7394 } 7395 7396 private static final class Marquee extends Handler { 7397 // TODO: Add an option to configure this 7398 private static final float MARQUEE_DELTA_MAX = 0.07f; 7399 private static final int MARQUEE_DELAY = 1200; 7400 private static final int MARQUEE_RESTART_DELAY = 1200; 7401 private static final int MARQUEE_RESOLUTION = 1000 / 30; 7402 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 7403 7404 private static final byte MARQUEE_STOPPED = 0x0; 7405 private static final byte MARQUEE_STARTING = 0x1; 7406 private static final byte MARQUEE_RUNNING = 0x2; 7407 7408 private static final int MESSAGE_START = 0x1; 7409 private static final int MESSAGE_TICK = 0x2; 7410 private static final int MESSAGE_RESTART = 0x3; 7411 7412 private final WeakReference<TextView> mView; 7413 7414 private byte mStatus = MARQUEE_STOPPED; 7415 private final float mScrollUnit; 7416 private float mMaxScroll; 7417 float mMaxFadeScroll; 7418 private float mGhostStart; 7419 private float mGhostOffset; 7420 private float mFadeStop; 7421 private int mRepeatLimit; 7422 7423 float mScroll; 7424 7425 Marquee(TextView v) { 7426 final float density = v.getContext().getResources().getDisplayMetrics().density; 7427 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 7428 mView = new WeakReference<TextView>(v); 7429 } 7430 7431 @Override 7432 public void handleMessage(Message msg) { 7433 switch (msg.what) { 7434 case MESSAGE_START: 7435 mStatus = MARQUEE_RUNNING; 7436 tick(); 7437 break; 7438 case MESSAGE_TICK: 7439 tick(); 7440 break; 7441 case MESSAGE_RESTART: 7442 if (mStatus == MARQUEE_RUNNING) { 7443 if (mRepeatLimit >= 0) { 7444 mRepeatLimit--; 7445 } 7446 start(mRepeatLimit); 7447 } 7448 break; 7449 } 7450 } 7451 7452 void tick() { 7453 if (mStatus != MARQUEE_RUNNING) { 7454 return; 7455 } 7456 7457 removeMessages(MESSAGE_TICK); 7458 7459 final TextView textView = mView.get(); 7460 if (textView != null && (textView.isFocused() || textView.isSelected())) { 7461 mScroll += mScrollUnit; 7462 if (mScroll > mMaxScroll) { 7463 mScroll = mMaxScroll; 7464 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 7465 } else { 7466 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 7467 } 7468 textView.invalidate(); 7469 } 7470 } 7471 7472 void stop() { 7473 mStatus = MARQUEE_STOPPED; 7474 removeMessages(MESSAGE_START); 7475 removeMessages(MESSAGE_RESTART); 7476 removeMessages(MESSAGE_TICK); 7477 resetScroll(); 7478 } 7479 7480 private void resetScroll() { 7481 mScroll = 0.0f; 7482 final TextView textView = mView.get(); 7483 if (textView != null) textView.invalidate(); 7484 } 7485 7486 void start(int repeatLimit) { 7487 if (repeatLimit == 0) { 7488 stop(); 7489 return; 7490 } 7491 mRepeatLimit = repeatLimit; 7492 final TextView textView = mView.get(); 7493 if (textView != null && textView.mLayout != null) { 7494 mStatus = MARQUEE_STARTING; 7495 mScroll = 0.0f; 7496 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 7497 textView.getCompoundPaddingRight(); 7498 final float lineWidth = textView.mLayout.getLineWidth(0); 7499 final float gap = textWidth / 3.0f; 7500 mGhostStart = lineWidth - textWidth + gap; 7501 mMaxScroll = mGhostStart + textWidth; 7502 mGhostOffset = lineWidth + gap; 7503 mFadeStop = lineWidth + textWidth / 6.0f; 7504 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 7505 7506 textView.invalidate(); 7507 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 7508 } 7509 } 7510 7511 float getGhostOffset() { 7512 return mGhostOffset; 7513 } 7514 7515 boolean shouldDrawLeftFade() { 7516 return mScroll <= mFadeStop; 7517 } 7518 7519 boolean shouldDrawGhost() { 7520 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 7521 } 7522 7523 boolean isRunning() { 7524 return mStatus == MARQUEE_RUNNING; 7525 } 7526 7527 boolean isStopped() { 7528 return mStatus == MARQUEE_STOPPED; 7529 } 7530 } 7531 7532 /** 7533 * This method is called when the text is changed, in case any subclasses 7534 * would like to know. 7535 * 7536 * Within <code>text</code>, the <code>lengthAfter</code> characters 7537 * beginning at <code>start</code> have just replaced old text that had 7538 * length <code>lengthBefore</code>. It is an error to attempt to make 7539 * changes to <code>text</code> from this callback. 7540 * 7541 * @param text The text the TextView is displaying 7542 * @param start The offset of the start of the range of the text that was 7543 * modified 7544 * @param lengthBefore The length of the former text that has been replaced 7545 * @param lengthAfter The length of the replacement modified text 7546 */ 7547 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 7548 // intentionally empty, template pattern method can be overridden by subclasses 7549 } 7550 7551 /** 7552 * This method is called when the selection has changed, in case any 7553 * subclasses would like to know. 7554 * 7555 * @param selStart The new selection start location. 7556 * @param selEnd The new selection end location. 7557 */ 7558 protected void onSelectionChanged(int selStart, int selEnd) { 7559 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7560 mTextDisplayListIsValid = false; 7561 } 7562 7563 /** 7564 * Adds a TextWatcher to the list of those whose methods are called 7565 * whenever this TextView's text changes. 7566 * <p> 7567 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 7568 * not called after {@link #setText} calls. Now, doing {@link #setText} 7569 * if there are any text changed listeners forces the buffer type to 7570 * Editable if it would not otherwise be and does call this method. 7571 */ 7572 public void addTextChangedListener(TextWatcher watcher) { 7573 if (mListeners == null) { 7574 mListeners = new ArrayList<TextWatcher>(); 7575 } 7576 7577 mListeners.add(watcher); 7578 } 7579 7580 /** 7581 * Removes the specified TextWatcher from the list of those whose 7582 * methods are called 7583 * whenever this TextView's text changes. 7584 */ 7585 public void removeTextChangedListener(TextWatcher watcher) { 7586 if (mListeners != null) { 7587 int i = mListeners.indexOf(watcher); 7588 7589 if (i >= 0) { 7590 mListeners.remove(i); 7591 } 7592 } 7593 } 7594 7595 private void sendBeforeTextChanged(CharSequence text, int start, int before, int after) { 7596 if (mListeners != null) { 7597 final ArrayList<TextWatcher> list = mListeners; 7598 final int count = list.size(); 7599 for (int i = 0; i < count; i++) { 7600 list.get(i).beforeTextChanged(text, start, before, after); 7601 } 7602 } 7603 7604 // The spans that are inside or intersect the modified region no longer make sense 7605 removeIntersectingSpans(start, start + before, SpellCheckSpan.class); 7606 removeIntersectingSpans(start, start + before, SuggestionSpan.class); 7607 } 7608 7609 // Removes all spans that are inside or actually overlap the start..end range 7610 private <T> void removeIntersectingSpans(int start, int end, Class<T> type) { 7611 if (!(mText instanceof Editable)) return; 7612 Editable text = (Editable) mText; 7613 7614 T[] spans = text.getSpans(start, end, type); 7615 final int length = spans.length; 7616 for (int i = 0; i < length; i++) { 7617 final int s = text.getSpanStart(spans[i]); 7618 final int e = text.getSpanEnd(spans[i]); 7619 // Spans that are adjacent to the edited region will be handled in 7620 // updateSpellCheckSpans. Result depends on what will be added (space or text) 7621 if (e == start || s == end) break; 7622 text.removeSpan(spans[i]); 7623 } 7624 } 7625 7626 /** 7627 * Not private so it can be called from an inner class without going 7628 * through a thunk. 7629 */ 7630 void sendOnTextChanged(CharSequence text, int start, int before, int after) { 7631 if (mListeners != null) { 7632 final ArrayList<TextWatcher> list = mListeners; 7633 final int count = list.size(); 7634 for (int i = 0; i < count; i++) { 7635 list.get(i).onTextChanged(text, start, before, after); 7636 } 7637 } 7638 7639 updateSpellCheckSpans(start, start + after, false); 7640 mTextDisplayListIsValid = false; 7641 7642 // Hide the controllers as soon as text is modified (typing, procedural...) 7643 // We do not hide the span controllers, since they can be added when a new text is 7644 // inserted into the text view (voice IME). 7645 hideCursorControllers(); 7646 } 7647 7648 /** 7649 * Not private so it can be called from an inner class without going 7650 * through a thunk. 7651 */ 7652 void sendAfterTextChanged(Editable text) { 7653 if (mListeners != null) { 7654 final ArrayList<TextWatcher> list = mListeners; 7655 final int count = list.size(); 7656 for (int i = 0; i < count; i++) { 7657 list.get(i).afterTextChanged(text); 7658 } 7659 } 7660 } 7661 7662 /** 7663 * Not private so it can be called from an inner class without going 7664 * through a thunk. 7665 */ 7666 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 7667 final InputMethodState ims = mInputMethodState; 7668 if (ims == null || ims.mBatchEditNesting == 0) { 7669 updateAfterEdit(); 7670 } 7671 if (ims != null) { 7672 ims.mContentChanged = true; 7673 if (ims.mChangedStart < 0) { 7674 ims.mChangedStart = start; 7675 ims.mChangedEnd = start+before; 7676 } else { 7677 ims.mChangedStart = Math.min(ims.mChangedStart, start); 7678 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 7679 } 7680 ims.mChangedDelta += after-before; 7681 } 7682 7683 sendOnTextChanged(buffer, start, before, after); 7684 onTextChanged(buffer, start, before, after); 7685 } 7686 7687 /** 7688 * Not private so it can be called from an inner class without going 7689 * through a thunk. 7690 */ 7691 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 7692 // XXX Make the start and end move together if this ends up 7693 // spending too much time invalidating. 7694 7695 boolean selChanged = false; 7696 int newSelStart=-1, newSelEnd=-1; 7697 7698 final InputMethodState ims = mInputMethodState; 7699 7700 if (what == Selection.SELECTION_END) { 7701 mHighlightPathBogus = true; 7702 selChanged = true; 7703 newSelEnd = newStart; 7704 7705 if (!isFocused()) { 7706 mSelectionMoved = true; 7707 } 7708 7709 if (oldStart >= 0 || newStart >= 0) { 7710 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 7711 registerForPreDraw(); 7712 makeBlink(); 7713 } 7714 } 7715 7716 if (what == Selection.SELECTION_START) { 7717 mHighlightPathBogus = true; 7718 selChanged = true; 7719 newSelStart = newStart; 7720 7721 if (!isFocused()) { 7722 mSelectionMoved = true; 7723 } 7724 7725 if (oldStart >= 0 || newStart >= 0) { 7726 int end = Selection.getSelectionEnd(buf); 7727 invalidateCursor(end, oldStart, newStart); 7728 } 7729 } 7730 7731 if (selChanged) { 7732 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 7733 if (newSelStart < 0) { 7734 newSelStart = Selection.getSelectionStart(buf); 7735 } 7736 if (newSelEnd < 0) { 7737 newSelEnd = Selection.getSelectionEnd(buf); 7738 } 7739 onSelectionChanged(newSelStart, newSelEnd); 7740 } 7741 } 7742 7743 if (what instanceof UpdateAppearance || what instanceof ParagraphStyle || 7744 what instanceof CharacterStyle) { 7745 if (ims == null || ims.mBatchEditNesting == 0) { 7746 invalidate(); 7747 mHighlightPathBogus = true; 7748 checkForResize(); 7749 } else { 7750 ims.mContentChanged = true; 7751 } 7752 mTextDisplayListIsValid = false; 7753 } 7754 7755 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 7756 mHighlightPathBogus = true; 7757 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 7758 ims.mSelectionModeChanged = true; 7759 } 7760 7761 if (Selection.getSelectionStart(buf) >= 0) { 7762 if (ims == null || ims.mBatchEditNesting == 0) { 7763 invalidateCursor(); 7764 } else { 7765 ims.mCursorChanged = true; 7766 } 7767 } 7768 } 7769 7770 if (what instanceof ParcelableSpan) { 7771 // If this is a span that can be sent to a remote process, 7772 // the current extract editor would be interested in it. 7773 if (ims != null && ims.mExtracting != null) { 7774 if (ims.mBatchEditNesting != 0) { 7775 if (oldStart >= 0) { 7776 if (ims.mChangedStart > oldStart) { 7777 ims.mChangedStart = oldStart; 7778 } 7779 if (ims.mChangedStart > oldEnd) { 7780 ims.mChangedStart = oldEnd; 7781 } 7782 } 7783 if (newStart >= 0) { 7784 if (ims.mChangedStart > newStart) { 7785 ims.mChangedStart = newStart; 7786 } 7787 if (ims.mChangedStart > newEnd) { 7788 ims.mChangedStart = newEnd; 7789 } 7790 } 7791 } else { 7792 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 7793 + oldStart + "-" + oldEnd + "," 7794 + newStart + "-" + newEnd + what); 7795 ims.mContentChanged = true; 7796 } 7797 } 7798 } 7799 7800 if (mSpellChecker != null && newStart < 0 && what instanceof SpellCheckSpan) { 7801 mSpellChecker.removeSpellCheckSpan((SpellCheckSpan) what); 7802 } 7803 } 7804 7805 /** 7806 * Create new SpellCheckSpans on the modified region. 7807 */ 7808 private void updateSpellCheckSpans(int start, int end, boolean createSpellChecker) { 7809 if (isTextEditable() && isSuggestionsEnabled() && !(this instanceof ExtractEditText)) { 7810 if (mSpellChecker == null && createSpellChecker) { 7811 mSpellChecker = new SpellChecker(this); 7812 } 7813 if (mSpellChecker != null) { 7814 mSpellChecker.spellCheck(start, end); 7815 } 7816 } 7817 } 7818 7819 /** 7820 * Controls the {@link EasyEditSpan} monitoring when it is added, and when the related 7821 * pop-up should be displayed. 7822 */ 7823 private class EasyEditSpanController { 7824 7825 private static final int DISPLAY_TIMEOUT_MS = 3000; // 3 secs 7826 7827 private EasyEditPopupWindow mPopupWindow; 7828 7829 private EasyEditSpan mEasyEditSpan; 7830 7831 private Runnable mHidePopup; 7832 7833 private void hide() { 7834 if (mPopupWindow != null) { 7835 mPopupWindow.hide(); 7836 TextView.this.removeCallbacks(mHidePopup); 7837 } 7838 removeSpans(mText); 7839 mEasyEditSpan = null; 7840 } 7841 7842 /** 7843 * Monitors the changes in the text. 7844 * 7845 * <p>{@link ChangeWatcher#onSpanAdded(Spannable, Object, int, int)} cannot be used, 7846 * as the notifications are not sent when a spannable (with spans) is inserted. 7847 */ 7848 public void onTextChange(CharSequence buffer) { 7849 adjustSpans(mText); 7850 7851 if (getWindowVisibility() != View.VISIBLE) { 7852 // The window is not visible yet, ignore the text change. 7853 return; 7854 } 7855 7856 if (mLayout == null) { 7857 // The view has not been layout yet, ignore the text change 7858 return; 7859 } 7860 7861 InputMethodManager imm = InputMethodManager.peekInstance(); 7862 if (!(TextView.this instanceof ExtractEditText) 7863 && imm != null && imm.isFullscreenMode()) { 7864 // The input is in extract mode. We do not have to handle the easy edit in the 7865 // original TextView, as the ExtractEditText will do 7866 return; 7867 } 7868 7869 // Remove the current easy edit span, as the text changed, and remove the pop-up 7870 // (if any) 7871 if (mEasyEditSpan != null) { 7872 if (mText instanceof Spannable) { 7873 ((Spannable) mText).removeSpan(mEasyEditSpan); 7874 } 7875 mEasyEditSpan = null; 7876 } 7877 if (mPopupWindow != null && mPopupWindow.isShowing()) { 7878 mPopupWindow.hide(); 7879 } 7880 7881 // Display the new easy edit span (if any). 7882 if (buffer instanceof Spanned) { 7883 mEasyEditSpan = getSpan((Spanned) buffer); 7884 if (mEasyEditSpan != null) { 7885 if (mPopupWindow == null) { 7886 mPopupWindow = new EasyEditPopupWindow(); 7887 mHidePopup = new Runnable() { 7888 @Override 7889 public void run() { 7890 hide(); 7891 } 7892 }; 7893 } 7894 mPopupWindow.show(mEasyEditSpan); 7895 TextView.this.removeCallbacks(mHidePopup); 7896 TextView.this.postDelayed(mHidePopup, DISPLAY_TIMEOUT_MS); 7897 } 7898 } 7899 } 7900 7901 /** 7902 * Adjusts the spans by removing all of them except the last one. 7903 */ 7904 private void adjustSpans(CharSequence buffer) { 7905 // This method enforces that only one easy edit span is attached to the text. 7906 // A better way to enforce this would be to listen for onSpanAdded, but this method 7907 // cannot be used in this scenario as no notification is triggered when a text with 7908 // spans is inserted into a text. 7909 if (buffer instanceof Spannable) { 7910 Spannable spannable = (Spannable) buffer; 7911 EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(), 7912 EasyEditSpan.class); 7913 for (int i = 0; i < spans.length - 1; i++) { 7914 spannable.removeSpan(spans[i]); 7915 } 7916 } 7917 } 7918 7919 /** 7920 * Removes all the {@link EasyEditSpan} currently attached. 7921 */ 7922 private void removeSpans(CharSequence buffer) { 7923 if (buffer instanceof Spannable) { 7924 Spannable spannable = (Spannable) buffer; 7925 EasyEditSpan[] spans = spannable.getSpans(0, spannable.length(), 7926 EasyEditSpan.class); 7927 for (int i = 0; i < spans.length; i++) { 7928 spannable.removeSpan(spans[i]); 7929 } 7930 } 7931 } 7932 7933 private EasyEditSpan getSpan(Spanned spanned) { 7934 EasyEditSpan[] easyEditSpans = spanned.getSpans(0, spanned.length(), 7935 EasyEditSpan.class); 7936 if (easyEditSpans.length == 0) { 7937 return null; 7938 } else { 7939 return easyEditSpans[0]; 7940 } 7941 } 7942 } 7943 7944 /** 7945 * Displays the actions associated to an {@link EasyEditSpan}. The pop-up is controlled 7946 * by {@link EasyEditSpanController}. 7947 */ 7948 private class EasyEditPopupWindow extends PinnedPopupWindow 7949 implements OnClickListener { 7950 private static final int POPUP_TEXT_LAYOUT = 7951 com.android.internal.R.layout.text_edit_action_popup_text; 7952 private TextView mDeleteTextView; 7953 private EasyEditSpan mEasyEditSpan; 7954 7955 @Override 7956 protected void createPopupWindow() { 7957 mPopupWindow = new PopupWindow(TextView.this.mContext, null, 7958 com.android.internal.R.attr.textSelectHandleWindowStyle); 7959 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 7960 mPopupWindow.setClippingEnabled(true); 7961 } 7962 7963 @Override 7964 protected void initContentView() { 7965 LinearLayout linearLayout = new LinearLayout(TextView.this.getContext()); 7966 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 7967 mContentView = linearLayout; 7968 mContentView.setBackgroundResource( 7969 com.android.internal.R.drawable.text_edit_side_paste_window); 7970 7971 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 7972 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 7973 7974 LayoutParams wrapContent = new LayoutParams( 7975 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 7976 7977 mDeleteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 7978 mDeleteTextView.setLayoutParams(wrapContent); 7979 mDeleteTextView.setText(com.android.internal.R.string.delete); 7980 mDeleteTextView.setOnClickListener(this); 7981 mContentView.addView(mDeleteTextView); 7982 } 7983 7984 public void show(EasyEditSpan easyEditSpan) { 7985 mEasyEditSpan = easyEditSpan; 7986 super.show(); 7987 } 7988 7989 @Override 7990 public void onClick(View view) { 7991 if (view == mDeleteTextView) { 7992 Editable editable = (Editable) mText; 7993 int start = editable.getSpanStart(mEasyEditSpan); 7994 int end = editable.getSpanEnd(mEasyEditSpan); 7995 if (start >= 0 && end >= 0) { 7996 deleteText_internal(start, end); 7997 } 7998 } 7999 } 8000 8001 @Override 8002 protected int getTextOffset() { 8003 // Place the pop-up at the end of the span 8004 Editable editable = (Editable) mText; 8005 return editable.getSpanEnd(mEasyEditSpan); 8006 } 8007 8008 @Override 8009 protected int getVerticalLocalPosition(int line) { 8010 return mLayout.getLineBottom(line); 8011 } 8012 8013 @Override 8014 protected int clipVertically(int positionY) { 8015 // As we display the pop-up below the span, no vertical clipping is required. 8016 return positionY; 8017 } 8018 } 8019 8020 private class ChangeWatcher implements TextWatcher, SpanWatcher { 8021 8022 private CharSequence mBeforeText; 8023 8024 private EasyEditSpanController mEasyEditSpanController; 8025 8026 private ChangeWatcher() { 8027 mEasyEditSpanController = new EasyEditSpanController(); 8028 } 8029 8030 public void beforeTextChanged(CharSequence buffer, int start, 8031 int before, int after) { 8032 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 8033 + " before=" + before + " after=" + after + ": " + buffer); 8034 8035 if (AccessibilityManager.getInstance(mContext).isEnabled() 8036 && !isPasswordInputType(mInputType) 8037 && !hasPasswordTransformationMethod()) { 8038 mBeforeText = buffer.toString(); 8039 } 8040 8041 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 8042 } 8043 8044 public void onTextChanged(CharSequence buffer, int start, 8045 int before, int after) { 8046 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 8047 + " before=" + before + " after=" + after + ": " + buffer); 8048 TextView.this.handleTextChanged(buffer, start, before, after); 8049 8050 mEasyEditSpanController.onTextChange(buffer); 8051 8052 if (AccessibilityManager.getInstance(mContext).isEnabled() && 8053 (isFocused() || isSelected() && isShown())) { 8054 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 8055 mBeforeText = null; 8056 } 8057 } 8058 8059 public void afterTextChanged(Editable buffer) { 8060 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 8061 TextView.this.sendAfterTextChanged(buffer); 8062 8063 if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { 8064 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 8065 } 8066 } 8067 8068 public void onSpanChanged(Spannable buf, 8069 Object what, int s, int e, int st, int en) { 8070 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 8071 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 8072 TextView.this.spanChange(buf, what, s, st, e, en); 8073 } 8074 8075 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 8076 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 8077 + " what=" + what + ": " + buf); 8078 TextView.this.spanChange(buf, what, -1, s, -1, e); 8079 } 8080 8081 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 8082 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 8083 + " what=" + what + ": " + buf); 8084 TextView.this.spanChange(buf, what, s, -1, e, -1); 8085 } 8086 8087 private void hideControllers() { 8088 mEasyEditSpanController.hide(); 8089 } 8090 } 8091 8092 /** 8093 * @hide 8094 */ 8095 @Override 8096 public void dispatchFinishTemporaryDetach() { 8097 mDispatchTemporaryDetach = true; 8098 super.dispatchFinishTemporaryDetach(); 8099 mDispatchTemporaryDetach = false; 8100 } 8101 8102 @Override 8103 public void onStartTemporaryDetach() { 8104 super.onStartTemporaryDetach(); 8105 // Only track when onStartTemporaryDetach() is called directly, 8106 // usually because this instance is an editable field in a list 8107 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 8108 8109 // Because of View recycling in ListView, there is no easy way to know when a TextView with 8110 // selection becomes visible again. Until a better solution is found, stop text selection 8111 // mode (if any) as soon as this TextView is recycled. 8112 hideControllers(); 8113 } 8114 8115 @Override 8116 public void onFinishTemporaryDetach() { 8117 super.onFinishTemporaryDetach(); 8118 // Only track when onStartTemporaryDetach() is called directly, 8119 // usually because this instance is an editable field in a list 8120 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 8121 } 8122 8123 @Override 8124 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 8125 if (mTemporaryDetach) { 8126 // If we are temporarily in the detach state, then do nothing. 8127 super.onFocusChanged(focused, direction, previouslyFocusedRect); 8128 return; 8129 } 8130 8131 mShowCursor = SystemClock.uptimeMillis(); 8132 8133 ensureEndedBatchEdit(); 8134 8135 if (focused) { 8136 int selStart = getSelectionStart(); 8137 int selEnd = getSelectionEnd(); 8138 8139 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 8140 // mode for these, unless there was a specific selection already started. 8141 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 8142 selEnd == mText.length(); 8143 mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted; 8144 8145 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 8146 // If a tap was used to give focus to that view, move cursor at tap position. 8147 // Has to be done before onTakeFocus, which can be overloaded. 8148 final int lastTapPosition = getLastTapPosition(); 8149 if (lastTapPosition >= 0) { 8150 Selection.setSelection((Spannable) mText, lastTapPosition); 8151 } 8152 8153 if (mMovement != null) { 8154 mMovement.onTakeFocus(this, (Spannable) mText, direction); 8155 } 8156 8157 // The DecorView does not have focus when the 'Done' ExtractEditText button is 8158 // pressed. Since it is the ViewAncestor's mView, it requests focus before 8159 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 8160 // This special case ensure that we keep current selection in that case. 8161 // It would be better to know why the DecorView does not have focus at that time. 8162 if (((this instanceof ExtractEditText) || mSelectionMoved) && 8163 selStart >= 0 && selEnd >= 0) { 8164 /* 8165 * Someone intentionally set the selection, so let them 8166 * do whatever it is that they wanted to do instead of 8167 * the default on-focus behavior. We reset the selection 8168 * here instead of just skipping the onTakeFocus() call 8169 * because some movement methods do something other than 8170 * just setting the selection in theirs and we still 8171 * need to go through that path. 8172 */ 8173 Selection.setSelection((Spannable) mText, selStart, selEnd); 8174 } 8175 8176 if (mSelectAllOnFocus) { 8177 selectAll(); 8178 } 8179 8180 mTouchFocusSelected = true; 8181 } 8182 8183 mFrozenWithFocus = false; 8184 mSelectionMoved = false; 8185 8186 if (mText instanceof Spannable) { 8187 Spannable sp = (Spannable) mText; 8188 MetaKeyKeyListener.resetMetaState(sp); 8189 } 8190 8191 makeBlink(); 8192 8193 if (mError != null) { 8194 showError(); 8195 } 8196 } else { 8197 if (mError != null) { 8198 hideError(); 8199 } 8200 // Don't leave us in the middle of a batch edit. 8201 onEndBatchEdit(); 8202 8203 if (this instanceof ExtractEditText) { 8204 // terminateTextSelectionMode removes selection, which we want to keep when 8205 // ExtractEditText goes out of focus. 8206 final int selStart = getSelectionStart(); 8207 final int selEnd = getSelectionEnd(); 8208 hideControllers(); 8209 Selection.setSelection((Spannable) mText, selStart, selEnd); 8210 } else { 8211 hideControllers(); 8212 downgradeEasyCorrectionSpans(); 8213 } 8214 8215 // No need to create the controller 8216 if (mSelectionModifierCursorController != null) { 8217 mSelectionModifierCursorController.resetTouchOffsets(); 8218 } 8219 } 8220 8221 startStopMarquee(focused); 8222 8223 if (mTransformation != null) { 8224 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 8225 } 8226 8227 super.onFocusChanged(focused, direction, previouslyFocusedRect); 8228 } 8229 8230 private int getLastTapPosition() { 8231 // No need to create the controller at that point, no last tap position saved 8232 if (mSelectionModifierCursorController != null) { 8233 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 8234 if (lastTapPosition >= 0) { 8235 // Safety check, should not be possible. 8236 if (lastTapPosition > mText.length()) { 8237 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 8238 + mText.length() + ")"); 8239 lastTapPosition = mText.length(); 8240 } 8241 return lastTapPosition; 8242 } 8243 } 8244 8245 return -1; 8246 } 8247 8248 @Override 8249 public void onWindowFocusChanged(boolean hasWindowFocus) { 8250 super.onWindowFocusChanged(hasWindowFocus); 8251 8252 if (hasWindowFocus) { 8253 if (mBlink != null) { 8254 mBlink.uncancel(); 8255 makeBlink(); 8256 } 8257 } else { 8258 if (mBlink != null) { 8259 mBlink.cancel(); 8260 } 8261 // Don't leave us in the middle of a batch edit. 8262 onEndBatchEdit(); 8263 if (mInputContentType != null) { 8264 mInputContentType.enterDown = false; 8265 } 8266 8267 hideControllers(); 8268 if (mSuggestionsPopupWindow != null) { 8269 mSuggestionsPopupWindow.onParentLostFocus(); 8270 } 8271 } 8272 8273 startStopMarquee(hasWindowFocus); 8274 } 8275 8276 @Override 8277 protected void onVisibilityChanged(View changedView, int visibility) { 8278 super.onVisibilityChanged(changedView, visibility); 8279 if (visibility != VISIBLE) { 8280 hideControllers(); 8281 } 8282 } 8283 8284 /** 8285 * Use {@link BaseInputConnection#removeComposingSpans 8286 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 8287 * state from this text view. 8288 */ 8289 public void clearComposingText() { 8290 if (mText instanceof Spannable) { 8291 BaseInputConnection.removeComposingSpans((Spannable)mText); 8292 } 8293 } 8294 8295 @Override 8296 public void setSelected(boolean selected) { 8297 boolean wasSelected = isSelected(); 8298 8299 super.setSelected(selected); 8300 8301 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 8302 if (selected) { 8303 startMarquee(); 8304 } else { 8305 stopMarquee(); 8306 } 8307 } 8308 } 8309 8310 @Override 8311 public boolean onTouchEvent(MotionEvent event) { 8312 final int action = event.getActionMasked(); 8313 8314 if (hasSelectionController()) { 8315 getSelectionController().onTouchEvent(event); 8316 } 8317 8318 if (mShowSuggestionRunnable != null) { 8319 removeCallbacks(mShowSuggestionRunnable); 8320 } 8321 8322 if (action == MotionEvent.ACTION_DOWN) { 8323 mLastDownPositionX = event.getX(); 8324 mLastDownPositionY = event.getY(); 8325 8326 // Reset this state; it will be re-set if super.onTouchEvent 8327 // causes focus to move to the view. 8328 mTouchFocusSelected = false; 8329 mIgnoreActionUpEvent = false; 8330 } 8331 8332 final boolean superResult = super.onTouchEvent(event); 8333 8334 /* 8335 * Don't handle the release after a long press, because it will 8336 * move the selection away from whatever the menu action was 8337 * trying to affect. 8338 */ 8339 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 8340 mDiscardNextActionUp = false; 8341 return superResult; 8342 } 8343 8344 final boolean touchIsFinished = (action == MotionEvent.ACTION_UP) && 8345 !mIgnoreActionUpEvent && isFocused(); 8346 8347 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 8348 && mText instanceof Spannable && mLayout != null) { 8349 boolean handled = false; 8350 8351 if (mMovement != null) { 8352 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 8353 } 8354 8355 if (touchIsFinished && mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable) { 8356 // The LinkMovementMethod which should handle taps on links has not been installed 8357 // on non editable text that support text selection. 8358 // We reproduce its behavior here to open links for these. 8359 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 8360 getSelectionEnd(), ClickableSpan.class); 8361 8362 if (links.length > 0) { 8363 links[0].onClick(this); 8364 handled = true; 8365 } 8366 } 8367 8368 if (touchIsFinished && (isTextEditable() || mTextIsSelectable)) { 8369 // Show the IME, except when selecting in read-only text. 8370 final InputMethodManager imm = InputMethodManager.peekInstance(); 8371 viewClicked(imm); 8372 if (!mTextIsSelectable) { 8373 handled |= imm != null && imm.showSoftInput(this, 0); 8374 } 8375 8376 boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect(); 8377 hideControllers(); 8378 if (!selectAllGotFocus && mText.length() > 0) { 8379 // Move cursor 8380 final int offset = getOffsetForPosition(event.getX(), event.getY()); 8381 Selection.setSelection((Spannable) mText, offset); 8382 if (mSpellChecker != null) { 8383 // When the cursor moves, the word that was typed may need spell check 8384 mSpellChecker.onSelectionChanged(); 8385 } 8386 if (!extractedTextModeWillBeStarted()) { 8387 if (isCursorInsideEasyCorrectionSpan()) { 8388 if (mShowSuggestionRunnable == null) { 8389 mShowSuggestionRunnable = new Runnable() { 8390 public void run() { 8391 showSuggestions(); 8392 } 8393 }; 8394 } 8395 postDelayed(mShowSuggestionRunnable, 8396 ViewConfiguration.getDoubleTapTimeout()); 8397 } else if (hasInsertionController()) { 8398 getInsertionController().show(); 8399 } 8400 } 8401 } 8402 8403 handled = true; 8404 } 8405 8406 if (handled) { 8407 return true; 8408 } 8409 } 8410 8411 return superResult; 8412 } 8413 8414 /** 8415 * @return <code>true</code> if the cursor/current selection overlaps a {@link SuggestionSpan}. 8416 */ 8417 private boolean isCursorInsideSuggestionSpan() { 8418 if (!(mText instanceof Spannable)) return false; 8419 8420 SuggestionSpan[] suggestionSpans = ((Spannable) mText).getSpans(getSelectionStart(), 8421 getSelectionEnd(), SuggestionSpan.class); 8422 return (suggestionSpans.length > 0); 8423 } 8424 8425 /** 8426 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with 8427 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set. 8428 */ 8429 private boolean isCursorInsideEasyCorrectionSpan() { 8430 Spannable spannable = (Spannable) mText; 8431 SuggestionSpan[] suggestionSpans = spannable.getSpans(getSelectionStart(), 8432 getSelectionEnd(), SuggestionSpan.class); 8433 for (int i = 0; i < suggestionSpans.length; i++) { 8434 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) { 8435 return true; 8436 } 8437 } 8438 return false; 8439 } 8440 8441 /** 8442 * Downgrades to simple suggestions all the easy correction spans that are not a spell check 8443 * span. 8444 */ 8445 private void downgradeEasyCorrectionSpans() { 8446 if (mText instanceof Spannable) { 8447 Spannable spannable = (Spannable) mText; 8448 SuggestionSpan[] suggestionSpans = spannable.getSpans(0, 8449 spannable.length(), SuggestionSpan.class); 8450 for (int i = 0; i < suggestionSpans.length; i++) { 8451 int flags = suggestionSpans[i].getFlags(); 8452 if ((flags & SuggestionSpan.FLAG_EASY_CORRECT) != 0 8453 && (flags & SuggestionSpan.FLAG_MISSPELLED) == 0) { 8454 flags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 8455 suggestionSpans[i].setFlags(flags); 8456 } 8457 } 8458 } 8459 } 8460 8461 @Override 8462 public boolean onGenericMotionEvent(MotionEvent event) { 8463 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 8464 try { 8465 if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { 8466 return true; 8467 } 8468 } catch (AbstractMethodError ex) { 8469 // onGenericMotionEvent was added to the MovementMethod interface in API 12. 8470 // Ignore its absence in case third party applications implemented the 8471 // interface directly. 8472 } 8473 } 8474 return super.onGenericMotionEvent(event); 8475 } 8476 8477 private void prepareCursorControllers() { 8478 boolean windowSupportsHandles = false; 8479 8480 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 8481 if (params instanceof WindowManager.LayoutParams) { 8482 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 8483 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 8484 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 8485 } 8486 8487 mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null; 8488 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 8489 mLayout != null; 8490 8491 if (!mInsertionControllerEnabled) { 8492 hideInsertionPointCursorController(); 8493 if (mInsertionPointCursorController != null) { 8494 mInsertionPointCursorController.onDetached(); 8495 mInsertionPointCursorController = null; 8496 } 8497 } 8498 8499 if (!mSelectionControllerEnabled) { 8500 stopSelectionActionMode(); 8501 if (mSelectionModifierCursorController != null) { 8502 mSelectionModifierCursorController.onDetached(); 8503 mSelectionModifierCursorController = null; 8504 } 8505 } 8506 } 8507 8508 /** 8509 * @return True iff this TextView contains a text that can be edited, or if this is 8510 * a selectable TextView. 8511 */ 8512 private boolean isTextEditable() { 8513 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 8514 } 8515 8516 /** 8517 * Returns true, only while processing a touch gesture, if the initial 8518 * touch down event caused focus to move to the text view and as a result 8519 * its selection changed. Only valid while processing the touch gesture 8520 * of interest. 8521 */ 8522 public boolean didTouchFocusSelect() { 8523 return mTouchFocusSelected; 8524 } 8525 8526 @Override 8527 public void cancelLongPress() { 8528 super.cancelLongPress(); 8529 mIgnoreActionUpEvent = true; 8530 } 8531 8532 @Override 8533 public boolean onTrackballEvent(MotionEvent event) { 8534 if (mMovement != null && mText instanceof Spannable && 8535 mLayout != null) { 8536 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 8537 return true; 8538 } 8539 } 8540 8541 return super.onTrackballEvent(event); 8542 } 8543 8544 public void setScroller(Scroller s) { 8545 mScroller = s; 8546 } 8547 8548 private static class Blink extends Handler implements Runnable { 8549 private final WeakReference<TextView> mView; 8550 private boolean mCancelled; 8551 8552 public Blink(TextView v) { 8553 mView = new WeakReference<TextView>(v); 8554 } 8555 8556 public void run() { 8557 if (mCancelled) { 8558 return; 8559 } 8560 8561 removeCallbacks(Blink.this); 8562 8563 TextView tv = mView.get(); 8564 8565 if (tv != null && tv.shouldBlink()) { 8566 if (tv.mLayout != null) { 8567 tv.invalidateCursorPath(); 8568 } 8569 8570 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 8571 } 8572 } 8573 8574 void cancel() { 8575 if (!mCancelled) { 8576 removeCallbacks(Blink.this); 8577 mCancelled = true; 8578 } 8579 } 8580 8581 void uncancel() { 8582 mCancelled = false; 8583 } 8584 } 8585 8586 /** 8587 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 8588 */ 8589 private boolean shouldBlink() { 8590 if (!isCursorVisible() || !isFocused()) return false; 8591 8592 final int start = getSelectionStart(); 8593 if (start < 0) return false; 8594 8595 final int end = getSelectionEnd(); 8596 if (end < 0) return false; 8597 8598 return start == end; 8599 } 8600 8601 private void makeBlink() { 8602 if (shouldBlink()) { 8603 mShowCursor = SystemClock.uptimeMillis(); 8604 if (mBlink == null) mBlink = new Blink(this); 8605 mBlink.removeCallbacks(mBlink); 8606 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 8607 } else { 8608 if (mBlink != null) mBlink.removeCallbacks(mBlink); 8609 } 8610 } 8611 8612 @Override 8613 protected float getLeftFadingEdgeStrength() { 8614 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8615 if (mEllipsize == TextUtils.TruncateAt.MARQUEE && 8616 mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 8617 if (mMarquee != null && !mMarquee.isStopped()) { 8618 final Marquee marquee = mMarquee; 8619 if (marquee.shouldDrawLeftFade()) { 8620 return marquee.mScroll / getHorizontalFadingEdgeLength(); 8621 } else { 8622 return 0.0f; 8623 } 8624 } else if (getLineCount() == 1) { 8625 final int layoutDirection = getResolvedLayoutDirection(); 8626 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8627 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8628 case Gravity.LEFT: 8629 return 0.0f; 8630 case Gravity.RIGHT: 8631 return (mLayout.getLineRight(0) - (mRight - mLeft) - 8632 getCompoundPaddingLeft() - getCompoundPaddingRight() - 8633 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 8634 case Gravity.CENTER_HORIZONTAL: 8635 return 0.0f; 8636 } 8637 } 8638 } 8639 return super.getLeftFadingEdgeStrength(); 8640 } 8641 8642 @Override 8643 protected float getRightFadingEdgeStrength() { 8644 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8645 if (mEllipsize == TextUtils.TruncateAt.MARQUEE && 8646 mMarqueeFadeMode != MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS) { 8647 if (mMarquee != null && !mMarquee.isStopped()) { 8648 final Marquee marquee = mMarquee; 8649 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 8650 } else if (getLineCount() == 1) { 8651 final int layoutDirection = getResolvedLayoutDirection(); 8652 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8653 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8654 case Gravity.LEFT: 8655 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 8656 getCompoundPaddingRight(); 8657 final float lineWidth = mLayout.getLineWidth(0); 8658 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 8659 case Gravity.RIGHT: 8660 return 0.0f; 8661 case Gravity.CENTER_HORIZONTAL: 8662 case Gravity.FILL_HORIZONTAL: 8663 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 8664 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 8665 getHorizontalFadingEdgeLength(); 8666 } 8667 } 8668 } 8669 return super.getRightFadingEdgeStrength(); 8670 } 8671 8672 @Override 8673 protected int computeHorizontalScrollRange() { 8674 if (mLayout != null) { 8675 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 8676 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 8677 } 8678 8679 return super.computeHorizontalScrollRange(); 8680 } 8681 8682 @Override 8683 protected int computeVerticalScrollRange() { 8684 if (mLayout != null) 8685 return mLayout.getHeight(); 8686 8687 return super.computeVerticalScrollRange(); 8688 } 8689 8690 @Override 8691 protected int computeVerticalScrollExtent() { 8692 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 8693 } 8694 8695 @Override 8696 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched, int flags) { 8697 super.findViewsWithText(outViews, searched, flags); 8698 if (!outViews.contains(this) && (flags & FIND_VIEWS_WITH_TEXT) != 0 8699 && !TextUtils.isEmpty(searched) && !TextUtils.isEmpty(mText)) { 8700 String searchedLowerCase = searched.toString().toLowerCase(); 8701 String textLowerCase = mText.toString().toLowerCase(); 8702 if (textLowerCase.contains(searchedLowerCase)) { 8703 outViews.add(this); 8704 } 8705 } 8706 } 8707 8708 public enum BufferType { 8709 NORMAL, SPANNABLE, EDITABLE, 8710 } 8711 8712 /** 8713 * Returns the TextView_textColor attribute from the 8714 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 8715 * from the TextView_textAppearance attribute, if TextView_textColor 8716 * was not set directly. 8717 */ 8718 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 8719 ColorStateList colors; 8720 colors = attrs.getColorStateList(com.android.internal.R.styleable. 8721 TextView_textColor); 8722 8723 if (colors == null) { 8724 int ap = attrs.getResourceId(com.android.internal.R.styleable. 8725 TextView_textAppearance, -1); 8726 if (ap != -1) { 8727 TypedArray appearance; 8728 appearance = context.obtainStyledAttributes(ap, 8729 com.android.internal.R.styleable.TextAppearance); 8730 colors = appearance.getColorStateList(com.android.internal.R.styleable. 8731 TextAppearance_textColor); 8732 appearance.recycle(); 8733 } 8734 } 8735 8736 return colors; 8737 } 8738 8739 /** 8740 * Returns the default color from the TextView_textColor attribute 8741 * from the AttributeSet, if set, or the default color from the 8742 * TextAppearance_textColor from the TextView_textAppearance attribute, 8743 * if TextView_textColor was not set directly. 8744 */ 8745 public static int getTextColor(Context context, 8746 TypedArray attrs, 8747 int def) { 8748 ColorStateList colors = getTextColors(context, attrs); 8749 8750 if (colors == null) { 8751 return def; 8752 } else { 8753 return colors.getDefaultColor(); 8754 } 8755 } 8756 8757 @Override 8758 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8759 final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; 8760 if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { 8761 switch (keyCode) { 8762 case KeyEvent.KEYCODE_A: 8763 if (canSelectText()) { 8764 return onTextContextMenuItem(ID_SELECT_ALL); 8765 } 8766 break; 8767 case KeyEvent.KEYCODE_X: 8768 if (canCut()) { 8769 return onTextContextMenuItem(ID_CUT); 8770 } 8771 break; 8772 case KeyEvent.KEYCODE_C: 8773 if (canCopy()) { 8774 return onTextContextMenuItem(ID_COPY); 8775 } 8776 break; 8777 case KeyEvent.KEYCODE_V: 8778 if (canPaste()) { 8779 return onTextContextMenuItem(ID_PASTE); 8780 } 8781 break; 8782 } 8783 } 8784 return super.onKeyShortcut(keyCode, event); 8785 } 8786 8787 /** 8788 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 8789 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 8790 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 8791 */ 8792 private boolean canSelectText() { 8793 return hasSelectionController() && mText.length() != 0; 8794 } 8795 8796 /** 8797 * Test based on the <i>intrinsic</i> charateristics of the TextView. 8798 * The text must be spannable and the movement method must allow for arbitary selection. 8799 * 8800 * See also {@link #canSelectText()}. 8801 */ 8802 private boolean textCanBeSelected() { 8803 // prepareCursorController() relies on this method. 8804 // If you change this condition, make sure prepareCursorController is called anywhere 8805 // the value of this condition might be changed. 8806 if (mMovement == null || !mMovement.canSelectArbitrarily()) return false; 8807 return isTextEditable() || (mTextIsSelectable && mText instanceof Spannable && isEnabled()); 8808 } 8809 8810 private boolean canCut() { 8811 if (hasPasswordTransformationMethod()) { 8812 return false; 8813 } 8814 8815 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 8816 return true; 8817 } 8818 8819 return false; 8820 } 8821 8822 private boolean canCopy() { 8823 if (hasPasswordTransformationMethod()) { 8824 return false; 8825 } 8826 8827 if (mText.length() > 0 && hasSelection()) { 8828 return true; 8829 } 8830 8831 return false; 8832 } 8833 8834 private boolean canPaste() { 8835 return (mText instanceof Editable && 8836 mInput != null && 8837 getSelectionStart() >= 0 && 8838 getSelectionEnd() >= 0 && 8839 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 8840 hasPrimaryClip()); 8841 } 8842 8843 private static long packRangeInLong(int start, int end) { 8844 return (((long) start) << 32) | end; 8845 } 8846 8847 private static int extractRangeStartFromLong(long range) { 8848 return (int) (range >>> 32); 8849 } 8850 8851 private static int extractRangeEndFromLong(long range) { 8852 return (int) (range & 0x00000000FFFFFFFFL); 8853 } 8854 8855 private boolean selectAll() { 8856 final int length = mText.length(); 8857 Selection.setSelection((Spannable) mText, 0, length); 8858 return length > 0; 8859 } 8860 8861 /** 8862 * Adjusts selection to the word under last touch offset. 8863 * Return true if the operation was successfully performed. 8864 */ 8865 private boolean selectCurrentWord() { 8866 if (!canSelectText()) { 8867 return false; 8868 } 8869 8870 if (hasPasswordTransformationMethod()) { 8871 // Always select all on a password field. 8872 // Cut/copy menu entries are not available for passwords, but being able to select all 8873 // is however useful to delete or paste to replace the entire content. 8874 return selectAll(); 8875 } 8876 8877 int klass = mInputType & InputType.TYPE_MASK_CLASS; 8878 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 8879 8880 // Specific text field types: select the entire text for these 8881 if (klass == InputType.TYPE_CLASS_NUMBER || 8882 klass == InputType.TYPE_CLASS_PHONE || 8883 klass == InputType.TYPE_CLASS_DATETIME || 8884 variation == InputType.TYPE_TEXT_VARIATION_URI || 8885 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 8886 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 8887 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 8888 return selectAll(); 8889 } 8890 8891 long lastTouchOffsets = getLastTouchOffsets(); 8892 final int minOffset = extractRangeStartFromLong(lastTouchOffsets); 8893 final int maxOffset = extractRangeEndFromLong(lastTouchOffsets); 8894 8895 // Safety check in case standard touch event handling has been bypassed 8896 if (minOffset < 0 || minOffset >= mText.length()) return false; 8897 if (maxOffset < 0 || maxOffset >= mText.length()) return false; 8898 8899 int selectionStart, selectionEnd; 8900 8901 // If a URLSpan (web address, email, phone...) is found at that position, select it. 8902 URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class); 8903 if (urlSpans.length >= 1) { 8904 URLSpan urlSpan = urlSpans[0]; 8905 selectionStart = ((Spanned) mText).getSpanStart(urlSpan); 8906 selectionEnd = ((Spanned) mText).getSpanEnd(urlSpan); 8907 } else { 8908 final WordIterator wordIterator = getWordIterator(); 8909 wordIterator.setCharSequence(mText, minOffset, maxOffset); 8910 8911 selectionStart = wordIterator.getBeginning(minOffset); 8912 selectionEnd = wordIterator.getEnd(maxOffset); 8913 8914 if (selectionStart == BreakIterator.DONE || selectionEnd == BreakIterator.DONE || 8915 selectionStart == selectionEnd) { 8916 // Possible when the word iterator does not properly handle the text's language 8917 long range = getCharRange(minOffset); 8918 selectionStart = extractRangeStartFromLong(range); 8919 selectionEnd = extractRangeEndFromLong(range); 8920 } 8921 } 8922 8923 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8924 return selectionEnd > selectionStart; 8925 } 8926 8927 /** 8928 * This is a temporary method. Future versions may support multi-locale text. 8929 * 8930 * @return The locale that should be used for a word iterator and a spell checker 8931 * in this TextView, based on the current spell checker settings, 8932 * the current IME's locale, or the system default locale. 8933 * @hide 8934 */ 8935 public Locale getTextServicesLocale() { 8936 Locale locale = Locale.getDefault(); 8937 final TextServicesManager textServicesManager = (TextServicesManager) 8938 mContext.getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE); 8939 final SpellCheckerSubtype subtype = textServicesManager.getCurrentSpellCheckerSubtype(true); 8940 if (subtype != null) { 8941 locale = new Locale(subtype.getLocale()); 8942 } 8943 return locale; 8944 } 8945 8946 void onLocaleChanged() { 8947 // Will be re-created on demand in getWordIterator with the proper new locale 8948 mWordIterator = null; 8949 } 8950 8951 /** 8952 * @hide 8953 */ 8954 public WordIterator getWordIterator() { 8955 if (mWordIterator == null) { 8956 mWordIterator = new WordIterator(getTextServicesLocale()); 8957 } 8958 return mWordIterator; 8959 } 8960 8961 private long getCharRange(int offset) { 8962 final int textLength = mText.length(); 8963 if (offset + 1 < textLength) { 8964 final char currentChar = mText.charAt(offset); 8965 final char nextChar = mText.charAt(offset + 1); 8966 if (Character.isSurrogatePair(currentChar, nextChar)) { 8967 return packRangeInLong(offset, offset + 2); 8968 } 8969 } 8970 if (offset < textLength) { 8971 return packRangeInLong(offset, offset + 1); 8972 } 8973 if (offset - 2 >= 0) { 8974 final char previousChar = mText.charAt(offset - 1); 8975 final char previousPreviousChar = mText.charAt(offset - 2); 8976 if (Character.isSurrogatePair(previousPreviousChar, previousChar)) { 8977 return packRangeInLong(offset - 2, offset); 8978 } 8979 } 8980 if (offset - 1 >= 0) { 8981 return packRangeInLong(offset - 1, offset); 8982 } 8983 return packRangeInLong(offset, offset); 8984 } 8985 8986 private long getLastTouchOffsets() { 8987 SelectionModifierCursorController selectionController = getSelectionController(); 8988 final int minOffset = selectionController.getMinTouchOffset(); 8989 final int maxOffset = selectionController.getMaxTouchOffset(); 8990 return packRangeInLong(minOffset, maxOffset); 8991 } 8992 8993 @Override 8994 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 8995 super.onPopulateAccessibilityEvent(event); 8996 8997 final boolean isPassword = hasPasswordTransformationMethod(); 8998 if (!isPassword) { 8999 CharSequence text = getTextForAccessibility(); 9000 if (!TextUtils.isEmpty(text)) { 9001 event.getText().add(text); 9002 } 9003 } 9004 } 9005 9006 @Override 9007 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 9008 super.onInitializeAccessibilityEvent(event); 9009 9010 event.setClassName(TextView.class.getName()); 9011 final boolean isPassword = hasPasswordTransformationMethod(); 9012 event.setPassword(isPassword); 9013 9014 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { 9015 event.setFromIndex(Selection.getSelectionStart(mText)); 9016 event.setToIndex(Selection.getSelectionEnd(mText)); 9017 event.setItemCount(mText.length()); 9018 } 9019 } 9020 9021 @Override 9022 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 9023 super.onInitializeAccessibilityNodeInfo(info); 9024 9025 info.setClassName(TextView.class.getName()); 9026 final boolean isPassword = hasPasswordTransformationMethod(); 9027 info.setPassword(isPassword); 9028 9029 if (!isPassword) { 9030 info.setText(getTextForAccessibility()); 9031 } 9032 } 9033 9034 @Override 9035 public void sendAccessibilityEvent(int eventType) { 9036 // Do not send scroll events since first they are not interesting for 9037 // accessibility and second such events a generated too frequently. 9038 // For details see the implementation of bringTextIntoView(). 9039 if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) { 9040 return; 9041 } 9042 super.sendAccessibilityEvent(eventType); 9043 } 9044 9045 /** 9046 * Gets the text reported for accessibility purposes. It is the 9047 * text if not empty or the hint. 9048 * 9049 * @return The accessibility text. 9050 */ 9051 private CharSequence getTextForAccessibility() { 9052 CharSequence text = getText(); 9053 if (TextUtils.isEmpty(text)) { 9054 text = getHint(); 9055 } 9056 return text; 9057 } 9058 9059 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 9060 int fromIndex, int removedCount, int addedCount) { 9061 AccessibilityEvent event = 9062 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 9063 event.setFromIndex(fromIndex); 9064 event.setRemovedCount(removedCount); 9065 event.setAddedCount(addedCount); 9066 event.setBeforeText(beforeText); 9067 sendAccessibilityEventUnchecked(event); 9068 } 9069 9070 /** 9071 * Returns whether this text view is a current input method target. The 9072 * default implementation just checks with {@link InputMethodManager}. 9073 */ 9074 public boolean isInputMethodTarget() { 9075 InputMethodManager imm = InputMethodManager.peekInstance(); 9076 return imm != null && imm.isActive(this); 9077 } 9078 9079 // Selection context mode 9080 private static final int ID_SELECT_ALL = android.R.id.selectAll; 9081 private static final int ID_CUT = android.R.id.cut; 9082 private static final int ID_COPY = android.R.id.copy; 9083 private static final int ID_PASTE = android.R.id.paste; 9084 9085 /** 9086 * Called when a context menu option for the text view is selected. Currently 9087 * this will be one of {@link android.R.id#selectAll}, {@link android.R.id#cut}, 9088 * {@link android.R.id#copy} or {@link android.R.id#paste}. 9089 * 9090 * @return true if the context menu item action was performed. 9091 */ 9092 public boolean onTextContextMenuItem(int id) { 9093 int min = 0; 9094 int max = mText.length(); 9095 9096 if (isFocused()) { 9097 final int selStart = getSelectionStart(); 9098 final int selEnd = getSelectionEnd(); 9099 9100 min = Math.max(0, Math.min(selStart, selEnd)); 9101 max = Math.max(0, Math.max(selStart, selEnd)); 9102 } 9103 9104 switch (id) { 9105 case ID_SELECT_ALL: 9106 // This does not enter text selection mode. Text is highlighted, so that it can be 9107 // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. 9108 selectAll(); 9109 return true; 9110 9111 case ID_PASTE: 9112 paste(min, max); 9113 return true; 9114 9115 case ID_CUT: 9116 setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max))); 9117 deleteText_internal(min, max); 9118 stopSelectionActionMode(); 9119 return true; 9120 9121 case ID_COPY: 9122 setPrimaryClip(ClipData.newPlainText(null, getTransformedText(min, max))); 9123 stopSelectionActionMode(); 9124 return true; 9125 } 9126 return false; 9127 } 9128 9129 private CharSequence getTransformedText(int start, int end) { 9130 return removeSuggestionSpans(mTransformed.subSequence(start, end)); 9131 } 9132 9133 /** 9134 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 9135 * by [min, max] when replacing this region by paste. 9136 * Note that if there were two spaces (or more) at that position before, they are kept. We just 9137 * make sure we do not add an extra one from the paste content. 9138 */ 9139 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 9140 if (paste.length() > 0) { 9141 if (min > 0) { 9142 final char charBefore = mTransformed.charAt(min - 1); 9143 final char charAfter = paste.charAt(0); 9144 9145 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 9146 // Two spaces at beginning of paste: remove one 9147 final int originalLength = mText.length(); 9148 deleteText_internal(min - 1, min); 9149 // Due to filters, there is no guarantee that exactly one character was 9150 // removed: count instead. 9151 final int delta = mText.length() - originalLength; 9152 min += delta; 9153 max += delta; 9154 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 9155 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 9156 // No space at beginning of paste: add one 9157 final int originalLength = mText.length(); 9158 replaceText_internal(min, min, " "); 9159 // Taking possible filters into account as above. 9160 final int delta = mText.length() - originalLength; 9161 min += delta; 9162 max += delta; 9163 } 9164 } 9165 9166 if (max < mText.length()) { 9167 final char charBefore = paste.charAt(paste.length() - 1); 9168 final char charAfter = mTransformed.charAt(max); 9169 9170 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 9171 // Two spaces at end of paste: remove one 9172 deleteText_internal(max, max + 1); 9173 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 9174 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 9175 // No space at end of paste: add one 9176 replaceText_internal(max, max, " "); 9177 } 9178 } 9179 } 9180 9181 return packRangeInLong(min, max); 9182 } 9183 9184 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 9185 TextView shadowView = (TextView) inflate(mContext, 9186 com.android.internal.R.layout.text_drag_thumbnail, null); 9187 9188 if (shadowView == null) { 9189 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 9190 } 9191 9192 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 9193 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 9194 } 9195 shadowView.setText(text); 9196 shadowView.setTextColor(getTextColors()); 9197 9198 shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 9199 shadowView.setGravity(Gravity.CENTER); 9200 9201 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 9202 ViewGroup.LayoutParams.WRAP_CONTENT)); 9203 9204 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 9205 shadowView.measure(size, size); 9206 9207 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 9208 shadowView.invalidate(); 9209 return new DragShadowBuilder(shadowView); 9210 } 9211 9212 private static class DragLocalState { 9213 public TextView sourceTextView; 9214 public int start, end; 9215 9216 public DragLocalState(TextView sourceTextView, int start, int end) { 9217 this.sourceTextView = sourceTextView; 9218 this.start = start; 9219 this.end = end; 9220 } 9221 } 9222 9223 @Override 9224 public boolean performLongClick() { 9225 boolean handled = false; 9226 boolean vibrate = true; 9227 9228 if (super.performLongClick()) { 9229 handled = true; 9230 } 9231 9232 // Long press in empty space moves cursor and shows the Paste affordance if available. 9233 if (!handled && !isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 9234 mInsertionControllerEnabled) { 9235 final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY); 9236 stopSelectionActionMode(); 9237 Selection.setSelection((Spannable) mText, offset); 9238 getInsertionController().showWithActionPopup(); 9239 handled = true; 9240 vibrate = false; 9241 } 9242 9243 if (!handled && mSelectionActionMode != null) { 9244 if (touchPositionIsInSelection()) { 9245 // Start a drag 9246 final int start = getSelectionStart(); 9247 final int end = getSelectionEnd(); 9248 CharSequence selectedText = getTransformedText(start, end); 9249 ClipData data = ClipData.newPlainText(null, selectedText); 9250 DragLocalState localState = new DragLocalState(this, start, end); 9251 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 9252 stopSelectionActionMode(); 9253 } else { 9254 getSelectionController().hide(); 9255 selectCurrentWord(); 9256 getSelectionController().show(); 9257 } 9258 handled = true; 9259 } 9260 9261 // Start a new selection 9262 if (!handled) { 9263 vibrate = handled = startSelectionActionMode(); 9264 } 9265 9266 if (vibrate) { 9267 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 9268 } 9269 9270 if (handled) { 9271 mDiscardNextActionUp = true; 9272 } 9273 9274 return handled; 9275 } 9276 9277 private boolean touchPositionIsInSelection() { 9278 int selectionStart = getSelectionStart(); 9279 int selectionEnd = getSelectionEnd(); 9280 9281 if (selectionStart == selectionEnd) { 9282 return false; 9283 } 9284 9285 if (selectionStart > selectionEnd) { 9286 int tmp = selectionStart; 9287 selectionStart = selectionEnd; 9288 selectionEnd = tmp; 9289 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 9290 } 9291 9292 SelectionModifierCursorController selectionController = getSelectionController(); 9293 int minOffset = selectionController.getMinTouchOffset(); 9294 int maxOffset = selectionController.getMaxTouchOffset(); 9295 9296 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 9297 } 9298 9299 private PositionListener getPositionListener() { 9300 if (mPositionListener == null) { 9301 mPositionListener = new PositionListener(); 9302 } 9303 return mPositionListener; 9304 } 9305 9306 private interface TextViewPositionListener { 9307 public void updatePosition(int parentPositionX, int parentPositionY, 9308 boolean parentPositionChanged, boolean parentScrolled); 9309 } 9310 9311 private class PositionListener implements ViewTreeObserver.OnPreDrawListener { 9312 // 3 handles 9313 // 3 ActionPopup [replace, suggestion, easyedit] (suggestionsPopup first hides the others) 9314 private final int MAXIMUM_NUMBER_OF_LISTENERS = 6; 9315 private TextViewPositionListener[] mPositionListeners = 9316 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS]; 9317 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS]; 9318 private boolean mPositionHasChanged = true; 9319 // Absolute position of the TextView with respect to its parent window 9320 private int mPositionX, mPositionY; 9321 private int mNumberOfListeners; 9322 private boolean mScrollHasChanged; 9323 9324 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) { 9325 if (mNumberOfListeners == 0) { 9326 updatePosition(); 9327 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9328 vto.addOnPreDrawListener(this); 9329 } 9330 9331 int emptySlotIndex = -1; 9332 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 9333 TextViewPositionListener listener = mPositionListeners[i]; 9334 if (listener == positionListener) { 9335 return; 9336 } else if (emptySlotIndex < 0 && listener == null) { 9337 emptySlotIndex = i; 9338 } 9339 } 9340 9341 mPositionListeners[emptySlotIndex] = positionListener; 9342 mCanMove[emptySlotIndex] = canMove; 9343 mNumberOfListeners++; 9344 } 9345 9346 public void removeSubscriber(TextViewPositionListener positionListener) { 9347 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 9348 if (mPositionListeners[i] == positionListener) { 9349 mPositionListeners[i] = null; 9350 mNumberOfListeners--; 9351 break; 9352 } 9353 } 9354 9355 if (mNumberOfListeners == 0) { 9356 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9357 vto.removeOnPreDrawListener(this); 9358 } 9359 } 9360 9361 public int getPositionX() { 9362 return mPositionX; 9363 } 9364 9365 public int getPositionY() { 9366 return mPositionY; 9367 } 9368 9369 @Override 9370 public boolean onPreDraw() { 9371 updatePosition(); 9372 9373 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 9374 if (mPositionHasChanged || mScrollHasChanged || mCanMove[i]) { 9375 TextViewPositionListener positionListener = mPositionListeners[i]; 9376 if (positionListener != null) { 9377 positionListener.updatePosition(mPositionX, mPositionY, 9378 mPositionHasChanged, mScrollHasChanged); 9379 } 9380 } 9381 } 9382 9383 mScrollHasChanged = false; 9384 return true; 9385 } 9386 9387 private void updatePosition() { 9388 TextView.this.getLocationInWindow(mTempCoords); 9389 9390 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY; 9391 9392 mPositionX = mTempCoords[0]; 9393 mPositionY = mTempCoords[1]; 9394 } 9395 9396 public void onScrollChanged() { 9397 mScrollHasChanged = true; 9398 } 9399 } 9400 9401 private boolean isPositionVisible(int positionX, int positionY) { 9402 synchronized (sTmpPosition) { 9403 final float[] position = sTmpPosition; 9404 position[0] = positionX; 9405 position[1] = positionY; 9406 View view = this; 9407 9408 while (view != null) { 9409 if (view != this) { 9410 // Local scroll is already taken into account in positionX/Y 9411 position[0] -= view.getScrollX(); 9412 position[1] -= view.getScrollY(); 9413 } 9414 9415 if (position[0] < 0 || position[1] < 0 || 9416 position[0] > view.getWidth() || position[1] > view.getHeight()) { 9417 return false; 9418 } 9419 9420 if (!view.getMatrix().isIdentity()) { 9421 view.getMatrix().mapPoints(position); 9422 } 9423 9424 position[0] += view.getLeft(); 9425 position[1] += view.getTop(); 9426 9427 final ViewParent parent = view.getParent(); 9428 if (parent instanceof View) { 9429 view = (View) parent; 9430 } else { 9431 // We've reached the ViewRoot, stop iterating 9432 view = null; 9433 } 9434 } 9435 } 9436 9437 // We've been able to walk up the view hierarchy and the position was never clipped 9438 return true; 9439 } 9440 9441 private boolean isOffsetVisible(int offset) { 9442 final int line = mLayout.getLineForOffset(offset); 9443 final int lineBottom = mLayout.getLineBottom(line); 9444 final int primaryHorizontal = (int) mLayout.getPrimaryHorizontal(offset); 9445 return isPositionVisible(primaryHorizontal + viewportToContentHorizontalOffset(), 9446 lineBottom + viewportToContentVerticalOffset()); 9447 } 9448 9449 @Override 9450 protected void onScrollChanged(int horiz, int vert, int oldHoriz, int oldVert) { 9451 super.onScrollChanged(horiz, vert, oldHoriz, oldVert); 9452 if (mPositionListener != null) { 9453 mPositionListener.onScrollChanged(); 9454 } 9455 } 9456 9457 private abstract class PinnedPopupWindow implements TextViewPositionListener { 9458 protected PopupWindow mPopupWindow; 9459 protected ViewGroup mContentView; 9460 int mPositionX, mPositionY; 9461 9462 protected abstract void createPopupWindow(); 9463 protected abstract void initContentView(); 9464 protected abstract int getTextOffset(); 9465 protected abstract int getVerticalLocalPosition(int line); 9466 protected abstract int clipVertically(int positionY); 9467 9468 public PinnedPopupWindow() { 9469 createPopupWindow(); 9470 9471 mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 9472 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 9473 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 9474 9475 initContentView(); 9476 9477 LayoutParams wrapContent = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 9478 ViewGroup.LayoutParams.WRAP_CONTENT); 9479 mContentView.setLayoutParams(wrapContent); 9480 9481 mPopupWindow.setContentView(mContentView); 9482 } 9483 9484 public void show() { 9485 TextView.this.getPositionListener().addSubscriber(this, false /* offset is fixed */); 9486 9487 computeLocalPosition(); 9488 9489 final PositionListener positionListener = TextView.this.getPositionListener(); 9490 updatePosition(positionListener.getPositionX(), positionListener.getPositionY()); 9491 } 9492 9493 protected void measureContent() { 9494 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9495 mContentView.measure( 9496 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, 9497 View.MeasureSpec.AT_MOST), 9498 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, 9499 View.MeasureSpec.AT_MOST)); 9500 } 9501 9502 /* The popup window will be horizontally centered on the getTextOffset() and vertically 9503 * positioned according to viewportToContentHorizontalOffset. 9504 * 9505 * This method assumes that mContentView has properly been measured from its content. */ 9506 private void computeLocalPosition() { 9507 measureContent(); 9508 final int width = mContentView.getMeasuredWidth(); 9509 final int offset = getTextOffset(); 9510 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f); 9511 mPositionX += viewportToContentHorizontalOffset(); 9512 9513 final int line = mLayout.getLineForOffset(offset); 9514 mPositionY = getVerticalLocalPosition(line); 9515 mPositionY += viewportToContentVerticalOffset(); 9516 } 9517 9518 private void updatePosition(int parentPositionX, int parentPositionY) { 9519 int positionX = parentPositionX + mPositionX; 9520 int positionY = parentPositionY + mPositionY; 9521 9522 positionY = clipVertically(positionY); 9523 9524 // Horizontal clipping 9525 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9526 final int width = mContentView.getMeasuredWidth(); 9527 positionX = Math.min(displayMetrics.widthPixels - width, positionX); 9528 positionX = Math.max(0, positionX); 9529 9530 if (isShowing()) { 9531 mPopupWindow.update(positionX, positionY, -1, -1); 9532 } else { 9533 mPopupWindow.showAtLocation(TextView.this, Gravity.NO_GRAVITY, 9534 positionX, positionY); 9535 } 9536 } 9537 9538 public void hide() { 9539 mPopupWindow.dismiss(); 9540 TextView.this.getPositionListener().removeSubscriber(this); 9541 } 9542 9543 @Override 9544 public void updatePosition(int parentPositionX, int parentPositionY, 9545 boolean parentPositionChanged, boolean parentScrolled) { 9546 // Either parentPositionChanged or parentScrolled is true, check if still visible 9547 if (isShowing() && isOffsetVisible(getTextOffset())) { 9548 if (parentScrolled) computeLocalPosition(); 9549 updatePosition(parentPositionX, parentPositionY); 9550 } else { 9551 hide(); 9552 } 9553 } 9554 9555 public boolean isShowing() { 9556 return mPopupWindow.isShowing(); 9557 } 9558 } 9559 9560 private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnItemClickListener { 9561 private static final int MAX_NUMBER_SUGGESTIONS = SuggestionSpan.SUGGESTIONS_MAX_SIZE; 9562 private static final int ADD_TO_DICTIONARY = -1; 9563 private static final int DELETE_TEXT = -2; 9564 private SuggestionInfo[] mSuggestionInfos; 9565 private int mNumberOfSuggestions; 9566 private boolean mCursorWasVisibleBeforeSuggestions; 9567 private boolean mIsShowingUp = false; 9568 private SuggestionAdapter mSuggestionsAdapter; 9569 private final Comparator<SuggestionSpan> mSuggestionSpanComparator; 9570 private final HashMap<SuggestionSpan, Integer> mSpansLengths; 9571 9572 private class CustomPopupWindow extends PopupWindow { 9573 public CustomPopupWindow(Context context, int defStyle) { 9574 super(context, null, defStyle); 9575 } 9576 9577 @Override 9578 public void dismiss() { 9579 super.dismiss(); 9580 9581 TextView.this.getPositionListener().removeSubscriber(SuggestionsPopupWindow.this); 9582 9583 // Safe cast since show() checks that mText is an Editable 9584 ((Spannable) mText).removeSpan(mSuggestionRangeSpan); 9585 9586 setCursorVisible(mCursorWasVisibleBeforeSuggestions); 9587 if (hasInsertionController()) { 9588 getInsertionController().show(); 9589 } 9590 } 9591 } 9592 9593 public SuggestionsPopupWindow() { 9594 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 9595 mSuggestionSpanComparator = new SuggestionSpanComparator(); 9596 mSpansLengths = new HashMap<SuggestionSpan, Integer>(); 9597 } 9598 9599 @Override 9600 protected void createPopupWindow() { 9601 mPopupWindow = new CustomPopupWindow(TextView.this.mContext, 9602 com.android.internal.R.attr.textSuggestionsWindowStyle); 9603 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 9604 mPopupWindow.setFocusable(true); 9605 mPopupWindow.setClippingEnabled(false); 9606 } 9607 9608 @Override 9609 protected void initContentView() { 9610 ListView listView = new ListView(TextView.this.getContext()); 9611 mSuggestionsAdapter = new SuggestionAdapter(); 9612 listView.setAdapter(mSuggestionsAdapter); 9613 listView.setOnItemClickListener(this); 9614 mContentView = listView; 9615 9616 // Inflate the suggestion items once and for all. + 2 for add to dictionary and delete 9617 mSuggestionInfos = new SuggestionInfo[MAX_NUMBER_SUGGESTIONS + 2]; 9618 for (int i = 0; i < mSuggestionInfos.length; i++) { 9619 mSuggestionInfos[i] = new SuggestionInfo(); 9620 } 9621 } 9622 9623 public boolean isShowingUp() { 9624 return mIsShowingUp; 9625 } 9626 9627 public void onParentLostFocus() { 9628 mIsShowingUp = false; 9629 } 9630 9631 private class SuggestionInfo { 9632 int suggestionStart, suggestionEnd; // range of actual suggestion within text 9633 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 9634 int suggestionIndex; // the index of this suggestion inside suggestionSpan 9635 SpannableStringBuilder text = new SpannableStringBuilder(); 9636 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext, 9637 android.R.style.TextAppearance_SuggestionHighlight); 9638 } 9639 9640 private class SuggestionAdapter extends BaseAdapter { 9641 private LayoutInflater mInflater = (LayoutInflater) TextView.this.mContext. 9642 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 9643 9644 @Override 9645 public int getCount() { 9646 return mNumberOfSuggestions; 9647 } 9648 9649 @Override 9650 public Object getItem(int position) { 9651 return mSuggestionInfos[position]; 9652 } 9653 9654 @Override 9655 public long getItemId(int position) { 9656 return position; 9657 } 9658 9659 @Override 9660 public View getView(int position, View convertView, ViewGroup parent) { 9661 TextView textView = (TextView) convertView; 9662 9663 if (textView == null) { 9664 textView = (TextView) mInflater.inflate(mTextEditSuggestionItemLayout, parent, 9665 false); 9666 } 9667 9668 final SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 9669 textView.setText(suggestionInfo.text); 9670 9671 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) { 9672 textView.setCompoundDrawablesWithIntrinsicBounds( 9673 com.android.internal.R.drawable.ic_suggestions_add, 0, 0, 0); 9674 } else if (suggestionInfo.suggestionIndex == DELETE_TEXT) { 9675 textView.setCompoundDrawablesWithIntrinsicBounds( 9676 com.android.internal.R.drawable.ic_suggestions_delete, 0, 0, 0); 9677 } else { 9678 textView.setCompoundDrawables(null, null, null, null); 9679 } 9680 9681 return textView; 9682 } 9683 } 9684 9685 private class SuggestionSpanComparator implements Comparator<SuggestionSpan> { 9686 public int compare(SuggestionSpan span1, SuggestionSpan span2) { 9687 final int flag1 = span1.getFlags(); 9688 final int flag2 = span2.getFlags(); 9689 if (flag1 != flag2) { 9690 // The order here should match what is used in updateDrawState 9691 final boolean easy1 = (flag1 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 9692 final boolean easy2 = (flag2 & SuggestionSpan.FLAG_EASY_CORRECT) != 0; 9693 final boolean misspelled1 = (flag1 & SuggestionSpan.FLAG_MISSPELLED) != 0; 9694 final boolean misspelled2 = (flag2 & SuggestionSpan.FLAG_MISSPELLED) != 0; 9695 if (easy1 && !misspelled1) return -1; 9696 if (easy2 && !misspelled2) return 1; 9697 if (misspelled1) return -1; 9698 if (misspelled2) return 1; 9699 } 9700 9701 return mSpansLengths.get(span1).intValue() - mSpansLengths.get(span2).intValue(); 9702 } 9703 } 9704 9705 /** 9706 * Returns the suggestion spans that cover the current cursor position. The suggestion 9707 * spans are sorted according to the length of text that they are attached to. 9708 */ 9709 private SuggestionSpan[] getSuggestionSpans() { 9710 int pos = TextView.this.getSelectionStart(); 9711 Spannable spannable = (Spannable) TextView.this.mText; 9712 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 9713 9714 mSpansLengths.clear(); 9715 for (SuggestionSpan suggestionSpan : suggestionSpans) { 9716 int start = spannable.getSpanStart(suggestionSpan); 9717 int end = spannable.getSpanEnd(suggestionSpan); 9718 mSpansLengths.put(suggestionSpan, Integer.valueOf(end - start)); 9719 } 9720 9721 // The suggestions are sorted according to their types (easy correction first, then 9722 // misspelled) and to the length of the text that they cover (shorter first). 9723 Arrays.sort(suggestionSpans, mSuggestionSpanComparator); 9724 return suggestionSpans; 9725 } 9726 9727 @Override 9728 public void show() { 9729 if (!(mText instanceof Editable)) return; 9730 9731 if (updateSuggestions()) { 9732 mCursorWasVisibleBeforeSuggestions = mCursorVisible; 9733 setCursorVisible(false); 9734 mIsShowingUp = true; 9735 super.show(); 9736 } 9737 } 9738 9739 @Override 9740 protected void measureContent() { 9741 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9742 final int horizontalMeasure = View.MeasureSpec.makeMeasureSpec( 9743 displayMetrics.widthPixels, View.MeasureSpec.AT_MOST); 9744 final int verticalMeasure = View.MeasureSpec.makeMeasureSpec( 9745 displayMetrics.heightPixels, View.MeasureSpec.AT_MOST); 9746 9747 int width = 0; 9748 View view = null; 9749 for (int i = 0; i < mNumberOfSuggestions; i++) { 9750 view = mSuggestionsAdapter.getView(i, view, mContentView); 9751 view.getLayoutParams().width = LayoutParams.WRAP_CONTENT; 9752 view.measure(horizontalMeasure, verticalMeasure); 9753 width = Math.max(width, view.getMeasuredWidth()); 9754 } 9755 9756 // Enforce the width based on actual text widths 9757 mContentView.measure( 9758 View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), 9759 verticalMeasure); 9760 9761 Drawable popupBackground = mPopupWindow.getBackground(); 9762 if (popupBackground != null) { 9763 if (mTempRect == null) mTempRect = new Rect(); 9764 popupBackground.getPadding(mTempRect); 9765 width += mTempRect.left + mTempRect.right; 9766 } 9767 mPopupWindow.setWidth(width); 9768 } 9769 9770 @Override 9771 protected int getTextOffset() { 9772 return getSelectionStart(); 9773 } 9774 9775 @Override 9776 protected int getVerticalLocalPosition(int line) { 9777 return mLayout.getLineBottom(line); 9778 } 9779 9780 @Override 9781 protected int clipVertically(int positionY) { 9782 final int height = mContentView.getMeasuredHeight(); 9783 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9784 return Math.min(positionY, displayMetrics.heightPixels - height); 9785 } 9786 9787 @Override 9788 public void hide() { 9789 super.hide(); 9790 } 9791 9792 private boolean updateSuggestions() { 9793 Spannable spannable = (Spannable) TextView.this.mText; 9794 SuggestionSpan[] suggestionSpans = getSuggestionSpans(); 9795 9796 final int nbSpans = suggestionSpans.length; 9797 // Suggestions are shown after a delay: the underlying spans may have been removed 9798 if (nbSpans == 0) return false; 9799 9800 mNumberOfSuggestions = 0; 9801 int spanUnionStart = mText.length(); 9802 int spanUnionEnd = 0; 9803 9804 SuggestionSpan misspelledSpan = null; 9805 int underlineColor = 0; 9806 9807 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 9808 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 9809 final int spanStart = spannable.getSpanStart(suggestionSpan); 9810 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 9811 spanUnionStart = Math.min(spanStart, spanUnionStart); 9812 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 9813 9814 if ((suggestionSpan.getFlags() & SuggestionSpan.FLAG_MISSPELLED) != 0) { 9815 misspelledSpan = suggestionSpan; 9816 } 9817 9818 // The first span dictates the background color of the highlighted text 9819 if (spanIndex == 0) underlineColor = suggestionSpan.getUnderlineColor(); 9820 9821 String[] suggestions = suggestionSpan.getSuggestions(); 9822 int nbSuggestions = suggestions.length; 9823 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 9824 String suggestion = suggestions[suggestionIndex]; 9825 9826 boolean suggestionIsDuplicate = false; 9827 for (int i = 0; i < mNumberOfSuggestions; i++) { 9828 if (mSuggestionInfos[i].text.toString().equals(suggestion)) { 9829 SuggestionSpan otherSuggestionSpan = mSuggestionInfos[i].suggestionSpan; 9830 final int otherSpanStart = spannable.getSpanStart(otherSuggestionSpan); 9831 final int otherSpanEnd = spannable.getSpanEnd(otherSuggestionSpan); 9832 if (spanStart == otherSpanStart && spanEnd == otherSpanEnd) { 9833 suggestionIsDuplicate = true; 9834 break; 9835 } 9836 } 9837 } 9838 9839 if (!suggestionIsDuplicate) { 9840 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 9841 suggestionInfo.suggestionSpan = suggestionSpan; 9842 suggestionInfo.suggestionIndex = suggestionIndex; 9843 suggestionInfo.text.replace(0, suggestionInfo.text.length(), suggestion); 9844 9845 mNumberOfSuggestions++; 9846 9847 if (mNumberOfSuggestions == MAX_NUMBER_SUGGESTIONS) { 9848 // Also end outer for loop 9849 spanIndex = nbSpans; 9850 break; 9851 } 9852 } 9853 } 9854 } 9855 9856 for (int i = 0; i < mNumberOfSuggestions; i++) { 9857 highlightTextDifferences(mSuggestionInfos[i], spanUnionStart, spanUnionEnd); 9858 } 9859 9860 // Add "Add to dictionary" item if there is a span with the misspelled flag 9861 if (misspelledSpan != null) { 9862 final int misspelledStart = spannable.getSpanStart(misspelledSpan); 9863 final int misspelledEnd = spannable.getSpanEnd(misspelledSpan); 9864 if (misspelledStart >= 0 && misspelledEnd > misspelledStart) { 9865 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 9866 suggestionInfo.suggestionSpan = misspelledSpan; 9867 suggestionInfo.suggestionIndex = ADD_TO_DICTIONARY; 9868 suggestionInfo.text.replace(0, suggestionInfo.text.length(), 9869 getContext().getString(com.android.internal.R.string.addToDictionary)); 9870 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 9871 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9872 9873 mNumberOfSuggestions++; 9874 } 9875 } 9876 9877 // Delete item 9878 SuggestionInfo suggestionInfo = mSuggestionInfos[mNumberOfSuggestions]; 9879 suggestionInfo.suggestionSpan = null; 9880 suggestionInfo.suggestionIndex = DELETE_TEXT; 9881 suggestionInfo.text.replace(0, suggestionInfo.text.length(), 9882 getContext().getString(com.android.internal.R.string.deleteText)); 9883 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 0, 9884 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9885 mNumberOfSuggestions++; 9886 9887 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 9888 if (underlineColor == 0) { 9889 // Fallback on the default highlight color when the first span does not provide one 9890 mSuggestionRangeSpan.setBackgroundColor(mHighlightColor); 9891 } else { 9892 final float BACKGROUND_TRANSPARENCY = 0.4f; 9893 final int newAlpha = (int) (Color.alpha(underlineColor) * BACKGROUND_TRANSPARENCY); 9894 mSuggestionRangeSpan.setBackgroundColor( 9895 (underlineColor & 0x00FFFFFF) + (newAlpha << 24)); 9896 } 9897 spannable.setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 9898 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9899 9900 mSuggestionsAdapter.notifyDataSetChanged(); 9901 return true; 9902 } 9903 9904 private void highlightTextDifferences(SuggestionInfo suggestionInfo, int unionStart, 9905 int unionEnd) { 9906 final Spannable text = (Spannable) mText; 9907 final int spanStart = text.getSpanStart(suggestionInfo.suggestionSpan); 9908 final int spanEnd = text.getSpanEnd(suggestionInfo.suggestionSpan); 9909 9910 // Adjust the start/end of the suggestion span 9911 suggestionInfo.suggestionStart = spanStart - unionStart; 9912 suggestionInfo.suggestionEnd = suggestionInfo.suggestionStart 9913 + suggestionInfo.text.length(); 9914 9915 suggestionInfo.text.setSpan(suggestionInfo.highlightSpan, 0, 9916 suggestionInfo.text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9917 9918 // Add the text before and after the span. 9919 final String textAsString = text.toString(); 9920 suggestionInfo.text.insert(0, textAsString.substring(unionStart, spanStart)); 9921 suggestionInfo.text.append(textAsString.substring(spanEnd, unionEnd)); 9922 } 9923 9924 @Override 9925 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 9926 Editable editable = (Editable) mText; 9927 SuggestionInfo suggestionInfo = mSuggestionInfos[position]; 9928 9929 if (suggestionInfo.suggestionIndex == DELETE_TEXT) { 9930 final int spanUnionStart = editable.getSpanStart(mSuggestionRangeSpan); 9931 int spanUnionEnd = editable.getSpanEnd(mSuggestionRangeSpan); 9932 if (spanUnionStart >= 0 && spanUnionEnd > spanUnionStart) { 9933 // Do not leave two adjacent spaces after deletion, or one at beginning of text 9934 if (spanUnionEnd < editable.length() && 9935 Character.isSpaceChar(editable.charAt(spanUnionEnd)) && 9936 (spanUnionStart == 0 || 9937 Character.isSpaceChar(editable.charAt(spanUnionStart - 1)))) { 9938 spanUnionEnd = spanUnionEnd + 1; 9939 } 9940 deleteText_internal(spanUnionStart, spanUnionEnd); 9941 } 9942 hide(); 9943 return; 9944 } 9945 9946 final int spanStart = editable.getSpanStart(suggestionInfo.suggestionSpan); 9947 final int spanEnd = editable.getSpanEnd(suggestionInfo.suggestionSpan); 9948 if (spanStart < 0 || spanEnd <= spanStart) { 9949 // Span has been removed 9950 hide(); 9951 return; 9952 } 9953 final String originalText = mText.toString().substring(spanStart, spanEnd); 9954 9955 if (suggestionInfo.suggestionIndex == ADD_TO_DICTIONARY) { 9956 Intent intent = new Intent(Settings.ACTION_USER_DICTIONARY_INSERT); 9957 intent.putExtra("word", originalText); 9958 intent.putExtra("locale", getTextServicesLocale().toString()); 9959 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 9960 getContext().startActivity(intent); 9961 // There is no way to know if the word was indeed added. Re-check. 9962 // TODO The ExtractEditText should remove the span in the original text instead 9963 editable.removeSpan(suggestionInfo.suggestionSpan); 9964 updateSpellCheckSpans(spanStart, spanEnd, false); 9965 } else { 9966 // SuggestionSpans are removed by replace: save them before 9967 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 9968 SuggestionSpan.class); 9969 final int length = suggestionSpans.length; 9970 int[] suggestionSpansStarts = new int[length]; 9971 int[] suggestionSpansEnds = new int[length]; 9972 int[] suggestionSpansFlags = new int[length]; 9973 for (int i = 0; i < length; i++) { 9974 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 9975 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 9976 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 9977 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 9978 9979 // Remove potential misspelled flags 9980 int suggestionSpanFlags = suggestionSpan.getFlags(); 9981 if ((suggestionSpanFlags & SuggestionSpan.FLAG_MISSPELLED) > 0) { 9982 suggestionSpanFlags &= ~SuggestionSpan.FLAG_MISSPELLED; 9983 suggestionSpanFlags &= ~SuggestionSpan.FLAG_EASY_CORRECT; 9984 suggestionSpan.setFlags(suggestionSpanFlags); 9985 } 9986 } 9987 9988 final int suggestionStart = suggestionInfo.suggestionStart; 9989 final int suggestionEnd = suggestionInfo.suggestionEnd; 9990 final String suggestion = suggestionInfo.text.subSequence( 9991 suggestionStart, suggestionEnd).toString(); 9992 replaceText_internal(spanStart, spanEnd, suggestion); 9993 9994 // Notify source IME of the suggestion pick. Do this before swaping texts. 9995 if (!TextUtils.isEmpty( 9996 suggestionInfo.suggestionSpan.getNotificationTargetClassName())) { 9997 InputMethodManager imm = InputMethodManager.peekInstance(); 9998 if (imm != null) { 9999 imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText, 10000 suggestionInfo.suggestionIndex); 10001 } 10002 } 10003 10004 // Swap text content between actual text and Suggestion span 10005 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 10006 suggestions[suggestionInfo.suggestionIndex] = originalText; 10007 10008 // Restore previous SuggestionSpans 10009 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 10010 for (int i = 0; i < length; i++) { 10011 // Only spans that include the modified region make sense after replacement 10012 // Spans partially included in the replaced region are removed, there is no 10013 // way to assign them a valid range after replacement 10014 if (suggestionSpansStarts[i] <= spanStart && 10015 suggestionSpansEnds[i] >= spanEnd) { 10016 setSpan_internal(suggestionSpans[i], suggestionSpansStarts[i], 10017 suggestionSpansEnds[i] + lengthDifference, suggestionSpansFlags[i]); 10018 } 10019 } 10020 10021 // Move cursor at the end of the replaced word 10022 final int newCursorPosition = spanEnd + lengthDifference; 10023 setCursorPosition_internal(newCursorPosition, newCursorPosition); 10024 } 10025 10026 hide(); 10027 } 10028 } 10029 10030 /** 10031 * Removes the suggestion spans. 10032 */ 10033 CharSequence removeSuggestionSpans(CharSequence text) { 10034 if (text instanceof Spanned) { 10035 Spannable spannable; 10036 if (text instanceof Spannable) { 10037 spannable = (Spannable) text; 10038 } else { 10039 spannable = new SpannableString(text); 10040 text = spannable; 10041 } 10042 10043 SuggestionSpan[] spans = spannable.getSpans(0, text.length(), SuggestionSpan.class); 10044 for (int i = 0; i < spans.length; i++) { 10045 spannable.removeSpan(spans[i]); 10046 } 10047 } 10048 return text; 10049 } 10050 10051 void showSuggestions() { 10052 if (mSuggestionsPopupWindow == null) { 10053 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 10054 } 10055 hideControllers(); 10056 mSuggestionsPopupWindow.show(); 10057 } 10058 10059 boolean areSuggestionsShown() { 10060 return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing(); 10061 } 10062 10063 /** 10064 * Return whether or not suggestions are enabled on this TextView. The suggestions are generated 10065 * by the IME or by the spell checker as the user types. This is done by adding 10066 * {@link SuggestionSpan}s to the text. 10067 * 10068 * When suggestions are enabled (default), this list of suggestions will be displayed when the 10069 * user asks for them on these parts of the text. This value depends on the inputType of this 10070 * TextView. 10071 * 10072 * The class of the input type must be {@link InputType#TYPE_CLASS_TEXT}. 10073 * 10074 * In addition, the type variation must be one of 10075 * {@link InputType#TYPE_TEXT_VARIATION_NORMAL}, 10076 * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, 10077 * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, 10078 * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or 10079 * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. 10080 * 10081 * And finally, the {@link InputType#TYPE_TEXT_FLAG_NO_SUGGESTIONS} flag must <i>not</i> be set. 10082 * 10083 * @return true if the suggestions popup window is enabled, based on the inputType. 10084 */ 10085 public boolean isSuggestionsEnabled() { 10086 if ((mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) return false; 10087 if ((mInputType & InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) > 0) return false; 10088 10089 final int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 10090 return (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL || 10091 variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT || 10092 variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE || 10093 variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE || 10094 variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT); 10095 } 10096 10097 /** 10098 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 10099 * selection is initiated in this View. 10100 * 10101 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 10102 * Paste actions, depending on what this View supports. 10103 * 10104 * A custom implementation can add new entries in the default menu in its 10105 * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The 10106 * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and 10107 * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} 10108 * or {@link android.R.id#paste} ids as parameters. 10109 * 10110 * Returning false from 10111 * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent 10112 * the action mode from being started. 10113 * 10114 * Action click events should be handled by the custom implementation of 10115 * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 10116 * 10117 * Note that text selection mode is not started when a TextView receives focus and the 10118 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 10119 * that case, to allow for quick replacement. 10120 */ 10121 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 10122 mCustomSelectionActionModeCallback = actionModeCallback; 10123 } 10124 10125 /** 10126 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 10127 * 10128 * @return The current custom selection callback. 10129 */ 10130 public ActionMode.Callback getCustomSelectionActionModeCallback() { 10131 return mCustomSelectionActionModeCallback; 10132 } 10133 10134 /** 10135 * 10136 * @return true if the selection mode was actually started. 10137 */ 10138 private boolean startSelectionActionMode() { 10139 if (mSelectionActionMode != null) { 10140 // Selection action mode is already started 10141 return false; 10142 } 10143 10144 if (!canSelectText() || !requestFocus()) { 10145 Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled."); 10146 return false; 10147 } 10148 10149 if (!hasSelection()) { 10150 // There may already be a selection on device rotation 10151 if (!selectCurrentWord()) { 10152 // No word found under cursor or text selection not permitted. 10153 return false; 10154 } 10155 } 10156 10157 boolean willExtract = extractedTextModeWillBeStarted(); 10158 10159 // Do not start the action mode when extracted text will show up full screen, which would 10160 // immediately hide the newly created action bar and would be visually distracting. 10161 if (!willExtract) { 10162 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 10163 mSelectionActionMode = startActionMode(actionModeCallback); 10164 } 10165 10166 final boolean selectionStarted = mSelectionActionMode != null || willExtract; 10167 if (selectionStarted && !mTextIsSelectable) { 10168 // Show the IME to be able to replace text, except when selecting non editable text. 10169 final InputMethodManager imm = InputMethodManager.peekInstance(); 10170 if (imm != null) { 10171 imm.showSoftInput(this, 0, null); 10172 } 10173 } 10174 10175 return selectionStarted; 10176 } 10177 10178 private boolean extractedTextModeWillBeStarted() { 10179 if (!(this instanceof ExtractEditText)) { 10180 final InputMethodManager imm = InputMethodManager.peekInstance(); 10181 return imm != null && imm.isFullscreenMode(); 10182 } 10183 return false; 10184 } 10185 10186 /** 10187 * @hide 10188 */ 10189 protected void stopSelectionActionMode() { 10190 if (mSelectionActionMode != null) { 10191 // This will hide the mSelectionModifierCursorController 10192 mSelectionActionMode.finish(); 10193 } 10194 } 10195 10196 /** 10197 * Paste clipboard content between min and max positions. 10198 */ 10199 private void paste(int min, int max) { 10200 ClipboardManager clipboard = 10201 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 10202 ClipData clip = clipboard.getPrimaryClip(); 10203 if (clip != null) { 10204 boolean didFirst = false; 10205 for (int i=0; i<clip.getItemCount(); i++) { 10206 CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); 10207 if (paste != null) { 10208 if (!didFirst) { 10209 long minMax = prepareSpacesAroundPaste(min, max, paste); 10210 min = extractRangeStartFromLong(minMax); 10211 max = extractRangeEndFromLong(minMax); 10212 Selection.setSelection((Spannable) mText, max); 10213 ((Editable) mText).replace(min, max, paste); 10214 didFirst = true; 10215 } else { 10216 ((Editable) mText).insert(getSelectionEnd(), "\n"); 10217 ((Editable) mText).insert(getSelectionEnd(), paste); 10218 } 10219 } 10220 } 10221 stopSelectionActionMode(); 10222 sLastCutOrCopyTime = 0; 10223 } 10224 } 10225 10226 private void setPrimaryClip(ClipData clip) { 10227 ClipboardManager clipboard = (ClipboardManager) getContext(). 10228 getSystemService(Context.CLIPBOARD_SERVICE); 10229 clipboard.setPrimaryClip(clip); 10230 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 10231 } 10232 10233 /** 10234 * An ActionMode Callback class that is used to provide actions while in text selection mode. 10235 * 10236 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 10237 * on which of these this TextView supports. 10238 */ 10239 private class SelectionActionModeCallback implements ActionMode.Callback { 10240 10241 @Override 10242 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 10243 TypedArray styledAttributes = mContext.obtainStyledAttributes( 10244 com.android.internal.R.styleable.SelectionModeDrawables); 10245 10246 boolean allowText = getContext().getResources().getBoolean( 10247 com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon); 10248 10249 mode.setTitle(allowText ? 10250 mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null); 10251 mode.setSubtitle(null); 10252 10253 int selectAllIconId = 0; // No icon by default 10254 if (!allowText) { 10255 // Provide an icon, text will not be displayed on smaller screens. 10256 selectAllIconId = styledAttributes.getResourceId( 10257 R.styleable.SelectionModeDrawables_actionModeSelectAllDrawable, 0); 10258 } 10259 10260 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 10261 setIcon(selectAllIconId). 10262 setAlphabeticShortcut('a'). 10263 setShowAsAction( 10264 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10265 10266 if (canCut()) { 10267 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 10268 setIcon(styledAttributes.getResourceId( 10269 R.styleable.SelectionModeDrawables_actionModeCutDrawable, 0)). 10270 setAlphabeticShortcut('x'). 10271 setShowAsAction( 10272 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10273 } 10274 10275 if (canCopy()) { 10276 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 10277 setIcon(styledAttributes.getResourceId( 10278 R.styleable.SelectionModeDrawables_actionModeCopyDrawable, 0)). 10279 setAlphabeticShortcut('c'). 10280 setShowAsAction( 10281 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10282 } 10283 10284 if (canPaste()) { 10285 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 10286 setIcon(styledAttributes.getResourceId( 10287 R.styleable.SelectionModeDrawables_actionModePasteDrawable, 0)). 10288 setAlphabeticShortcut('v'). 10289 setShowAsAction( 10290 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 10291 } 10292 10293 styledAttributes.recycle(); 10294 10295 if (mCustomSelectionActionModeCallback != null) { 10296 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 10297 // The custom mode can choose to cancel the action mode 10298 return false; 10299 } 10300 } 10301 10302 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 10303 getSelectionController().show(); 10304 return true; 10305 } else { 10306 return false; 10307 } 10308 } 10309 10310 @Override 10311 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 10312 if (mCustomSelectionActionModeCallback != null) { 10313 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 10314 } 10315 return true; 10316 } 10317 10318 @Override 10319 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 10320 if (mCustomSelectionActionModeCallback != null && 10321 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 10322 return true; 10323 } 10324 return onTextContextMenuItem(item.getItemId()); 10325 } 10326 10327 @Override 10328 public void onDestroyActionMode(ActionMode mode) { 10329 if (mCustomSelectionActionModeCallback != null) { 10330 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 10331 } 10332 Selection.setSelection((Spannable) mText, getSelectionEnd()); 10333 10334 if (mSelectionModifierCursorController != null) { 10335 mSelectionModifierCursorController.hide(); 10336 } 10337 10338 mSelectionActionMode = null; 10339 } 10340 } 10341 10342 private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener { 10343 private static final int POPUP_TEXT_LAYOUT = 10344 com.android.internal.R.layout.text_edit_action_popup_text; 10345 private TextView mPasteTextView; 10346 private TextView mReplaceTextView; 10347 10348 @Override 10349 protected void createPopupWindow() { 10350 mPopupWindow = new PopupWindow(TextView.this.mContext, null, 10351 com.android.internal.R.attr.textSelectHandleWindowStyle); 10352 mPopupWindow.setClippingEnabled(true); 10353 } 10354 10355 @Override 10356 protected void initContentView() { 10357 LinearLayout linearLayout = new LinearLayout(TextView.this.getContext()); 10358 linearLayout.setOrientation(LinearLayout.HORIZONTAL); 10359 mContentView = linearLayout; 10360 mContentView.setBackgroundResource( 10361 com.android.internal.R.drawable.text_edit_paste_window); 10362 10363 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 10364 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 10365 10366 LayoutParams wrapContent = new LayoutParams( 10367 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 10368 10369 mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 10370 mPasteTextView.setLayoutParams(wrapContent); 10371 mContentView.addView(mPasteTextView); 10372 mPasteTextView.setText(com.android.internal.R.string.paste); 10373 mPasteTextView.setOnClickListener(this); 10374 10375 mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 10376 mReplaceTextView.setLayoutParams(wrapContent); 10377 mContentView.addView(mReplaceTextView); 10378 mReplaceTextView.setText(com.android.internal.R.string.replace); 10379 mReplaceTextView.setOnClickListener(this); 10380 } 10381 10382 @Override 10383 public void show() { 10384 boolean canPaste = canPaste(); 10385 boolean canSuggest = isSuggestionsEnabled() && isCursorInsideSuggestionSpan(); 10386 mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE); 10387 mReplaceTextView.setVisibility(canSuggest ? View.VISIBLE : View.GONE); 10388 10389 if (!canPaste && !canSuggest) return; 10390 10391 super.show(); 10392 } 10393 10394 @Override 10395 public void onClick(View view) { 10396 if (view == mPasteTextView && canPaste()) { 10397 onTextContextMenuItem(ID_PASTE); 10398 hide(); 10399 } else if (view == mReplaceTextView) { 10400 final int middle = (getSelectionStart() + getSelectionEnd()) / 2; 10401 stopSelectionActionMode(); 10402 Selection.setSelection((Spannable) mText, middle); 10403 showSuggestions(); 10404 } 10405 } 10406 10407 @Override 10408 protected int getTextOffset() { 10409 return (getSelectionStart() + getSelectionEnd()) / 2; 10410 } 10411 10412 @Override 10413 protected int getVerticalLocalPosition(int line) { 10414 return mLayout.getLineTop(line) - mContentView.getMeasuredHeight(); 10415 } 10416 10417 @Override 10418 protected int clipVertically(int positionY) { 10419 if (positionY < 0) { 10420 final int offset = getTextOffset(); 10421 final int line = mLayout.getLineForOffset(offset); 10422 positionY += mLayout.getLineBottom(line) - mLayout.getLineTop(line); 10423 positionY += mContentView.getMeasuredHeight(); 10424 10425 // Assumes insertion and selection handles share the same height 10426 final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes); 10427 positionY += handle.getIntrinsicHeight(); 10428 } 10429 10430 return positionY; 10431 } 10432 } 10433 10434 private abstract class HandleView extends View implements TextViewPositionListener { 10435 protected Drawable mDrawable; 10436 protected Drawable mDrawableLtr; 10437 protected Drawable mDrawableRtl; 10438 private final PopupWindow mContainer; 10439 // Position with respect to the parent TextView 10440 private int mPositionX, mPositionY; 10441 private boolean mIsDragging; 10442 // Offset from touch position to mPosition 10443 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 10444 protected int mHotspotX; 10445 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 10446 private float mTouchOffsetY; 10447 // Where the touch position should be on the handle to ensure a maximum cursor visibility 10448 private float mIdealVerticalOffset; 10449 // Parent's (TextView) previous position in window 10450 private int mLastParentX, mLastParentY; 10451 // Transient action popup window for Paste and Replace actions 10452 protected ActionPopupWindow mActionPopupWindow; 10453 // Previous text character offset 10454 private int mPreviousOffset = -1; 10455 // Previous text character offset 10456 private boolean mPositionHasChanged = true; 10457 // Used to delay the appearance of the action popup window 10458 private Runnable mActionPopupShower; 10459 10460 public HandleView(Drawable drawableLtr, Drawable drawableRtl) { 10461 super(TextView.this.mContext); 10462 mContainer = new PopupWindow(TextView.this.mContext, null, 10463 com.android.internal.R.attr.textSelectHandleWindowStyle); 10464 mContainer.setSplitTouchEnabled(true); 10465 mContainer.setClippingEnabled(false); 10466 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 10467 mContainer.setContentView(this); 10468 10469 mDrawableLtr = drawableLtr; 10470 mDrawableRtl = drawableRtl; 10471 10472 updateDrawable(); 10473 10474 final int handleHeight = mDrawable.getIntrinsicHeight(); 10475 mTouchOffsetY = -0.3f * handleHeight; 10476 mIdealVerticalOffset = 0.7f * handleHeight; 10477 } 10478 10479 protected void updateDrawable() { 10480 final int offset = getCurrentCursorOffset(); 10481 final boolean isRtlCharAtOffset = mLayout.isRtlCharAt(offset); 10482 mDrawable = isRtlCharAtOffset ? mDrawableRtl : mDrawableLtr; 10483 mHotspotX = getHotspotX(mDrawable, isRtlCharAtOffset); 10484 } 10485 10486 protected abstract int getHotspotX(Drawable drawable, boolean isRtlRun); 10487 10488 // Touch-up filter: number of previous positions remembered 10489 private static final int HISTORY_SIZE = 5; 10490 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 10491 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 10492 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 10493 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 10494 private int mPreviousOffsetIndex = 0; 10495 private int mNumberPreviousOffsets = 0; 10496 10497 private void startTouchUpFilter(int offset) { 10498 mNumberPreviousOffsets = 0; 10499 addPositionToTouchUpFilter(offset); 10500 } 10501 10502 private void addPositionToTouchUpFilter(int offset) { 10503 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 10504 mPreviousOffsets[mPreviousOffsetIndex] = offset; 10505 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 10506 mNumberPreviousOffsets++; 10507 } 10508 10509 private void filterOnTouchUp() { 10510 final long now = SystemClock.uptimeMillis(); 10511 int i = 0; 10512 int index = mPreviousOffsetIndex; 10513 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 10514 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 10515 i++; 10516 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 10517 } 10518 10519 if (i > 0 && i < iMax && 10520 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 10521 positionAtCursorOffset(mPreviousOffsets[index], false); 10522 } 10523 } 10524 10525 public boolean offsetHasBeenChanged() { 10526 return mNumberPreviousOffsets > 1; 10527 } 10528 10529 @Override 10530 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 10531 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 10532 } 10533 10534 public void show() { 10535 if (isShowing()) return; 10536 10537 getPositionListener().addSubscriber(this, true /* local position may change */); 10538 10539 // Make sure the offset is always considered new, even when focusing at same position 10540 mPreviousOffset = -1; 10541 positionAtCursorOffset(getCurrentCursorOffset(), false); 10542 10543 hideActionPopupWindow(); 10544 } 10545 10546 protected void dismiss() { 10547 mIsDragging = false; 10548 mContainer.dismiss(); 10549 onDetached(); 10550 } 10551 10552 public void hide() { 10553 dismiss(); 10554 10555 TextView.this.getPositionListener().removeSubscriber(this); 10556 } 10557 10558 void showActionPopupWindow(int delay) { 10559 if (mActionPopupWindow == null) { 10560 mActionPopupWindow = new ActionPopupWindow(); 10561 } 10562 if (mActionPopupShower == null) { 10563 mActionPopupShower = new Runnable() { 10564 public void run() { 10565 mActionPopupWindow.show(); 10566 } 10567 }; 10568 } else { 10569 TextView.this.removeCallbacks(mActionPopupShower); 10570 } 10571 TextView.this.postDelayed(mActionPopupShower, delay); 10572 } 10573 10574 protected void hideActionPopupWindow() { 10575 if (mActionPopupShower != null) { 10576 TextView.this.removeCallbacks(mActionPopupShower); 10577 } 10578 if (mActionPopupWindow != null) { 10579 mActionPopupWindow.hide(); 10580 } 10581 } 10582 10583 public boolean isShowing() { 10584 return mContainer.isShowing(); 10585 } 10586 10587 private boolean isVisible() { 10588 // Always show a dragging handle. 10589 if (mIsDragging) { 10590 return true; 10591 } 10592 10593 if (isInBatchEditMode()) { 10594 return false; 10595 } 10596 10597 return TextView.this.isPositionVisible(mPositionX + mHotspotX, mPositionY); 10598 } 10599 10600 public abstract int getCurrentCursorOffset(); 10601 10602 protected abstract void updateSelection(int offset); 10603 10604 public abstract void updatePosition(float x, float y); 10605 10606 protected void positionAtCursorOffset(int offset, boolean parentScrolled) { 10607 // A HandleView relies on the layout, which may be nulled by external methods 10608 if (mLayout == null) { 10609 // Will update controllers' state, hiding them and stopping selection mode if needed 10610 prepareCursorControllers(); 10611 return; 10612 } 10613 10614 if (offset != mPreviousOffset || parentScrolled) { 10615 updateSelection(offset); 10616 addPositionToTouchUpFilter(offset); 10617 final int line = mLayout.getLineForOffset(offset); 10618 10619 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 10620 mPositionY = mLayout.getLineBottom(line); 10621 10622 // Take TextView's padding and scroll into account. 10623 mPositionX += viewportToContentHorizontalOffset(); 10624 mPositionY += viewportToContentVerticalOffset(); 10625 10626 mPreviousOffset = offset; 10627 mPositionHasChanged = true; 10628 } 10629 } 10630 10631 public void updatePosition(int parentPositionX, int parentPositionY, 10632 boolean parentPositionChanged, boolean parentScrolled) { 10633 positionAtCursorOffset(getCurrentCursorOffset(), parentScrolled); 10634 if (parentPositionChanged || mPositionHasChanged) { 10635 if (mIsDragging) { 10636 // Update touchToWindow offset in case of parent scrolling while dragging 10637 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) { 10638 mTouchToWindowOffsetX += parentPositionX - mLastParentX; 10639 mTouchToWindowOffsetY += parentPositionY - mLastParentY; 10640 mLastParentX = parentPositionX; 10641 mLastParentY = parentPositionY; 10642 } 10643 10644 onHandleMoved(); 10645 } 10646 10647 if (isVisible()) { 10648 final int positionX = parentPositionX + mPositionX; 10649 final int positionY = parentPositionY + mPositionY; 10650 if (isShowing()) { 10651 mContainer.update(positionX, positionY, -1, -1); 10652 } else { 10653 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, 10654 positionX, positionY); 10655 } 10656 } else { 10657 if (isShowing()) { 10658 dismiss(); 10659 } 10660 } 10661 10662 mPositionHasChanged = false; 10663 } 10664 } 10665 10666 @Override 10667 protected void onDraw(Canvas c) { 10668 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10669 mDrawable.draw(c); 10670 } 10671 10672 @Override 10673 public boolean onTouchEvent(MotionEvent ev) { 10674 switch (ev.getActionMasked()) { 10675 case MotionEvent.ACTION_DOWN: { 10676 startTouchUpFilter(getCurrentCursorOffset()); 10677 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 10678 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 10679 10680 final PositionListener positionListener = getPositionListener(); 10681 mLastParentX = positionListener.getPositionX(); 10682 mLastParentY = positionListener.getPositionY(); 10683 mIsDragging = true; 10684 break; 10685 } 10686 10687 case MotionEvent.ACTION_MOVE: { 10688 final float rawX = ev.getRawX(); 10689 final float rawY = ev.getRawY(); 10690 10691 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 10692 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 10693 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 10694 float newVerticalOffset; 10695 if (previousVerticalOffset < mIdealVerticalOffset) { 10696 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 10697 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 10698 } else { 10699 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 10700 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 10701 } 10702 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 10703 10704 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 10705 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 10706 10707 updatePosition(newPosX, newPosY); 10708 break; 10709 } 10710 10711 case MotionEvent.ACTION_UP: 10712 filterOnTouchUp(); 10713 mIsDragging = false; 10714 break; 10715 10716 case MotionEvent.ACTION_CANCEL: 10717 mIsDragging = false; 10718 break; 10719 } 10720 return true; 10721 } 10722 10723 public boolean isDragging() { 10724 return mIsDragging; 10725 } 10726 10727 void onHandleMoved() { 10728 hideActionPopupWindow(); 10729 } 10730 10731 public void onDetached() { 10732 hideActionPopupWindow(); 10733 } 10734 } 10735 10736 private class InsertionHandleView extends HandleView { 10737 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000; 10738 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 10739 10740 // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow 10741 private float mDownPositionX, mDownPositionY; 10742 private Runnable mHider; 10743 10744 public InsertionHandleView(Drawable drawable) { 10745 super(drawable, drawable); 10746 } 10747 10748 @Override 10749 public void show() { 10750 super.show(); 10751 10752 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 10753 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 10754 showActionPopupWindow(0); 10755 } 10756 10757 hideAfterDelay(); 10758 } 10759 10760 public void showWithActionPopup() { 10761 show(); 10762 showActionPopupWindow(0); 10763 } 10764 10765 private void hideAfterDelay() { 10766 removeHiderCallback(); 10767 if (mHider == null) { 10768 mHider = new Runnable() { 10769 public void run() { 10770 hide(); 10771 } 10772 }; 10773 } 10774 TextView.this.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT); 10775 } 10776 10777 private void removeHiderCallback() { 10778 if (mHider != null) { 10779 TextView.this.removeCallbacks(mHider); 10780 } 10781 } 10782 10783 @Override 10784 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 10785 return drawable.getIntrinsicWidth() / 2; 10786 } 10787 10788 @Override 10789 public boolean onTouchEvent(MotionEvent ev) { 10790 final boolean result = super.onTouchEvent(ev); 10791 10792 switch (ev.getActionMasked()) { 10793 case MotionEvent.ACTION_DOWN: 10794 mDownPositionX = ev.getRawX(); 10795 mDownPositionY = ev.getRawY(); 10796 break; 10797 10798 case MotionEvent.ACTION_UP: 10799 if (!offsetHasBeenChanged()) { 10800 final float deltaX = mDownPositionX - ev.getRawX(); 10801 final float deltaY = mDownPositionY - ev.getRawY(); 10802 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 10803 10804 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 10805 TextView.this.getContext()); 10806 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 10807 10808 if (distanceSquared < touchSlop * touchSlop) { 10809 if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) { 10810 // Tapping on the handle dismisses the displayed action popup 10811 mActionPopupWindow.hide(); 10812 } else { 10813 showWithActionPopup(); 10814 } 10815 } 10816 } 10817 hideAfterDelay(); 10818 break; 10819 10820 case MotionEvent.ACTION_CANCEL: 10821 hideAfterDelay(); 10822 break; 10823 10824 default: 10825 break; 10826 } 10827 10828 return result; 10829 } 10830 10831 @Override 10832 public int getCurrentCursorOffset() { 10833 return TextView.this.getSelectionStart(); 10834 } 10835 10836 @Override 10837 public void updateSelection(int offset) { 10838 Selection.setSelection((Spannable) mText, offset); 10839 } 10840 10841 @Override 10842 public void updatePosition(float x, float y) { 10843 positionAtCursorOffset(getOffsetForPosition(x, y), false); 10844 } 10845 10846 @Override 10847 void onHandleMoved() { 10848 super.onHandleMoved(); 10849 removeHiderCallback(); 10850 } 10851 10852 @Override 10853 public void onDetached() { 10854 super.onDetached(); 10855 removeHiderCallback(); 10856 } 10857 } 10858 10859 private class SelectionStartHandleView extends HandleView { 10860 10861 public SelectionStartHandleView(Drawable drawableLtr, Drawable drawableRtl) { 10862 super(drawableLtr, drawableRtl); 10863 } 10864 10865 @Override 10866 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 10867 if (isRtlRun) { 10868 return drawable.getIntrinsicWidth() / 4; 10869 } else { 10870 return (drawable.getIntrinsicWidth() * 3) / 4; 10871 } 10872 } 10873 10874 @Override 10875 public int getCurrentCursorOffset() { 10876 return TextView.this.getSelectionStart(); 10877 } 10878 10879 @Override 10880 public void updateSelection(int offset) { 10881 Selection.setSelection((Spannable) mText, offset, getSelectionEnd()); 10882 updateDrawable(); 10883 } 10884 10885 @Override 10886 public void updatePosition(float x, float y) { 10887 int offset = getOffsetForPosition(x, y); 10888 10889 // Handles can not cross and selection is at least one character 10890 final int selectionEnd = getSelectionEnd(); 10891 if (offset >= selectionEnd) offset = Math.max(0, selectionEnd - 1); 10892 10893 positionAtCursorOffset(offset, false); 10894 } 10895 10896 public ActionPopupWindow getActionPopupWindow() { 10897 return mActionPopupWindow; 10898 } 10899 } 10900 10901 private class SelectionEndHandleView extends HandleView { 10902 10903 public SelectionEndHandleView(Drawable drawableLtr, Drawable drawableRtl) { 10904 super(drawableLtr, drawableRtl); 10905 } 10906 10907 @Override 10908 protected int getHotspotX(Drawable drawable, boolean isRtlRun) { 10909 if (isRtlRun) { 10910 return (drawable.getIntrinsicWidth() * 3) / 4; 10911 } else { 10912 return drawable.getIntrinsicWidth() / 4; 10913 } 10914 } 10915 10916 @Override 10917 public int getCurrentCursorOffset() { 10918 return TextView.this.getSelectionEnd(); 10919 } 10920 10921 @Override 10922 public void updateSelection(int offset) { 10923 Selection.setSelection((Spannable) mText, getSelectionStart(), offset); 10924 updateDrawable(); 10925 } 10926 10927 @Override 10928 public void updatePosition(float x, float y) { 10929 int offset = getOffsetForPosition(x, y); 10930 10931 // Handles can not cross and selection is at least one character 10932 final int selectionStart = getSelectionStart(); 10933 if (offset <= selectionStart) offset = Math.min(selectionStart + 1, mText.length()); 10934 10935 positionAtCursorOffset(offset, false); 10936 } 10937 10938 public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) { 10939 mActionPopupWindow = actionPopupWindow; 10940 } 10941 } 10942 10943 /** 10944 * A CursorController instance can be used to control a cursor in the text. 10945 * It is not used outside of {@link TextView}. 10946 * @hide 10947 */ 10948 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 10949 /** 10950 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 10951 * See also {@link #hide()}. 10952 */ 10953 public void show(); 10954 10955 /** 10956 * Hide the cursor controller from screen. 10957 * See also {@link #show()}. 10958 */ 10959 public void hide(); 10960 10961 /** 10962 * Called when the view is detached from window. Perform house keeping task, such as 10963 * stopping Runnable thread that would otherwise keep a reference on the context, thus 10964 * preventing the activity from being recycled. 10965 */ 10966 public void onDetached(); 10967 } 10968 10969 private class InsertionPointCursorController implements CursorController { 10970 private InsertionHandleView mHandle; 10971 10972 public void show() { 10973 getHandle().show(); 10974 } 10975 10976 public void showWithActionPopup() { 10977 getHandle().showWithActionPopup(); 10978 } 10979 10980 public void hide() { 10981 if (mHandle != null) { 10982 mHandle.hide(); 10983 } 10984 } 10985 10986 public void onTouchModeChanged(boolean isInTouchMode) { 10987 if (!isInTouchMode) { 10988 hide(); 10989 } 10990 } 10991 10992 private InsertionHandleView getHandle() { 10993 if (mSelectHandleCenter == null) { 10994 mSelectHandleCenter = mContext.getResources().getDrawable( 10995 mTextSelectHandleRes); 10996 } 10997 if (mHandle == null) { 10998 mHandle = new InsertionHandleView(mSelectHandleCenter); 10999 } 11000 return mHandle; 11001 } 11002 11003 @Override 11004 public void onDetached() { 11005 final ViewTreeObserver observer = getViewTreeObserver(); 11006 observer.removeOnTouchModeChangeListener(this); 11007 11008 if (mHandle != null) mHandle.onDetached(); 11009 } 11010 } 11011 11012 private class SelectionModifierCursorController implements CursorController { 11013 private static final int DELAY_BEFORE_REPLACE_ACTION = 200; // milliseconds 11014 // The cursor controller handles, lazily created when shown. 11015 private SelectionStartHandleView mStartHandle; 11016 private SelectionEndHandleView mEndHandle; 11017 // The offsets of that last touch down event. Remembered to start selection there. 11018 private int mMinTouchOffset, mMaxTouchOffset; 11019 11020 // Double tap detection 11021 private long mPreviousTapUpTime = 0; 11022 private float mDownPositionX, mDownPositionY; 11023 private boolean mGestureStayedInTapRegion; 11024 11025 SelectionModifierCursorController() { 11026 resetTouchOffsets(); 11027 } 11028 11029 public void show() { 11030 if (isInBatchEditMode()) { 11031 return; 11032 } 11033 initDrawables(); 11034 initHandles(); 11035 hideInsertionPointCursorController(); 11036 } 11037 11038 private void initDrawables() { 11039 if (mSelectHandleLeft == null) { 11040 mSelectHandleLeft = mContext.getResources().getDrawable( 11041 mTextSelectHandleLeftRes); 11042 } 11043 if (mSelectHandleRight == null) { 11044 mSelectHandleRight = mContext.getResources().getDrawable( 11045 mTextSelectHandleRightRes); 11046 } 11047 } 11048 11049 private void initHandles() { 11050 // Lazy object creation has to be done before updatePosition() is called. 11051 if (mStartHandle == null) { 11052 mStartHandle = new SelectionStartHandleView(mSelectHandleLeft, mSelectHandleRight); 11053 } 11054 if (mEndHandle == null) { 11055 mEndHandle = new SelectionEndHandleView(mSelectHandleRight, mSelectHandleLeft); 11056 } 11057 11058 mStartHandle.show(); 11059 mEndHandle.show(); 11060 11061 // Make sure both left and right handles share the same ActionPopupWindow (so that 11062 // moving any of the handles hides the action popup). 11063 mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION); 11064 mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow()); 11065 11066 hideInsertionPointCursorController(); 11067 } 11068 11069 public void hide() { 11070 if (mStartHandle != null) mStartHandle.hide(); 11071 if (mEndHandle != null) mEndHandle.hide(); 11072 } 11073 11074 public void onTouchEvent(MotionEvent event) { 11075 // This is done even when the View does not have focus, so that long presses can start 11076 // selection and tap can move cursor from this tap position. 11077 switch (event.getActionMasked()) { 11078 case MotionEvent.ACTION_DOWN: 11079 final float x = event.getX(); 11080 final float y = event.getY(); 11081 11082 // Remember finger down position, to be able to start selection from there 11083 mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y); 11084 11085 // Double tap detection 11086 if (mGestureStayedInTapRegion) { 11087 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 11088 if (duration <= ViewConfiguration.getDoubleTapTimeout()) { 11089 final float deltaX = x - mDownPositionX; 11090 final float deltaY = y - mDownPositionY; 11091 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 11092 11093 ViewConfiguration viewConfiguration = ViewConfiguration.get( 11094 TextView.this.getContext()); 11095 int doubleTapSlop = viewConfiguration.getScaledDoubleTapSlop(); 11096 boolean stayedInArea = distanceSquared < doubleTapSlop * doubleTapSlop; 11097 11098 if (stayedInArea && isPositionOnText(x, y)) { 11099 startSelectionActionMode(); 11100 mDiscardNextActionUp = true; 11101 } 11102 } 11103 } 11104 11105 mDownPositionX = x; 11106 mDownPositionY = y; 11107 mGestureStayedInTapRegion = true; 11108 break; 11109 11110 case MotionEvent.ACTION_POINTER_DOWN: 11111 case MotionEvent.ACTION_POINTER_UP: 11112 // Handle multi-point gestures. Keep min and max offset positions. 11113 // Only activated for devices that correctly handle multi-touch. 11114 if (mContext.getPackageManager().hasSystemFeature( 11115 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 11116 updateMinAndMaxOffsets(event); 11117 } 11118 break; 11119 11120 case MotionEvent.ACTION_MOVE: 11121 if (mGestureStayedInTapRegion) { 11122 final float deltaX = event.getX() - mDownPositionX; 11123 final float deltaY = event.getY() - mDownPositionY; 11124 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 11125 11126 final ViewConfiguration viewConfiguration = ViewConfiguration.get( 11127 TextView.this.getContext()); 11128 int doubleTapTouchSlop = viewConfiguration.getScaledDoubleTapTouchSlop(); 11129 11130 if (distanceSquared > doubleTapTouchSlop * doubleTapTouchSlop) { 11131 mGestureStayedInTapRegion = false; 11132 } 11133 } 11134 break; 11135 11136 case MotionEvent.ACTION_UP: 11137 mPreviousTapUpTime = SystemClock.uptimeMillis(); 11138 break; 11139 } 11140 } 11141 11142 /** 11143 * @param event 11144 */ 11145 private void updateMinAndMaxOffsets(MotionEvent event) { 11146 int pointerCount = event.getPointerCount(); 11147 for (int index = 0; index < pointerCount; index++) { 11148 int offset = getOffsetForPosition(event.getX(index), event.getY(index)); 11149 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 11150 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 11151 } 11152 } 11153 11154 public int getMinTouchOffset() { 11155 return mMinTouchOffset; 11156 } 11157 11158 public int getMaxTouchOffset() { 11159 return mMaxTouchOffset; 11160 } 11161 11162 public void resetTouchOffsets() { 11163 mMinTouchOffset = mMaxTouchOffset = -1; 11164 } 11165 11166 /** 11167 * @return true iff this controller is currently used to move the selection start. 11168 */ 11169 public boolean isSelectionStartDragged() { 11170 return mStartHandle != null && mStartHandle.isDragging(); 11171 } 11172 11173 public void onTouchModeChanged(boolean isInTouchMode) { 11174 if (!isInTouchMode) { 11175 hide(); 11176 } 11177 } 11178 11179 @Override 11180 public void onDetached() { 11181 final ViewTreeObserver observer = getViewTreeObserver(); 11182 observer.removeOnTouchModeChangeListener(this); 11183 11184 if (mStartHandle != null) mStartHandle.onDetached(); 11185 if (mEndHandle != null) mEndHandle.onDetached(); 11186 } 11187 } 11188 11189 private void hideInsertionPointCursorController() { 11190 // No need to create the controller to hide it. 11191 if (mInsertionPointCursorController != null) { 11192 mInsertionPointCursorController.hide(); 11193 } 11194 } 11195 11196 /** 11197 * Hides the insertion controller and stops text selection mode, hiding the selection controller 11198 */ 11199 private void hideControllers() { 11200 hideCursorControllers(); 11201 hideSpanControllers(); 11202 } 11203 11204 private void hideSpanControllers() { 11205 if (mChangeWatcher != null) { 11206 mChangeWatcher.hideControllers(); 11207 } 11208 } 11209 11210 private void hideCursorControllers() { 11211 if (mSuggestionsPopupWindow != null && !mSuggestionsPopupWindow.isShowingUp()) { 11212 // Should be done before hide insertion point controller since it triggers a show of it 11213 mSuggestionsPopupWindow.hide(); 11214 } 11215 hideInsertionPointCursorController(); 11216 stopSelectionActionMode(); 11217 } 11218 11219 /** 11220 * Get the character offset closest to the specified absolute position. A typical use case is to 11221 * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. 11222 * 11223 * @param x The horizontal absolute position of a point on screen 11224 * @param y The vertical absolute position of a point on screen 11225 * @return the character offset for the character whose position is closest to the specified 11226 * position. Returns -1 if there is no layout. 11227 */ 11228 public int getOffsetForPosition(float x, float y) { 11229 if (getLayout() == null) return -1; 11230 final int line = getLineAtCoordinate(y); 11231 final int offset = getOffsetAtCoordinate(line, x); 11232 return offset; 11233 } 11234 11235 private float convertToLocalHorizontalCoordinate(float x) { 11236 x -= getTotalPaddingLeft(); 11237 // Clamp the position to inside of the view. 11238 x = Math.max(0.0f, x); 11239 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 11240 x += getScrollX(); 11241 return x; 11242 } 11243 11244 private int getLineAtCoordinate(float y) { 11245 y -= getTotalPaddingTop(); 11246 // Clamp the position to inside of the view. 11247 y = Math.max(0.0f, y); 11248 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 11249 y += getScrollY(); 11250 return getLayout().getLineForVertical((int) y); 11251 } 11252 11253 private int getOffsetAtCoordinate(int line, float x) { 11254 x = convertToLocalHorizontalCoordinate(x); 11255 return getLayout().getOffsetForHorizontal(line, x); 11256 } 11257 11258 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 11259 * in the view. Returns false when the position is in the empty space of left/right of text. 11260 */ 11261 private boolean isPositionOnText(float x, float y) { 11262 if (getLayout() == null) return false; 11263 11264 final int line = getLineAtCoordinate(y); 11265 x = convertToLocalHorizontalCoordinate(x); 11266 11267 if (x < getLayout().getLineLeft(line)) return false; 11268 if (x > getLayout().getLineRight(line)) return false; 11269 return true; 11270 } 11271 11272 @Override 11273 public boolean onDragEvent(DragEvent event) { 11274 switch (event.getAction()) { 11275 case DragEvent.ACTION_DRAG_STARTED: 11276 return hasInsertionController(); 11277 11278 case DragEvent.ACTION_DRAG_ENTERED: 11279 TextView.this.requestFocus(); 11280 return true; 11281 11282 case DragEvent.ACTION_DRAG_LOCATION: 11283 final int offset = getOffsetForPosition(event.getX(), event.getY()); 11284 Selection.setSelection((Spannable)mText, offset); 11285 return true; 11286 11287 case DragEvent.ACTION_DROP: 11288 onDrop(event); 11289 return true; 11290 11291 case DragEvent.ACTION_DRAG_ENDED: 11292 case DragEvent.ACTION_DRAG_EXITED: 11293 default: 11294 return true; 11295 } 11296 } 11297 11298 private void onDrop(DragEvent event) { 11299 StringBuilder content = new StringBuilder(""); 11300 ClipData clipData = event.getClipData(); 11301 final int itemCount = clipData.getItemCount(); 11302 for (int i=0; i < itemCount; i++) { 11303 Item item = clipData.getItemAt(i); 11304 content.append(item.coerceToText(TextView.this.mContext)); 11305 } 11306 11307 final int offset = getOffsetForPosition(event.getX(), event.getY()); 11308 11309 Object localState = event.getLocalState(); 11310 DragLocalState dragLocalState = null; 11311 if (localState instanceof DragLocalState) { 11312 dragLocalState = (DragLocalState) localState; 11313 } 11314 boolean dragDropIntoItself = dragLocalState != null && 11315 dragLocalState.sourceTextView == this; 11316 11317 if (dragDropIntoItself) { 11318 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 11319 // A drop inside the original selection discards the drop. 11320 return; 11321 } 11322 } 11323 11324 final int originalLength = mText.length(); 11325 long minMax = prepareSpacesAroundPaste(offset, offset, content); 11326 int min = extractRangeStartFromLong(minMax); 11327 int max = extractRangeEndFromLong(minMax); 11328 11329 Selection.setSelection((Spannable) mText, max); 11330 replaceText_internal(min, max, content); 11331 11332 if (dragDropIntoItself) { 11333 int dragSourceStart = dragLocalState.start; 11334 int dragSourceEnd = dragLocalState.end; 11335 if (max <= dragSourceStart) { 11336 // Inserting text before selection has shifted positions 11337 final int shift = mText.length() - originalLength; 11338 dragSourceStart += shift; 11339 dragSourceEnd += shift; 11340 } 11341 11342 // Delete original selection 11343 deleteText_internal(dragSourceStart, dragSourceEnd); 11344 11345 // Make sure we do not leave two adjacent spaces. 11346 if ((dragSourceStart == 0 || 11347 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 11348 (dragSourceStart == mText.length() || 11349 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 11350 final int pos = dragSourceStart == mText.length() ? 11351 dragSourceStart - 1 : dragSourceStart; 11352 deleteText_internal(pos, pos + 1); 11353 } 11354 } 11355 } 11356 11357 /** 11358 * @return True if this view supports insertion handles. 11359 */ 11360 boolean hasInsertionController() { 11361 return mInsertionControllerEnabled; 11362 } 11363 11364 /** 11365 * @return True if this view supports selection handles. 11366 */ 11367 boolean hasSelectionController() { 11368 return mSelectionControllerEnabled; 11369 } 11370 11371 InsertionPointCursorController getInsertionController() { 11372 if (!mInsertionControllerEnabled) { 11373 return null; 11374 } 11375 11376 if (mInsertionPointCursorController == null) { 11377 mInsertionPointCursorController = new InsertionPointCursorController(); 11378 11379 final ViewTreeObserver observer = getViewTreeObserver(); 11380 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 11381 } 11382 11383 return mInsertionPointCursorController; 11384 } 11385 11386 SelectionModifierCursorController getSelectionController() { 11387 if (!mSelectionControllerEnabled) { 11388 return null; 11389 } 11390 11391 if (mSelectionModifierCursorController == null) { 11392 mSelectionModifierCursorController = new SelectionModifierCursorController(); 11393 11394 final ViewTreeObserver observer = getViewTreeObserver(); 11395 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 11396 } 11397 11398 return mSelectionModifierCursorController; 11399 } 11400 11401 boolean isInBatchEditMode() { 11402 final InputMethodState ims = mInputMethodState; 11403 if (ims != null) { 11404 return ims.mBatchEditNesting > 0; 11405 } 11406 return mInBatchEditControllers; 11407 } 11408 11409 @Override 11410 public void onResolveTextDirection() { 11411 if (hasPasswordTransformationMethod()) { 11412 mTextDir = TextDirectionHeuristics.LOCALE; 11413 return; 11414 } 11415 11416 // Always need to resolve layout direction first 11417 final boolean defaultIsRtl = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 11418 11419 // Now, we can select the heuristic 11420 int textDir = getResolvedTextDirection(); 11421 switch (textDir) { 11422 default: 11423 case TEXT_DIRECTION_FIRST_STRONG: 11424 mTextDir = (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL : 11425 TextDirectionHeuristics.FIRSTSTRONG_LTR); 11426 break; 11427 case TEXT_DIRECTION_ANY_RTL: 11428 mTextDir = TextDirectionHeuristics.ANYRTL_LTR; 11429 break; 11430 case TEXT_DIRECTION_LTR: 11431 mTextDir = TextDirectionHeuristics.LTR; 11432 break; 11433 case TEXT_DIRECTION_RTL: 11434 mTextDir = TextDirectionHeuristics.RTL; 11435 break; 11436 case TEXT_DIRECTION_LOCALE: 11437 mTextDir = TextDirectionHeuristics.LOCALE; 11438 break; 11439 } 11440 } 11441 11442 /** 11443 * Subclasses will need to override this method to implement their own way of resolving 11444 * drawables depending on the layout direction. 11445 * 11446 * A call to the super method will be required from the subclasses implementation. 11447 */ 11448 protected void resolveDrawables() { 11449 // No need to resolve twice 11450 if (mResolvedDrawables) { 11451 return; 11452 } 11453 // No drawable to resolve 11454 if (mDrawables == null) { 11455 return; 11456 } 11457 // No relative drawable to resolve 11458 if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) { 11459 mResolvedDrawables = true; 11460 return; 11461 } 11462 11463 Drawables dr = mDrawables; 11464 switch(getResolvedLayoutDirection()) { 11465 case LAYOUT_DIRECTION_RTL: 11466 if (dr.mDrawableStart != null) { 11467 dr.mDrawableRight = dr.mDrawableStart; 11468 11469 dr.mDrawableSizeRight = dr.mDrawableSizeStart; 11470 dr.mDrawableHeightRight = dr.mDrawableHeightStart; 11471 } 11472 if (dr.mDrawableEnd != null) { 11473 dr.mDrawableLeft = dr.mDrawableEnd; 11474 11475 dr.mDrawableSizeLeft = dr.mDrawableSizeEnd; 11476 dr.mDrawableHeightLeft = dr.mDrawableHeightEnd; 11477 } 11478 break; 11479 11480 case LAYOUT_DIRECTION_LTR: 11481 default: 11482 if (dr.mDrawableStart != null) { 11483 dr.mDrawableLeft = dr.mDrawableStart; 11484 11485 dr.mDrawableSizeLeft = dr.mDrawableSizeStart; 11486 dr.mDrawableHeightLeft = dr.mDrawableHeightStart; 11487 } 11488 if (dr.mDrawableEnd != null) { 11489 dr.mDrawableRight = dr.mDrawableEnd; 11490 11491 dr.mDrawableSizeRight = dr.mDrawableSizeEnd; 11492 dr.mDrawableHeightRight = dr.mDrawableHeightEnd; 11493 } 11494 break; 11495 } 11496 mResolvedDrawables = true; 11497 } 11498 11499 protected void resetResolvedDrawables() { 11500 mResolvedDrawables = false; 11501 } 11502 11503 /** 11504 * @hide 11505 */ 11506 protected void viewClicked(InputMethodManager imm) { 11507 if (imm != null) { 11508 imm.viewClicked(this); 11509 } 11510 } 11511 11512 /** 11513 * Deletes the range of text [start, end[. 11514 * @hide 11515 */ 11516 protected void deleteText_internal(int start, int end) { 11517 ((Editable) mText).delete(start, end); 11518 } 11519 11520 /** 11521 * Replaces the range of text [start, end[ by replacement text 11522 * @hide 11523 */ 11524 protected void replaceText_internal(int start, int end, CharSequence text) { 11525 ((Editable) mText).replace(start, end, text); 11526 } 11527 11528 /** 11529 * Sets a span on the specified range of text 11530 * @hide 11531 */ 11532 protected void setSpan_internal(Object span, int start, int end, int flags) { 11533 ((Editable) mText).setSpan(span, start, end, flags); 11534 } 11535 11536 /** 11537 * Moves the cursor to the specified offset position in text 11538 * @hide 11539 */ 11540 protected void setCursorPosition_internal(int start, int end) { 11541 Selection.setSelection(((Editable) mText), start, end); 11542 } 11543 11544 @ViewDebug.ExportedProperty(category = "text") 11545 private CharSequence mText; 11546 private CharSequence mTransformed; 11547 private BufferType mBufferType = BufferType.NORMAL; 11548 11549 private int mInputType = EditorInfo.TYPE_NULL; 11550 private CharSequence mHint; 11551 private Layout mHintLayout; 11552 11553 private KeyListener mInput; 11554 11555 private MovementMethod mMovement; 11556 private TransformationMethod mTransformation; 11557 private boolean mAllowTransformationLengthChange; 11558 private ChangeWatcher mChangeWatcher; 11559 11560 private ArrayList<TextWatcher> mListeners = null; 11561 11562 // display attributes 11563 private final TextPaint mTextPaint; 11564 private boolean mUserSetTextScaleX; 11565 private final Paint mHighlightPaint; 11566 private int mHighlightColor = 0x6633B5E5; 11567 private Layout mLayout; 11568 11569 private long mShowCursor; 11570 private Blink mBlink; 11571 private boolean mCursorVisible = true; 11572 11573 // Cursor Controllers. 11574 private InsertionPointCursorController mInsertionPointCursorController; 11575 private SelectionModifierCursorController mSelectionModifierCursorController; 11576 private ActionMode mSelectionActionMode; 11577 private boolean mInsertionControllerEnabled; 11578 private boolean mSelectionControllerEnabled; 11579 private boolean mInBatchEditControllers; 11580 11581 private boolean mSelectAllOnFocus = false; 11582 11583 private int mGravity = Gravity.TOP | Gravity.START; 11584 private boolean mHorizontallyScrolling; 11585 11586 private int mAutoLinkMask; 11587 private boolean mLinksClickable = true; 11588 11589 private float mSpacingMult = 1.0f; 11590 private float mSpacingAdd = 0.0f; 11591 private boolean mTextIsSelectable = false; 11592 11593 private static final int LINES = 1; 11594 private static final int EMS = LINES; 11595 private static final int PIXELS = 2; 11596 11597 private int mMaximum = Integer.MAX_VALUE; 11598 private int mMaxMode = LINES; 11599 private int mMinimum = 0; 11600 private int mMinMode = LINES; 11601 11602 private int mOldMaximum = mMaximum; 11603 private int mOldMaxMode = mMaxMode; 11604 11605 private int mMaxWidth = Integer.MAX_VALUE; 11606 private int mMaxWidthMode = PIXELS; 11607 private int mMinWidth = 0; 11608 private int mMinWidthMode = PIXELS; 11609 11610 private boolean mSingleLine; 11611 private int mDesiredHeightAtMeasure = -1; 11612 private boolean mIncludePad = true; 11613 11614 // tmp primitives, so we don't alloc them on each draw 11615 private Path mHighlightPath; 11616 private boolean mHighlightPathBogus = true; 11617 private static final RectF sTempRect = new RectF(); 11618 private static final float[] sTmpPosition = new float[2]; 11619 11620 // XXX should be much larger 11621 private static final int VERY_WIDE = 1024*1024; 11622 11623 private static final int BLINK = 500; 11624 11625 private static final int ANIMATED_SCROLL_GAP = 250; 11626 private long mLastScroll; 11627 private Scroller mScroller = null; 11628 11629 private BoringLayout.Metrics mBoring; 11630 private BoringLayout.Metrics mHintBoring; 11631 11632 private BoringLayout mSavedLayout, mSavedHintLayout; 11633 11634 private TextDirectionHeuristic mTextDir = null; 11635 11636 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 11637 private InputFilter[] mFilters = NO_FILTERS; 11638 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 11639 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 11640 // System wide time for last cut or copy action. 11641 private static long sLastCutOrCopyTime; 11642 // Used to highlight a word when it is corrected by the IME 11643 private CorrectionHighlighter mCorrectionHighlighter; 11644 // New state used to change background based on whether this TextView is multiline. 11645 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 11646} 11647