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