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