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