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