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