TextView.java revision aa85a4c8b7abf82c54ecbad29e4266581c65c3f9
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 hideControllers(); 3948 } 3949 3950 @Override 3951 protected boolean isPaddingOffsetRequired() { 3952 return mShadowRadius != 0 || mDrawables != null; 3953 } 3954 3955 @Override 3956 protected int getLeftPaddingOffset() { 3957 return getCompoundPaddingLeft() - mPaddingLeft + 3958 (int) Math.min(0, mShadowDx - mShadowRadius); 3959 } 3960 3961 @Override 3962 protected int getTopPaddingOffset() { 3963 return (int) Math.min(0, mShadowDy - mShadowRadius); 3964 } 3965 3966 @Override 3967 protected int getBottomPaddingOffset() { 3968 return (int) Math.max(0, mShadowDy + mShadowRadius); 3969 } 3970 3971 @Override 3972 protected int getRightPaddingOffset() { 3973 return -(getCompoundPaddingRight() - mPaddingRight) + 3974 (int) Math.max(0, mShadowDx + mShadowRadius); 3975 } 3976 3977 @Override 3978 protected boolean verifyDrawable(Drawable who) { 3979 final boolean verified = super.verifyDrawable(who); 3980 if (!verified && mDrawables != null) { 3981 return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || 3982 who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom; 3983 } 3984 return verified; 3985 } 3986 3987 @Override 3988 public void jumpDrawablesToCurrentState() { 3989 super.jumpDrawablesToCurrentState(); 3990 if (mDrawables != null) { 3991 if (mDrawables.mDrawableLeft != null) { 3992 mDrawables.mDrawableLeft.jumpToCurrentState(); 3993 } 3994 if (mDrawables.mDrawableTop != null) { 3995 mDrawables.mDrawableTop.jumpToCurrentState(); 3996 } 3997 if (mDrawables.mDrawableRight != null) { 3998 mDrawables.mDrawableRight.jumpToCurrentState(); 3999 } 4000 if (mDrawables.mDrawableBottom != null) { 4001 mDrawables.mDrawableBottom.jumpToCurrentState(); 4002 } 4003 } 4004 } 4005 4006 @Override 4007 public void invalidateDrawable(Drawable drawable) { 4008 if (verifyDrawable(drawable)) { 4009 final Rect dirty = drawable.getBounds(); 4010 int scrollX = mScrollX; 4011 int scrollY = mScrollY; 4012 4013 // IMPORTANT: The coordinates below are based on the coordinates computed 4014 // for each compound drawable in onDraw(). Make sure to update each section 4015 // accordingly. 4016 final TextView.Drawables drawables = mDrawables; 4017 if (drawables != null) { 4018 if (drawable == drawables.mDrawableLeft) { 4019 final int compoundPaddingTop = getCompoundPaddingTop(); 4020 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4021 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4022 4023 scrollX += mPaddingLeft; 4024 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 4025 } else if (drawable == drawables.mDrawableRight) { 4026 final int compoundPaddingTop = getCompoundPaddingTop(); 4027 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4028 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4029 4030 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 4031 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 4032 } else if (drawable == drawables.mDrawableTop) { 4033 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4034 final int compoundPaddingRight = getCompoundPaddingRight(); 4035 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4036 4037 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 4038 scrollY += mPaddingTop; 4039 } else if (drawable == drawables.mDrawableBottom) { 4040 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4041 final int compoundPaddingRight = getCompoundPaddingRight(); 4042 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4043 4044 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 4045 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 4046 } 4047 } 4048 4049 invalidate(dirty.left + scrollX, dirty.top + scrollY, 4050 dirty.right + scrollX, dirty.bottom + scrollY); 4051 } 4052 } 4053 4054 @Override 4055 protected boolean onSetAlpha(int alpha) { 4056 if (mMovement == null && getBackground() == null) { 4057 mCurrentAlpha = alpha; 4058 final Drawables dr = mDrawables; 4059 if (dr != null) { 4060 if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha); 4061 if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha); 4062 if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha); 4063 if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha); 4064 } 4065 return true; 4066 } 4067 return false; 4068 } 4069 4070 /** 4071 * When a TextView is used to display a useful piece of information to the user (such as a 4072 * contact's address), it should be made selectable, so that the user can select and copy this 4073 * content. 4074 * 4075 * Use {@link #setTextIsSelectable(boolean)} or the 4076 * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView 4077 * selectable (the text is not selectable by default). Note that the content of an EditText is 4078 * always selectable. 4079 * 4080 * @return True if the text displayed in this TextView can be selected by the user. 4081 * 4082 * @attr ref android.R.styleable#TextView_textIsSelectable 4083 */ 4084 public boolean isTextSelectable() { 4085 return mTextIsSelectable; 4086 } 4087 4088 /** 4089 * Sets whether or not (default) the content of this view is selectable by the user. 4090 * 4091 * See {@link #isTextSelectable} for details. 4092 * 4093 * @param selectable Whether or not the content of this TextView should be selectable. 4094 */ 4095 public void setTextIsSelectable(boolean selectable) { 4096 if (mTextIsSelectable == selectable) return; 4097 4098 mTextIsSelectable = selectable; 4099 4100 setFocusableInTouchMode(selectable); 4101 setFocusable(selectable); 4102 setClickable(selectable); 4103 setLongClickable(selectable); 4104 4105 // mInputType is already EditorInfo.TYPE_NULL and mInput is null; 4106 4107 setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); 4108 setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL); 4109 4110 // Called by setText above, but safer in case of future code changes 4111 prepareCursorControllers(); 4112 } 4113 4114 @Override 4115 protected int[] onCreateDrawableState(int extraSpace) { 4116 final int[] drawableState = super.onCreateDrawableState(extraSpace); 4117 if (mTextIsSelectable) { 4118 // Disable pressed state, which was introduced when TextView was made clickable. 4119 // Prevents text color change. 4120 // setClickable(false) would have a similar effect, but it also disables focus changes 4121 // and long press actions, which are both needed by text selection. 4122 final int length = drawableState.length; 4123 for (int i = 0; i < length; i++) { 4124 if (drawableState[i] == R.attr.state_pressed) { 4125 final int[] nonPressedState = new int[length - 1]; 4126 System.arraycopy(drawableState, 0, nonPressedState, 0, i); 4127 System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); 4128 return nonPressedState; 4129 } 4130 } 4131 } 4132 return drawableState; 4133 } 4134 4135 @Override 4136 protected void onDraw(Canvas canvas) { 4137 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return; 4138 4139 restartMarqueeIfNeeded(); 4140 4141 // Draw the background for this view 4142 super.onDraw(canvas); 4143 4144 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4145 final int compoundPaddingTop = getCompoundPaddingTop(); 4146 final int compoundPaddingRight = getCompoundPaddingRight(); 4147 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4148 final int scrollX = mScrollX; 4149 final int scrollY = mScrollY; 4150 final int right = mRight; 4151 final int left = mLeft; 4152 final int bottom = mBottom; 4153 final int top = mTop; 4154 4155 final Drawables dr = mDrawables; 4156 if (dr != null) { 4157 /* 4158 * Compound, not extended, because the icon is not clipped 4159 * if the text height is smaller. 4160 */ 4161 4162 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 4163 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 4164 4165 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4166 // Make sure to update invalidateDrawable() when changing this code. 4167 if (dr.mDrawableLeft != null) { 4168 canvas.save(); 4169 canvas.translate(scrollX + mPaddingLeft, 4170 scrollY + compoundPaddingTop + 4171 (vspace - dr.mDrawableHeightLeft) / 2); 4172 dr.mDrawableLeft.draw(canvas); 4173 canvas.restore(); 4174 } 4175 4176 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4177 // Make sure to update invalidateDrawable() when changing this code. 4178 if (dr.mDrawableRight != null) { 4179 canvas.save(); 4180 canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight, 4181 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 4182 dr.mDrawableRight.draw(canvas); 4183 canvas.restore(); 4184 } 4185 4186 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4187 // Make sure to update invalidateDrawable() when changing this code. 4188 if (dr.mDrawableTop != null) { 4189 canvas.save(); 4190 canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, 4191 scrollY + mPaddingTop); 4192 dr.mDrawableTop.draw(canvas); 4193 canvas.restore(); 4194 } 4195 4196 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4197 // Make sure to update invalidateDrawable() when changing this code. 4198 if (dr.mDrawableBottom != null) { 4199 canvas.save(); 4200 canvas.translate(scrollX + compoundPaddingLeft + 4201 (hspace - dr.mDrawableWidthBottom) / 2, 4202 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 4203 dr.mDrawableBottom.draw(canvas); 4204 canvas.restore(); 4205 } 4206 } 4207 4208 if (mPreDrawState == PREDRAW_DONE) { 4209 final ViewTreeObserver observer = getViewTreeObserver(); 4210 if (observer != null) { 4211 observer.removeOnPreDrawListener(this); 4212 mPreDrawState = PREDRAW_NOT_REGISTERED; 4213 } 4214 } 4215 4216 int color = mCurTextColor; 4217 4218 if (mLayout == null) { 4219 assumeLayout(); 4220 } 4221 4222 Layout layout = mLayout; 4223 int cursorcolor = color; 4224 4225 if (mHint != null && mText.length() == 0) { 4226 if (mHintTextColor != null) { 4227 color = mCurHintTextColor; 4228 } 4229 4230 layout = mHintLayout; 4231 } 4232 4233 mTextPaint.setColor(color); 4234 mTextPaint.setAlpha(mCurrentAlpha); 4235 mTextPaint.drawableState = getDrawableState(); 4236 4237 canvas.save(); 4238 /* Would be faster if we didn't have to do this. Can we chop the 4239 (displayable) text so that we don't need to do this ever? 4240 */ 4241 4242 int extendedPaddingTop = getExtendedPaddingTop(); 4243 int extendedPaddingBottom = getExtendedPaddingBottom(); 4244 4245 float clipLeft = compoundPaddingLeft + scrollX; 4246 float clipTop = extendedPaddingTop + scrollY; 4247 float clipRight = right - left - compoundPaddingRight + scrollX; 4248 float clipBottom = bottom - top - extendedPaddingBottom + scrollY; 4249 4250 if (mShadowRadius != 0) { 4251 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 4252 clipRight += Math.max(0, mShadowDx + mShadowRadius); 4253 4254 clipTop += Math.min(0, mShadowDy - mShadowRadius); 4255 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 4256 } 4257 4258 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 4259 4260 int voffsetText = 0; 4261 int voffsetCursor = 0; 4262 4263 // translate in by our padding 4264 { 4265 /* shortcircuit calling getVerticaOffset() */ 4266 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4267 voffsetText = getVerticalOffset(false); 4268 voffsetCursor = getVerticalOffset(true); 4269 } 4270 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 4271 } 4272 4273 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 4274 if (!mSingleLine && getLineCount() == 1 && canMarquee() && 4275 (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 4276 canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft - 4277 getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f); 4278 } 4279 4280 if (mMarquee != null && mMarquee.isRunning()) { 4281 canvas.translate(-mMarquee.mScroll, 0.0f); 4282 } 4283 } 4284 4285 Path highlight = null; 4286 int selStart = -1, selEnd = -1; 4287 4288 // If there is no movement method, then there can be no selection. 4289 // Check that first and attempt to skip everything having to do with 4290 // the cursor. 4291 // XXX This is not strictly true -- a program could set the 4292 // selection manually if it really wanted to. 4293 if (mMovement != null && (isFocused() || isPressed())) { 4294 selStart = getSelectionStart(); 4295 selEnd = getSelectionEnd(); 4296 4297 if ((mCursorVisible || mTextIsSelectable) && selStart >= 0 && isEnabled()) { 4298 if (mHighlightPath == null) 4299 mHighlightPath = new Path(); 4300 4301 if (selStart == selEnd) { 4302 if (!mTextIsSelectable && 4303 (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) { 4304 if (mHighlightPathBogus) { 4305 mHighlightPath.reset(); 4306 mLayout.getCursorPath(selStart, mHighlightPath, mText); 4307 mHighlightPathBogus = false; 4308 } 4309 4310 // XXX should pass to skin instead of drawing directly 4311 mHighlightPaint.setColor(cursorcolor); 4312 mHighlightPaint.setStyle(Paint.Style.STROKE); 4313 4314 highlight = mHighlightPath; 4315 } 4316 } else { 4317 if (mHighlightPathBogus) { 4318 mHighlightPath.reset(); 4319 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 4320 mHighlightPathBogus = false; 4321 } 4322 4323 // XXX should pass to skin instead of drawing directly 4324 mHighlightPaint.setColor(mHighlightColor); 4325 mHighlightPaint.setStyle(Paint.Style.FILL); 4326 4327 highlight = mHighlightPath; 4328 } 4329 } 4330 } 4331 4332 /* Comment out until we decide what to do about animations 4333 boolean isLinearTextOn = false; 4334 if (currentTransformation != null) { 4335 isLinearTextOn = mTextPaint.isLinearTextOn(); 4336 Matrix m = currentTransformation.getMatrix(); 4337 if (!m.isIdentity()) { 4338 // mTextPaint.setLinearTextOn(true); 4339 } 4340 } 4341 */ 4342 4343 final InputMethodState ims = mInputMethodState; 4344 final int cursorOffsetVertical = voffsetCursor - voffsetText; 4345 if (ims != null && ims.mBatchEditNesting == 0) { 4346 InputMethodManager imm = InputMethodManager.peekInstance(); 4347 if (imm != null) { 4348 if (imm.isActive(this)) { 4349 boolean reported = false; 4350 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4351 // We are in extract mode and the content has changed 4352 // in some way... just report complete new text to the 4353 // input method. 4354 reported = reportExtractedText(); 4355 } 4356 if (!reported && highlight != null) { 4357 int candStart = -1; 4358 int candEnd = -1; 4359 if (mText instanceof Spannable) { 4360 Spannable sp = (Spannable)mText; 4361 candStart = EditableInputConnection.getComposingSpanStart(sp); 4362 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 4363 } 4364 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 4365 } 4366 } 4367 4368 if (imm.isWatchingCursor(this) && highlight != null) { 4369 highlight.computeBounds(ims.mTmpRectF, true); 4370 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 4371 4372 canvas.getMatrix().mapPoints(ims.mTmpOffset); 4373 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 4374 4375 ims.mTmpRectF.offset(0, cursorOffsetVertical); 4376 4377 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 4378 (int)(ims.mTmpRectF.top + 0.5), 4379 (int)(ims.mTmpRectF.right + 0.5), 4380 (int)(ims.mTmpRectF.bottom + 0.5)); 4381 4382 imm.updateCursor(this, 4383 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 4384 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 4385 } 4386 } 4387 } 4388 4389 if (mCorrectionHighlighter != null) { 4390 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 4391 } 4392 4393 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 4394 4395 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 4396 canvas.translate((int) mMarquee.getGhostOffset(), 0.0f); 4397 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 4398 } 4399 4400 /* Comment out until we decide what to do about animations 4401 if (currentTransformation != null) { 4402 mTextPaint.setLinearTextOn(isLinearTextOn); 4403 } 4404 */ 4405 4406 canvas.restore(); 4407 4408 updateCursorControllerPositions(); 4409 } 4410 4411 /** 4412 * Update the positions of the CursorControllers. Needed by WebTextView, 4413 * which does not draw. 4414 * @hide 4415 */ 4416 protected void updateCursorControllerPositions() { 4417 // No need to create the controllers if they were not already 4418 if (mInsertionPointCursorController != null && 4419 mInsertionPointCursorController.isShowing()) { 4420 mInsertionPointCursorController.updatePosition(); 4421 } 4422 if (mSelectionModifierCursorController != null && 4423 mSelectionModifierCursorController.isShowing()) { 4424 mSelectionModifierCursorController.updatePosition(); 4425 } 4426 } 4427 4428 @Override 4429 public void getFocusedRect(Rect r) { 4430 if (mLayout == null) { 4431 super.getFocusedRect(r); 4432 return; 4433 } 4434 4435 int sel = getSelectionEnd(); 4436 if (sel < 0) { 4437 super.getFocusedRect(r); 4438 return; 4439 } 4440 4441 int line = mLayout.getLineForOffset(sel); 4442 r.top = mLayout.getLineTop(line); 4443 r.bottom = mLayout.getLineBottom(line); 4444 4445 r.left = (int) mLayout.getPrimaryHorizontal(sel); 4446 r.right = r.left + 1; 4447 4448 // Adjust for padding and gravity. 4449 int paddingLeft = getCompoundPaddingLeft(); 4450 int paddingTop = getExtendedPaddingTop(); 4451 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4452 paddingTop += getVerticalOffset(false); 4453 } 4454 r.offset(paddingLeft, paddingTop); 4455 } 4456 4457 /** 4458 * Return the number of lines of text, or 0 if the internal Layout has not 4459 * been built. 4460 */ 4461 public int getLineCount() { 4462 return mLayout != null ? mLayout.getLineCount() : 0; 4463 } 4464 4465 /** 4466 * Return the baseline for the specified line (0...getLineCount() - 1) 4467 * If bounds is not null, return the top, left, right, bottom extents 4468 * of the specified line in it. If the internal Layout has not been built, 4469 * return 0 and set bounds to (0, 0, 0, 0) 4470 * @param line which line to examine (0..getLineCount() - 1) 4471 * @param bounds Optional. If not null, it returns the extent of the line 4472 * @return the Y-coordinate of the baseline 4473 */ 4474 public int getLineBounds(int line, Rect bounds) { 4475 if (mLayout == null) { 4476 if (bounds != null) { 4477 bounds.set(0, 0, 0, 0); 4478 } 4479 return 0; 4480 } 4481 else { 4482 int baseline = mLayout.getLineBounds(line, bounds); 4483 4484 int voffset = getExtendedPaddingTop(); 4485 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4486 voffset += getVerticalOffset(true); 4487 } 4488 if (bounds != null) { 4489 bounds.offset(getCompoundPaddingLeft(), voffset); 4490 } 4491 return baseline + voffset; 4492 } 4493 } 4494 4495 @Override 4496 public int getBaseline() { 4497 if (mLayout == null) { 4498 return super.getBaseline(); 4499 } 4500 4501 int voffset = 0; 4502 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4503 voffset = getVerticalOffset(true); 4504 } 4505 4506 return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); 4507 } 4508 4509 @Override 4510 public boolean onKeyDown(int keyCode, KeyEvent event) { 4511 int which = doKeyDown(keyCode, event, null); 4512 if (which == 0) { 4513 // Go through default dispatching. 4514 return super.onKeyDown(keyCode, event); 4515 } 4516 4517 return true; 4518 } 4519 4520 @Override 4521 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4522 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 4523 4524 int which = doKeyDown(keyCode, down, event); 4525 if (which == 0) { 4526 // Go through default dispatching. 4527 return super.onKeyMultiple(keyCode, repeatCount, event); 4528 } 4529 if (which == -1) { 4530 // Consumed the whole thing. 4531 return true; 4532 } 4533 4534 repeatCount--; 4535 4536 // We are going to dispatch the remaining events to either the input 4537 // or movement method. To do this, we will just send a repeated stream 4538 // of down and up events until we have done the complete repeatCount. 4539 // It would be nice if those interfaces had an onKeyMultiple() method, 4540 // but adding that is a more complicated change. 4541 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 4542 if (which == 1) { 4543 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4544 while (--repeatCount > 0) { 4545 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 4546 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4547 } 4548 if (mError != null && !mErrorWasChanged) { 4549 setError(null, null); 4550 } 4551 4552 } else if (which == 2) { 4553 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4554 while (--repeatCount > 0) { 4555 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 4556 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4557 } 4558 } 4559 4560 return true; 4561 } 4562 4563 /** 4564 * Returns true if pressing ENTER in this field advances focus instead 4565 * of inserting the character. This is true mostly in single-line fields, 4566 * but also in mail addresses and subjects which will display on multiple 4567 * lines but where it doesn't make sense to insert newlines. 4568 */ 4569 private boolean shouldAdvanceFocusOnEnter() { 4570 if (mInput == null) { 4571 return false; 4572 } 4573 4574 if (mSingleLine) { 4575 return true; 4576 } 4577 4578 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 4579 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 4580 4581 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 4582 variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 4583 return true; 4584 } 4585 } 4586 4587 return false; 4588 } 4589 4590 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 4591 if (!isEnabled()) { 4592 return 0; 4593 } 4594 4595 switch (keyCode) { 4596 case KeyEvent.KEYCODE_ENTER: 4597 mEnterKeyIsDown = true; 4598 // If ALT modifier is held, then we always insert a 4599 // newline character. 4600 if ((event.getMetaState()&KeyEvent.META_ALT_ON) == 0) { 4601 4602 // When mInputContentType is set, we know that we are 4603 // running in a "modern" cupcake environment, so don't need 4604 // to worry about the application trying to capture 4605 // enter key events. 4606 if (mInputContentType != null) { 4607 4608 // If there is an action listener, given them a 4609 // chance to consume the event. 4610 if (mInputContentType.onEditorActionListener != null && 4611 mInputContentType.onEditorActionListener.onEditorAction( 4612 this, EditorInfo.IME_NULL, event)) { 4613 mInputContentType.enterDown = true; 4614 // We are consuming the enter key for them. 4615 return -1; 4616 } 4617 } 4618 4619 // If our editor should move focus when enter is pressed, or 4620 // this is a generated event from an IME action button, then 4621 // don't let it be inserted into the text. 4622 if ((event.getFlags()&KeyEvent.FLAG_EDITOR_ACTION) != 0 4623 || shouldAdvanceFocusOnEnter()) { 4624 return -1; 4625 } 4626 } 4627 break; 4628 4629 case KeyEvent.KEYCODE_DPAD_CENTER: 4630 mDPadCenterIsDown = true; 4631 if (shouldAdvanceFocusOnEnter()) { 4632 return 0; 4633 } 4634 break; 4635 4636 // Has to be done on key down (and not on key up) to correctly be intercepted. 4637 case KeyEvent.KEYCODE_BACK: 4638 if (mSelectionActionMode != null) { 4639 stopSelectionActionMode(); 4640 return -1; 4641 } 4642 break; 4643 } 4644 4645 if (mInput != null) { 4646 /* 4647 * Keep track of what the error was before doing the input 4648 * so that if an input filter changed the error, we leave 4649 * that error showing. Otherwise, we take down whatever 4650 * error was showing when the user types something. 4651 */ 4652 mErrorWasChanged = false; 4653 4654 boolean doDown = true; 4655 if (otherEvent != null) { 4656 try { 4657 beginBatchEdit(); 4658 boolean handled = mInput.onKeyOther(this, (Editable) mText, 4659 otherEvent); 4660 if (mError != null && !mErrorWasChanged) { 4661 setError(null, null); 4662 } 4663 doDown = false; 4664 if (handled) { 4665 return -1; 4666 } 4667 } catch (AbstractMethodError e) { 4668 // onKeyOther was added after 1.0, so if it isn't 4669 // implemented we need to try to dispatch as a regular down. 4670 } finally { 4671 endBatchEdit(); 4672 } 4673 } 4674 4675 if (doDown) { 4676 beginBatchEdit(); 4677 if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) { 4678 endBatchEdit(); 4679 if (mError != null && !mErrorWasChanged) { 4680 setError(null, null); 4681 } 4682 return 1; 4683 } 4684 endBatchEdit(); 4685 } 4686 } 4687 4688 // bug 650865: sometimes we get a key event before a layout. 4689 // don't try to move around if we don't know the layout. 4690 4691 if (mMovement != null && mLayout != null) { 4692 boolean doDown = true; 4693 if (otherEvent != null) { 4694 try { 4695 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 4696 otherEvent); 4697 doDown = false; 4698 if (handled) { 4699 return -1; 4700 } 4701 } catch (AbstractMethodError e) { 4702 // onKeyOther was added after 1.0, so if it isn't 4703 // implemented we need to try to dispatch as a regular down. 4704 } 4705 } 4706 if (doDown) { 4707 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 4708 return 2; 4709 } 4710 } 4711 4712 return 0; 4713 } 4714 4715 @Override 4716 public boolean onKeyUp(int keyCode, KeyEvent event) { 4717 if (!isEnabled()) { 4718 return super.onKeyUp(keyCode, event); 4719 } 4720 4721 hideControllers(); 4722 stopSelectionActionMode(); 4723 4724 switch (keyCode) { 4725 case KeyEvent.KEYCODE_DPAD_CENTER: 4726 mDPadCenterIsDown = false; 4727 /* 4728 * If there is a click listener, just call through to 4729 * super, which will invoke it. 4730 * 4731 * If there isn't a click listener, try to show the soft 4732 * input method. (It will also 4733 * call performClick(), but that won't do anything in 4734 * this case.) 4735 */ 4736 if (mOnClickListener == null) { 4737 if (mMovement != null && mText instanceof Editable 4738 && mLayout != null && onCheckIsTextEditor()) { 4739 InputMethodManager imm = (InputMethodManager) 4740 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 4741 imm.showSoftInput(this, 0); 4742 } 4743 } 4744 return super.onKeyUp(keyCode, event); 4745 4746 case KeyEvent.KEYCODE_ENTER: 4747 mEnterKeyIsDown = false; 4748 if (mInputContentType != null 4749 && mInputContentType.onEditorActionListener != null 4750 && mInputContentType.enterDown) { 4751 mInputContentType.enterDown = false; 4752 if (mInputContentType.onEditorActionListener.onEditorAction( 4753 this, EditorInfo.IME_NULL, event)) { 4754 return true; 4755 } 4756 } 4757 4758 if ((event.getFlags()&KeyEvent.FLAG_EDITOR_ACTION) != 0 4759 || shouldAdvanceFocusOnEnter()) { 4760 /* 4761 * If there is a click listener, just call through to 4762 * super, which will invoke it. 4763 * 4764 * If there isn't a click listener, try to advance focus, 4765 * but still call through to super, which will reset the 4766 * pressed state and longpress state. (It will also 4767 * call performClick(), but that won't do anything in 4768 * this case.) 4769 */ 4770 if (mOnClickListener == null) { 4771 View v = focusSearch(FOCUS_DOWN); 4772 4773 if (v != null) { 4774 if (!v.requestFocus(FOCUS_DOWN)) { 4775 throw new IllegalStateException("focus search returned a view " + 4776 "that wasn't able to take focus!"); 4777 } 4778 4779 /* 4780 * Return true because we handled the key; super 4781 * will return false because there was no click 4782 * listener. 4783 */ 4784 super.onKeyUp(keyCode, event); 4785 return true; 4786 } else if ((event.getFlags() 4787 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 4788 // No target for next focus, but make sure the IME 4789 // if this came from it. 4790 InputMethodManager imm = InputMethodManager.peekInstance(); 4791 if (imm != null) { 4792 imm.hideSoftInputFromWindow(getWindowToken(), 0); 4793 } 4794 } 4795 } 4796 4797 return super.onKeyUp(keyCode, event); 4798 } 4799 break; 4800 } 4801 4802 if (mInput != null) 4803 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 4804 return true; 4805 4806 if (mMovement != null && mLayout != null) 4807 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 4808 return true; 4809 4810 return super.onKeyUp(keyCode, event); 4811 } 4812 4813 @Override public boolean onCheckIsTextEditor() { 4814 return mInputType != EditorInfo.TYPE_NULL; 4815 } 4816 4817 @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4818 if (onCheckIsTextEditor() && isEnabled()) { 4819 if (mInputMethodState == null) { 4820 mInputMethodState = new InputMethodState(); 4821 } 4822 outAttrs.inputType = mInputType; 4823 if (mInputContentType != null) { 4824 outAttrs.imeOptions = mInputContentType.imeOptions; 4825 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 4826 outAttrs.actionLabel = mInputContentType.imeActionLabel; 4827 outAttrs.actionId = mInputContentType.imeActionId; 4828 outAttrs.extras = mInputContentType.extras; 4829 } else { 4830 outAttrs.imeOptions = EditorInfo.IME_NULL; 4831 } 4832 if (focusSearch(FOCUS_DOWN) != null) { 4833 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 4834 } 4835 if (focusSearch(FOCUS_UP) != null) { 4836 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 4837 } 4838 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 4839 == EditorInfo.IME_ACTION_UNSPECIFIED) { 4840 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 4841 // An action has not been set, but the enter key will move to 4842 // the next focus, so set the action to that. 4843 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 4844 } else { 4845 // An action has not been set, and there is no focus to move 4846 // to, so let's just supply a "done" action. 4847 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 4848 } 4849 if (!shouldAdvanceFocusOnEnter()) { 4850 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 4851 } 4852 } 4853 if (isMultilineInputType(outAttrs.inputType)) { 4854 // Multi-line text editors should always show an enter key. 4855 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 4856 } 4857 outAttrs.hintText = mHint; 4858 if (mText instanceof Editable) { 4859 InputConnection ic = new EditableInputConnection(this); 4860 outAttrs.initialSelStart = getSelectionStart(); 4861 outAttrs.initialSelEnd = getSelectionEnd(); 4862 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 4863 return ic; 4864 } 4865 } 4866 return null; 4867 } 4868 4869 /** 4870 * If this TextView contains editable content, extract a portion of it 4871 * based on the information in <var>request</var> in to <var>outText</var>. 4872 * @return Returns true if the text was successfully extracted, else false. 4873 */ 4874 public boolean extractText(ExtractedTextRequest request, 4875 ExtractedText outText) { 4876 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 4877 EXTRACT_UNKNOWN, outText); 4878 } 4879 4880 static final int EXTRACT_NOTHING = -2; 4881 static final int EXTRACT_UNKNOWN = -1; 4882 4883 boolean extractTextInternal(ExtractedTextRequest request, 4884 int partialStartOffset, int partialEndOffset, int delta, 4885 ExtractedText outText) { 4886 final CharSequence content = mText; 4887 if (content != null) { 4888 if (partialStartOffset != EXTRACT_NOTHING) { 4889 final int N = content.length(); 4890 if (partialStartOffset < 0) { 4891 outText.partialStartOffset = outText.partialEndOffset = -1; 4892 partialStartOffset = 0; 4893 partialEndOffset = N; 4894 } else { 4895 // Now use the delta to determine the actual amount of text 4896 // we need. 4897 partialEndOffset += delta; 4898 // Adjust offsets to ensure we contain full spans. 4899 if (content instanceof Spanned) { 4900 Spanned spanned = (Spanned)content; 4901 Object[] spans = spanned.getSpans(partialStartOffset, 4902 partialEndOffset, ParcelableSpan.class); 4903 int i = spans.length; 4904 while (i > 0) { 4905 i--; 4906 int j = spanned.getSpanStart(spans[i]); 4907 if (j < partialStartOffset) partialStartOffset = j; 4908 j = spanned.getSpanEnd(spans[i]); 4909 if (j > partialEndOffset) partialEndOffset = j; 4910 } 4911 } 4912 outText.partialStartOffset = partialStartOffset; 4913 outText.partialEndOffset = partialEndOffset - delta; 4914 4915 if (partialStartOffset > N) { 4916 partialStartOffset = N; 4917 } else if (partialStartOffset < 0) { 4918 partialStartOffset = 0; 4919 } 4920 if (partialEndOffset > N) { 4921 partialEndOffset = N; 4922 } else if (partialEndOffset < 0) { 4923 partialEndOffset = 0; 4924 } 4925 } 4926 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 4927 outText.text = content.subSequence(partialStartOffset, 4928 partialEndOffset); 4929 } else { 4930 outText.text = TextUtils.substring(content, partialStartOffset, 4931 partialEndOffset); 4932 } 4933 } else { 4934 outText.partialStartOffset = 0; 4935 outText.partialEndOffset = 0; 4936 outText.text = ""; 4937 } 4938 outText.flags = 0; 4939 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 4940 outText.flags |= ExtractedText.FLAG_SELECTING; 4941 } 4942 if (mSingleLine) { 4943 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 4944 } 4945 outText.startOffset = 0; 4946 outText.selectionStart = getSelectionStart(); 4947 outText.selectionEnd = getSelectionEnd(); 4948 return true; 4949 } 4950 return false; 4951 } 4952 4953 boolean reportExtractedText() { 4954 final InputMethodState ims = mInputMethodState; 4955 if (ims != null) { 4956 final boolean contentChanged = ims.mContentChanged; 4957 if (contentChanged || ims.mSelectionModeChanged) { 4958 ims.mContentChanged = false; 4959 ims.mSelectionModeChanged = false; 4960 final ExtractedTextRequest req = mInputMethodState.mExtracting; 4961 if (req != null) { 4962 InputMethodManager imm = InputMethodManager.peekInstance(); 4963 if (imm != null) { 4964 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 4965 + ims.mChangedStart + " end=" + ims.mChangedEnd 4966 + " delta=" + ims.mChangedDelta); 4967 if (ims.mChangedStart < 0 && !contentChanged) { 4968 ims.mChangedStart = EXTRACT_NOTHING; 4969 } 4970 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 4971 ims.mChangedDelta, ims.mTmpExtracted)) { 4972 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 4973 + ims.mTmpExtracted.partialStartOffset 4974 + " end=" + ims.mTmpExtracted.partialEndOffset 4975 + ": " + ims.mTmpExtracted.text); 4976 imm.updateExtractedText(this, req.token, 4977 mInputMethodState.mTmpExtracted); 4978 ims.mChangedStart = EXTRACT_UNKNOWN; 4979 ims.mChangedEnd = EXTRACT_UNKNOWN; 4980 ims.mChangedDelta = 0; 4981 ims.mContentChanged = false; 4982 return true; 4983 } 4984 } 4985 } 4986 } 4987 } 4988 return false; 4989 } 4990 4991 /** 4992 * This is used to remove all style-impacting spans from text before new 4993 * extracted text is being replaced into it, so that we don't have any 4994 * lingering spans applied during the replace. 4995 */ 4996 static void removeParcelableSpans(Spannable spannable, int start, int end) { 4997 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 4998 int i = spans.length; 4999 while (i > 0) { 5000 i--; 5001 spannable.removeSpan(spans[i]); 5002 } 5003 } 5004 5005 /** 5006 * Apply to this text view the given extracted text, as previously 5007 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 5008 */ 5009 public void setExtractedText(ExtractedText text) { 5010 Editable content = getEditableText(); 5011 if (text.text != null) { 5012 if (content == null) { 5013 setText(text.text, TextView.BufferType.EDITABLE); 5014 } else if (text.partialStartOffset < 0) { 5015 removeParcelableSpans(content, 0, content.length()); 5016 content.replace(0, content.length(), text.text); 5017 } else { 5018 final int N = content.length(); 5019 int start = text.partialStartOffset; 5020 if (start > N) start = N; 5021 int end = text.partialEndOffset; 5022 if (end > N) end = N; 5023 removeParcelableSpans(content, start, end); 5024 content.replace(start, end, text.text); 5025 } 5026 } 5027 5028 // Now set the selection position... make sure it is in range, to 5029 // avoid crashes. If this is a partial update, it is possible that 5030 // the underlying text may have changed, causing us problems here. 5031 // Also we just don't want to trust clients to do the right thing. 5032 Spannable sp = (Spannable)getText(); 5033 final int N = sp.length(); 5034 int start = text.selectionStart; 5035 if (start < 0) start = 0; 5036 else if (start > N) start = N; 5037 int end = text.selectionEnd; 5038 if (end < 0) end = 0; 5039 else if (end > N) end = N; 5040 Selection.setSelection(sp, start, end); 5041 5042 // Finally, update the selection mode. 5043 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 5044 MetaKeyKeyListener.startSelecting(this, sp); 5045 } else { 5046 MetaKeyKeyListener.stopSelecting(this, sp); 5047 } 5048 } 5049 5050 /** 5051 * @hide 5052 */ 5053 public void setExtracting(ExtractedTextRequest req) { 5054 if (mInputMethodState != null) { 5055 mInputMethodState.mExtracting = req; 5056 } 5057 hideControllers(); 5058 } 5059 5060 /** 5061 * Called by the framework in response to a text completion from 5062 * the current input method, provided by it calling 5063 * {@link InputConnection#commitCompletion 5064 * InputConnection.commitCompletion()}. The default implementation does 5065 * nothing; text views that are supporting auto-completion should override 5066 * this to do their desired behavior. 5067 * 5068 * @param text The auto complete text the user has selected. 5069 */ 5070 public void onCommitCompletion(CompletionInfo text) { 5071 } 5072 5073 /** 5074 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 5075 * a dictionnary) from the current input method, provided by it calling 5076 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 5077 * implementation flashes the background of the corrected word to provide feedback to the user. 5078 * 5079 * @param info The auto correct info about the text that was corrected. 5080 */ 5081 public void onCommitCorrection(CorrectionInfo info) { 5082 if (mCorrectionHighlighter == null) { 5083 mCorrectionHighlighter = new CorrectionHighlighter(); 5084 } else { 5085 mCorrectionHighlighter.invalidate(false); 5086 } 5087 5088 mCorrectionHighlighter.highlight(info); 5089 } 5090 5091 private class CorrectionHighlighter { 5092 private final Path mPath = new Path(); 5093 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5094 private int mStart, mEnd; 5095 private long mFadingStartTime; 5096 private final static int FADE_OUT_DURATION = 400; 5097 5098 public CorrectionHighlighter() { 5099 mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale); 5100 mPaint.setStyle(Paint.Style.FILL); 5101 } 5102 5103 public void highlight(CorrectionInfo info) { 5104 mStart = info.getOffset(); 5105 mEnd = mStart + info.getNewText().length(); 5106 mFadingStartTime = SystemClock.uptimeMillis(); 5107 5108 if (mStart < 0 || mEnd < 0) { 5109 stopAnimation(); 5110 } 5111 } 5112 5113 public void draw(Canvas canvas, int cursorOffsetVertical) { 5114 if (updatePath() && updatePaint()) { 5115 if (cursorOffsetVertical != 0) { 5116 canvas.translate(0, cursorOffsetVertical); 5117 } 5118 5119 canvas.drawPath(mPath, mPaint); 5120 5121 if (cursorOffsetVertical != 0) { 5122 canvas.translate(0, -cursorOffsetVertical); 5123 } 5124 invalidate(true); 5125 } else { 5126 stopAnimation(); 5127 invalidate(false); 5128 } 5129 } 5130 5131 private boolean updatePaint() { 5132 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5133 if (duration > FADE_OUT_DURATION) return false; 5134 5135 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5136 final int highlightColorAlpha = Color.alpha(mHighlightColor); 5137 final int color = (mHighlightColor & 0x00FFFFFF) + 5138 ((int) (highlightColorAlpha * coef) << 24); 5139 mPaint.setColor(color); 5140 return true; 5141 } 5142 5143 private boolean updatePath() { 5144 final Layout layout = TextView.this.mLayout; 5145 if (layout == null) return false; 5146 5147 // Update in case text is edited while the animation is run 5148 final int length = mText.length(); 5149 int start = Math.min(length, mStart); 5150 int end = Math.min(length, mEnd); 5151 5152 mPath.reset(); 5153 TextView.this.mLayout.getSelectionPath(start, end, mPath); 5154 return true; 5155 } 5156 5157 private void invalidate(boolean delayed) { 5158 if (TextView.this.mLayout == null) return; 5159 5160 synchronized (sTempRect) { 5161 mPath.computeBounds(sTempRect, false); 5162 5163 int left = getCompoundPaddingLeft(); 5164 int top = getExtendedPaddingTop() + getVerticalOffset(true); 5165 5166 if (delayed) { 5167 TextView.this.postInvalidateDelayed(16, // 60 Hz update 5168 left + (int) sTempRect.left, top + (int) sTempRect.top, 5169 left + (int) sTempRect.right, top + (int) sTempRect.bottom); 5170 } else { 5171 TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top, 5172 (int) sTempRect.right, (int) sTempRect.bottom); 5173 } 5174 } 5175 } 5176 5177 private void stopAnimation() { 5178 TextView.this.mCorrectionHighlighter = null; 5179 } 5180 } 5181 5182 public void beginBatchEdit() { 5183 mInBatchEditControllers = true; 5184 final InputMethodState ims = mInputMethodState; 5185 if (ims != null) { 5186 int nesting = ++ims.mBatchEditNesting; 5187 if (nesting == 1) { 5188 ims.mCursorChanged = false; 5189 ims.mChangedDelta = 0; 5190 if (ims.mContentChanged) { 5191 // We already have a pending change from somewhere else, 5192 // so turn this into a full update. 5193 ims.mChangedStart = 0; 5194 ims.mChangedEnd = mText.length(); 5195 } else { 5196 ims.mChangedStart = EXTRACT_UNKNOWN; 5197 ims.mChangedEnd = EXTRACT_UNKNOWN; 5198 ims.mContentChanged = false; 5199 } 5200 onBeginBatchEdit(); 5201 } 5202 } 5203 } 5204 5205 public void endBatchEdit() { 5206 mInBatchEditControllers = false; 5207 final InputMethodState ims = mInputMethodState; 5208 if (ims != null) { 5209 int nesting = --ims.mBatchEditNesting; 5210 if (nesting == 0) { 5211 finishBatchEdit(ims); 5212 } 5213 } 5214 } 5215 5216 void ensureEndedBatchEdit() { 5217 final InputMethodState ims = mInputMethodState; 5218 if (ims != null && ims.mBatchEditNesting != 0) { 5219 ims.mBatchEditNesting = 0; 5220 finishBatchEdit(ims); 5221 } 5222 } 5223 5224 void finishBatchEdit(final InputMethodState ims) { 5225 onEndBatchEdit(); 5226 5227 if (ims.mContentChanged || ims.mSelectionModeChanged) { 5228 updateAfterEdit(); 5229 reportExtractedText(); 5230 } else if (ims.mCursorChanged) { 5231 // Cheezy way to get us to report the current cursor location. 5232 invalidateCursor(); 5233 } 5234 } 5235 5236 void updateAfterEdit() { 5237 invalidate(); 5238 int curs = getSelectionStart(); 5239 5240 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == 5241 Gravity.BOTTOM) { 5242 registerForPreDraw(); 5243 } 5244 5245 if (curs >= 0) { 5246 mHighlightPathBogus = true; 5247 5248 if (isFocused()) { 5249 mShowCursor = SystemClock.uptimeMillis(); 5250 makeBlink(); 5251 } 5252 } 5253 5254 checkForResize(); 5255 } 5256 5257 /** 5258 * Called by the framework in response to a request to begin a batch 5259 * of edit operations through a call to link {@link #beginBatchEdit()}. 5260 */ 5261 public void onBeginBatchEdit() { 5262 } 5263 5264 /** 5265 * Called by the framework in response to a request to end a batch 5266 * of edit operations through a call to link {@link #endBatchEdit}. 5267 */ 5268 public void onEndBatchEdit() { 5269 } 5270 5271 /** 5272 * Called by the framework in response to a private command from the 5273 * current method, provided by it calling 5274 * {@link InputConnection#performPrivateCommand 5275 * InputConnection.performPrivateCommand()}. 5276 * 5277 * @param action The action name of the command. 5278 * @param data Any additional data for the command. This may be null. 5279 * @return Return true if you handled the command, else false. 5280 */ 5281 public boolean onPrivateIMECommand(String action, Bundle data) { 5282 return false; 5283 } 5284 5285 private void nullLayouts() { 5286 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 5287 mSavedLayout = (BoringLayout) mLayout; 5288 } 5289 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 5290 mSavedHintLayout = (BoringLayout) mHintLayout; 5291 } 5292 5293 mLayout = mHintLayout = null; 5294 5295 // Since it depends on the value of mLayout 5296 prepareCursorControllers(); 5297 } 5298 5299 /** 5300 * Make a new Layout based on the already-measured size of the view, 5301 * on the assumption that it was measured correctly at some point. 5302 */ 5303 private void assumeLayout() { 5304 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5305 5306 if (width < 1) { 5307 width = 0; 5308 } 5309 5310 int physicalWidth = width; 5311 5312 if (mHorizontallyScrolling) { 5313 width = VERY_WIDE; 5314 } 5315 5316 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 5317 physicalWidth, false); 5318 } 5319 5320 /** 5321 * The width passed in is now the desired layout width, 5322 * not the full view width with padding. 5323 * {@hide} 5324 */ 5325 protected void makeNewLayout(int w, int hintWidth, 5326 BoringLayout.Metrics boring, 5327 BoringLayout.Metrics hintBoring, 5328 int ellipsisWidth, boolean bringIntoView) { 5329 stopMarquee(); 5330 5331 mHighlightPathBogus = true; 5332 5333 if (w < 0) { 5334 w = 0; 5335 } 5336 if (hintWidth < 0) { 5337 hintWidth = 0; 5338 } 5339 5340 Layout.Alignment alignment; 5341 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 5342 case Gravity.CENTER_HORIZONTAL: 5343 alignment = Layout.Alignment.ALIGN_CENTER; 5344 break; 5345 5346 case Gravity.RIGHT: 5347 // Note, Layout resolves ALIGN_OPPOSITE to left or 5348 // right based on the paragraph direction. 5349 alignment = Layout.Alignment.ALIGN_OPPOSITE; 5350 break; 5351 5352 default: 5353 alignment = Layout.Alignment.ALIGN_NORMAL; 5354 } 5355 5356 boolean shouldEllipsize = mEllipsize != null && mInput == null; 5357 5358 if (mText instanceof Spannable) { 5359 mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w, 5360 alignment, mSpacingMult, 5361 mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null, 5362 ellipsisWidth); 5363 } else { 5364 if (boring == UNKNOWN_BORING) { 5365 boring = BoringLayout.isBoring(mTransformed, mTextPaint, 5366 mBoring); 5367 if (boring != null) { 5368 mBoring = boring; 5369 } 5370 } 5371 5372 if (boring != null) { 5373 if (boring.width <= w && 5374 (mEllipsize == null || boring.width <= ellipsisWidth)) { 5375 if (mSavedLayout != null) { 5376 mLayout = mSavedLayout. 5377 replaceOrMake(mTransformed, mTextPaint, 5378 w, alignment, mSpacingMult, mSpacingAdd, 5379 boring, mIncludePad); 5380 } else { 5381 mLayout = BoringLayout.make(mTransformed, mTextPaint, 5382 w, alignment, mSpacingMult, mSpacingAdd, 5383 boring, mIncludePad); 5384 } 5385 5386 mSavedLayout = (BoringLayout) mLayout; 5387 } else if (shouldEllipsize && boring.width <= w) { 5388 if (mSavedLayout != null) { 5389 mLayout = mSavedLayout. 5390 replaceOrMake(mTransformed, mTextPaint, 5391 w, alignment, mSpacingMult, mSpacingAdd, 5392 boring, mIncludePad, mEllipsize, 5393 ellipsisWidth); 5394 } else { 5395 mLayout = BoringLayout.make(mTransformed, mTextPaint, 5396 w, alignment, mSpacingMult, mSpacingAdd, 5397 boring, mIncludePad, mEllipsize, 5398 ellipsisWidth); 5399 } 5400 } else if (shouldEllipsize) { 5401 mLayout = new StaticLayout(mTransformed, 5402 0, mTransformed.length(), 5403 mTextPaint, w, alignment, mSpacingMult, 5404 mSpacingAdd, mIncludePad, mEllipsize, 5405 ellipsisWidth); 5406 } else { 5407 mLayout = new StaticLayout(mTransformed, mTextPaint, 5408 w, alignment, mSpacingMult, mSpacingAdd, 5409 mIncludePad); 5410 } 5411 } else if (shouldEllipsize) { 5412 mLayout = new StaticLayout(mTransformed, 5413 0, mTransformed.length(), 5414 mTextPaint, w, alignment, mSpacingMult, 5415 mSpacingAdd, mIncludePad, mEllipsize, 5416 ellipsisWidth); 5417 } else { 5418 mLayout = new StaticLayout(mTransformed, mTextPaint, 5419 w, alignment, mSpacingMult, mSpacingAdd, 5420 mIncludePad); 5421 } 5422 } 5423 5424 shouldEllipsize = mEllipsize != null; 5425 mHintLayout = null; 5426 5427 if (mHint != null) { 5428 if (shouldEllipsize) hintWidth = w; 5429 5430 if (hintBoring == UNKNOWN_BORING) { 5431 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, 5432 mHintBoring); 5433 if (hintBoring != null) { 5434 mHintBoring = hintBoring; 5435 } 5436 } 5437 5438 if (hintBoring != null) { 5439 if (hintBoring.width <= hintWidth && 5440 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 5441 if (mSavedHintLayout != null) { 5442 mHintLayout = mSavedHintLayout. 5443 replaceOrMake(mHint, mTextPaint, 5444 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5445 hintBoring, mIncludePad); 5446 } else { 5447 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5448 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5449 hintBoring, mIncludePad); 5450 } 5451 5452 mSavedHintLayout = (BoringLayout) mHintLayout; 5453 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 5454 if (mSavedHintLayout != null) { 5455 mHintLayout = mSavedHintLayout. 5456 replaceOrMake(mHint, mTextPaint, 5457 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5458 hintBoring, mIncludePad, mEllipsize, 5459 ellipsisWidth); 5460 } else { 5461 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5462 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5463 hintBoring, mIncludePad, mEllipsize, 5464 ellipsisWidth); 5465 } 5466 } else if (shouldEllipsize) { 5467 mHintLayout = new StaticLayout(mHint, 5468 0, mHint.length(), 5469 mTextPaint, hintWidth, alignment, mSpacingMult, 5470 mSpacingAdd, mIncludePad, mEllipsize, 5471 ellipsisWidth); 5472 } else { 5473 mHintLayout = new StaticLayout(mHint, mTextPaint, 5474 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5475 mIncludePad); 5476 } 5477 } else if (shouldEllipsize) { 5478 mHintLayout = new StaticLayout(mHint, 5479 0, mHint.length(), 5480 mTextPaint, hintWidth, alignment, mSpacingMult, 5481 mSpacingAdd, mIncludePad, mEllipsize, 5482 ellipsisWidth); 5483 } else { 5484 mHintLayout = new StaticLayout(mHint, mTextPaint, 5485 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5486 mIncludePad); 5487 } 5488 } 5489 5490 if (bringIntoView) { 5491 registerForPreDraw(); 5492 } 5493 5494 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 5495 if (!compressText(ellipsisWidth)) { 5496 final int height = mLayoutParams.height; 5497 // If the size of the view does not depend on the size of the text, try to 5498 // start the marquee immediately 5499 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 5500 startMarquee(); 5501 } else { 5502 // Defer the start of the marquee until we know our width (see setFrame()) 5503 mRestartMarquee = true; 5504 } 5505 } 5506 } 5507 5508 // CursorControllers need a non-null mLayout 5509 prepareCursorControllers(); 5510 } 5511 5512 private boolean compressText(float width) { 5513 if (isHardwareAccelerated()) return false; 5514 5515 // Only compress the text if it hasn't been compressed by the previous pass 5516 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 5517 mTextPaint.getTextScaleX() == 1.0f) { 5518 final float textWidth = mLayout.getLineWidth(0); 5519 final float overflow = (textWidth + 1.0f - width) / width; 5520 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 5521 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 5522 post(new Runnable() { 5523 public void run() { 5524 requestLayout(); 5525 } 5526 }); 5527 return true; 5528 } 5529 } 5530 5531 return false; 5532 } 5533 5534 private static int desired(Layout layout) { 5535 int n = layout.getLineCount(); 5536 CharSequence text = layout.getText(); 5537 float max = 0; 5538 5539 // if any line was wrapped, we can't use it. 5540 // but it's ok for the last line not to have a newline 5541 5542 for (int i = 0; i < n - 1; i++) { 5543 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 5544 return -1; 5545 } 5546 5547 for (int i = 0; i < n; i++) { 5548 max = Math.max(max, layout.getLineWidth(i)); 5549 } 5550 5551 return (int) FloatMath.ceil(max); 5552 } 5553 5554 /** 5555 * Set whether the TextView includes extra top and bottom padding to make 5556 * room for accents that go above the normal ascent and descent. 5557 * The default is true. 5558 * 5559 * @attr ref android.R.styleable#TextView_includeFontPadding 5560 */ 5561 public void setIncludeFontPadding(boolean includepad) { 5562 mIncludePad = includepad; 5563 5564 if (mLayout != null) { 5565 nullLayouts(); 5566 requestLayout(); 5567 invalidate(); 5568 } 5569 } 5570 5571 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 5572 5573 @Override 5574 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5575 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5576 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5577 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5578 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5579 5580 int width; 5581 int height; 5582 5583 BoringLayout.Metrics boring = UNKNOWN_BORING; 5584 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 5585 5586 int des = -1; 5587 boolean fromexisting = false; 5588 5589 if (widthMode == MeasureSpec.EXACTLY) { 5590 // Parent has told us how big to be. So be it. 5591 width = widthSize; 5592 } else { 5593 if (mLayout != null && mEllipsize == null) { 5594 des = desired(mLayout); 5595 } 5596 5597 if (des < 0) { 5598 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring); 5599 if (boring != null) { 5600 mBoring = boring; 5601 } 5602 } else { 5603 fromexisting = true; 5604 } 5605 5606 if (boring == null || boring == UNKNOWN_BORING) { 5607 if (des < 0) { 5608 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 5609 } 5610 5611 width = des; 5612 } else { 5613 width = boring.width; 5614 } 5615 5616 final Drawables dr = mDrawables; 5617 if (dr != null) { 5618 width = Math.max(width, dr.mDrawableWidthTop); 5619 width = Math.max(width, dr.mDrawableWidthBottom); 5620 } 5621 5622 if (mHint != null) { 5623 int hintDes = -1; 5624 int hintWidth; 5625 5626 if (mHintLayout != null && mEllipsize == null) { 5627 hintDes = desired(mHintLayout); 5628 } 5629 5630 if (hintDes < 0) { 5631 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 5632 if (hintBoring != null) { 5633 mHintBoring = hintBoring; 5634 } 5635 } 5636 5637 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 5638 if (hintDes < 0) { 5639 hintDes = (int) FloatMath.ceil( 5640 Layout.getDesiredWidth(mHint, mTextPaint)); 5641 } 5642 5643 hintWidth = hintDes; 5644 } else { 5645 hintWidth = hintBoring.width; 5646 } 5647 5648 if (hintWidth > width) { 5649 width = hintWidth; 5650 } 5651 } 5652 5653 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 5654 5655 if (mMaxWidthMode == EMS) { 5656 width = Math.min(width, mMaxWidth * getLineHeight()); 5657 } else { 5658 width = Math.min(width, mMaxWidth); 5659 } 5660 5661 if (mMinWidthMode == EMS) { 5662 width = Math.max(width, mMinWidth * getLineHeight()); 5663 } else { 5664 width = Math.max(width, mMinWidth); 5665 } 5666 5667 // Check against our minimum width 5668 width = Math.max(width, getSuggestedMinimumWidth()); 5669 5670 if (widthMode == MeasureSpec.AT_MOST) { 5671 width = Math.min(widthSize, width); 5672 } 5673 } 5674 5675 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5676 int unpaddedWidth = want; 5677 int hintWant = want; 5678 5679 if (mHorizontallyScrolling) 5680 want = VERY_WIDE; 5681 5682 int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth(); 5683 5684 if (mLayout == null) { 5685 makeNewLayout(want, hintWant, boring, hintBoring, 5686 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5687 } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) || 5688 (mLayout.getEllipsizedWidth() != 5689 width - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 5690 if (mHint == null && mEllipsize == null && 5691 want > mLayout.getWidth() && 5692 (mLayout instanceof BoringLayout || 5693 (fromexisting && des >= 0 && des <= want))) { 5694 mLayout.increaseWidthTo(want); 5695 } else { 5696 makeNewLayout(want, hintWant, boring, hintBoring, 5697 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5698 } 5699 } else { 5700 // Width has not changed. 5701 } 5702 5703 if (heightMode == MeasureSpec.EXACTLY) { 5704 // Parent has told us how big to be. So be it. 5705 height = heightSize; 5706 mDesiredHeightAtMeasure = -1; 5707 } else { 5708 int desired = getDesiredHeight(); 5709 5710 height = desired; 5711 mDesiredHeightAtMeasure = desired; 5712 5713 if (heightMode == MeasureSpec.AT_MOST) { 5714 height = Math.min(desired, heightSize); 5715 } 5716 } 5717 5718 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 5719 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 5720 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 5721 } 5722 5723 /* 5724 * We didn't let makeNewLayout() register to bring the cursor into view, 5725 * so do it here if there is any possibility that it is needed. 5726 */ 5727 if (mMovement != null || 5728 mLayout.getWidth() > unpaddedWidth || 5729 mLayout.getHeight() > unpaddedHeight) { 5730 registerForPreDraw(); 5731 } else { 5732 scrollTo(0, 0); 5733 } 5734 5735 setMeasuredDimension(width, height); 5736 } 5737 5738 private int getDesiredHeight() { 5739 return Math.max( 5740 getDesiredHeight(mLayout, true), 5741 getDesiredHeight(mHintLayout, mEllipsize != null)); 5742 } 5743 5744 private int getDesiredHeight(Layout layout, boolean cap) { 5745 if (layout == null) { 5746 return 0; 5747 } 5748 5749 int linecount = layout.getLineCount(); 5750 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 5751 int desired = layout.getLineTop(linecount); 5752 5753 final Drawables dr = mDrawables; 5754 if (dr != null) { 5755 desired = Math.max(desired, dr.mDrawableHeightLeft); 5756 desired = Math.max(desired, dr.mDrawableHeightRight); 5757 } 5758 5759 desired += pad; 5760 5761 if (mMaxMode == LINES) { 5762 /* 5763 * Don't cap the hint to a certain number of lines. 5764 * (Do cap it, though, if we have a maximum pixel height.) 5765 */ 5766 if (cap) { 5767 if (linecount > mMaximum) { 5768 desired = layout.getLineTop(mMaximum) + 5769 layout.getBottomPadding(); 5770 5771 if (dr != null) { 5772 desired = Math.max(desired, dr.mDrawableHeightLeft); 5773 desired = Math.max(desired, dr.mDrawableHeightRight); 5774 } 5775 5776 desired += pad; 5777 linecount = mMaximum; 5778 } 5779 } 5780 } else { 5781 desired = Math.min(desired, mMaximum); 5782 } 5783 5784 if (mMinMode == LINES) { 5785 if (linecount < mMinimum) { 5786 desired += getLineHeight() * (mMinimum - linecount); 5787 } 5788 } else { 5789 desired = Math.max(desired, mMinimum); 5790 } 5791 5792 // Check against our minimum height 5793 desired = Math.max(desired, getSuggestedMinimumHeight()); 5794 5795 return desired; 5796 } 5797 5798 /** 5799 * Check whether a change to the existing text layout requires a 5800 * new view layout. 5801 */ 5802 private void checkForResize() { 5803 boolean sizeChanged = false; 5804 5805 if (mLayout != null) { 5806 // Check if our width changed 5807 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 5808 sizeChanged = true; 5809 invalidate(); 5810 } 5811 5812 // Check if our height changed 5813 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 5814 int desiredHeight = getDesiredHeight(); 5815 5816 if (desiredHeight != this.getHeight()) { 5817 sizeChanged = true; 5818 } 5819 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 5820 if (mDesiredHeightAtMeasure >= 0) { 5821 int desiredHeight = getDesiredHeight(); 5822 5823 if (desiredHeight != mDesiredHeightAtMeasure) { 5824 sizeChanged = true; 5825 } 5826 } 5827 } 5828 } 5829 5830 if (sizeChanged) { 5831 requestLayout(); 5832 // caller will have already invalidated 5833 } 5834 } 5835 5836 /** 5837 * Check whether entirely new text requires a new view layout 5838 * or merely a new text layout. 5839 */ 5840 private void checkForRelayout() { 5841 // If we have a fixed width, we can just swap in a new text layout 5842 // if the text height stays the same or if the view height is fixed. 5843 5844 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 5845 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 5846 (mHint == null || mHintLayout != null) && 5847 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 5848 // Static width, so try making a new text layout. 5849 5850 int oldht = mLayout.getHeight(); 5851 int want = mLayout.getWidth(); 5852 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 5853 5854 /* 5855 * No need to bring the text into view, since the size is not 5856 * changing (unless we do the requestLayout(), in which case it 5857 * will happen at measure). 5858 */ 5859 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 5860 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 5861 false); 5862 5863 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 5864 // In a fixed-height view, so use our new text layout. 5865 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 5866 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 5867 invalidate(); 5868 return; 5869 } 5870 5871 // Dynamic height, but height has stayed the same, 5872 // so use our new text layout. 5873 if (mLayout.getHeight() == oldht && 5874 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 5875 invalidate(); 5876 return; 5877 } 5878 } 5879 5880 // We lose: the height has changed and we have a dynamic height. 5881 // Request a new view layout using our new text layout. 5882 requestLayout(); 5883 invalidate(); 5884 } else { 5885 // Dynamic width, so we have no choice but to request a new 5886 // view layout with a new text layout. 5887 5888 nullLayouts(); 5889 requestLayout(); 5890 invalidate(); 5891 } 5892 } 5893 5894 /** 5895 * Returns true if anything changed. 5896 */ 5897 private boolean bringTextIntoView() { 5898 int line = 0; 5899 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 5900 line = mLayout.getLineCount() - 1; 5901 } 5902 5903 Layout.Alignment a = mLayout.getParagraphAlignment(line); 5904 int dir = mLayout.getParagraphDirection(line); 5905 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5906 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 5907 int ht = mLayout.getHeight(); 5908 5909 int scrollx, scrolly; 5910 5911 if (a == Layout.Alignment.ALIGN_CENTER) { 5912 /* 5913 * Keep centered if possible, or, if it is too wide to fit, 5914 * keep leading edge in view. 5915 */ 5916 5917 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5918 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5919 5920 if (right - left < hspace) { 5921 scrollx = (right + left) / 2 - hspace / 2; 5922 } else { 5923 if (dir < 0) { 5924 scrollx = right - hspace; 5925 } else { 5926 scrollx = left; 5927 } 5928 } 5929 } else if (a == Layout.Alignment.ALIGN_NORMAL) { 5930 /* 5931 * Keep leading edge in view. 5932 */ 5933 5934 if (dir < 0) { 5935 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5936 scrollx = right - hspace; 5937 } else { 5938 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5939 } 5940 } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ { 5941 /* 5942 * Keep trailing edge in view. 5943 */ 5944 5945 if (dir < 0) { 5946 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5947 } else { 5948 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5949 scrollx = right - hspace; 5950 } 5951 } 5952 5953 if (ht < vspace) { 5954 scrolly = 0; 5955 } else { 5956 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 5957 scrolly = ht - vspace; 5958 } else { 5959 scrolly = 0; 5960 } 5961 } 5962 5963 if (scrollx != mScrollX || scrolly != mScrollY) { 5964 scrollTo(scrollx, scrolly); 5965 return true; 5966 } else { 5967 return false; 5968 } 5969 } 5970 5971 /** 5972 * Move the point, specified by the offset, into the view if it is needed. 5973 * This has to be called after layout. Returns true if anything changed. 5974 */ 5975 public boolean bringPointIntoView(int offset) { 5976 boolean changed = false; 5977 5978 int line = mLayout.getLineForOffset(offset); 5979 5980 // FIXME: Is it okay to truncate this, or should we round? 5981 final int x = (int)mLayout.getPrimaryHorizontal(offset); 5982 final int top = mLayout.getLineTop(line); 5983 final int bottom = mLayout.getLineTop(line + 1); 5984 5985 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5986 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5987 int ht = mLayout.getHeight(); 5988 5989 int grav; 5990 5991 switch (mLayout.getParagraphAlignment(line)) { 5992 case ALIGN_NORMAL: 5993 grav = 1; 5994 break; 5995 5996 case ALIGN_OPPOSITE: 5997 grav = -1; 5998 break; 5999 6000 default: 6001 grav = 0; 6002 } 6003 6004 grav *= mLayout.getParagraphDirection(line); 6005 6006 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6007 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6008 6009 int hslack = (bottom - top) / 2; 6010 int vslack = hslack; 6011 6012 if (vslack > vspace / 4) 6013 vslack = vspace / 4; 6014 if (hslack > hspace / 4) 6015 hslack = hspace / 4; 6016 6017 int hs = mScrollX; 6018 int vs = mScrollY; 6019 6020 if (top - vs < vslack) 6021 vs = top - vslack; 6022 if (bottom - vs > vspace - vslack) 6023 vs = bottom - (vspace - vslack); 6024 if (ht - vs < vspace) 6025 vs = ht - vspace; 6026 if (0 - vs > 0) 6027 vs = 0; 6028 6029 if (grav != 0) { 6030 if (x - hs < hslack) { 6031 hs = x - hslack; 6032 } 6033 if (x - hs > hspace - hslack) { 6034 hs = x - (hspace - hslack); 6035 } 6036 } 6037 6038 if (grav < 0) { 6039 if (left - hs > 0) 6040 hs = left; 6041 if (right - hs < hspace) 6042 hs = right - hspace; 6043 } else if (grav > 0) { 6044 if (right - hs < hspace) 6045 hs = right - hspace; 6046 if (left - hs > 0) 6047 hs = left; 6048 } else /* grav == 0 */ { 6049 if (right - left <= hspace) { 6050 /* 6051 * If the entire text fits, center it exactly. 6052 */ 6053 hs = left - (hspace - (right - left)) / 2; 6054 } else if (x > right - hslack) { 6055 /* 6056 * If we are near the right edge, keep the right edge 6057 * at the edge of the view. 6058 */ 6059 hs = right - hspace; 6060 } else if (x < left + hslack) { 6061 /* 6062 * If we are near the left edge, keep the left edge 6063 * at the edge of the view. 6064 */ 6065 hs = left; 6066 } else if (left > hs) { 6067 /* 6068 * Is there whitespace visible at the left? Fix it if so. 6069 */ 6070 hs = left; 6071 } else if (right < hs + hspace) { 6072 /* 6073 * Is there whitespace visible at the right? Fix it if so. 6074 */ 6075 hs = right - hspace; 6076 } else { 6077 /* 6078 * Otherwise, float as needed. 6079 */ 6080 if (x - hs < hslack) { 6081 hs = x - hslack; 6082 } 6083 if (x - hs > hspace - hslack) { 6084 hs = x - (hspace - hslack); 6085 } 6086 } 6087 } 6088 6089 if (hs != mScrollX || vs != mScrollY) { 6090 if (mScroller == null) { 6091 scrollTo(hs, vs); 6092 } else { 6093 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6094 int dx = hs - mScrollX; 6095 int dy = vs - mScrollY; 6096 6097 if (duration > ANIMATED_SCROLL_GAP) { 6098 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6099 awakenScrollBars(mScroller.getDuration()); 6100 invalidate(); 6101 } else { 6102 if (!mScroller.isFinished()) { 6103 mScroller.abortAnimation(); 6104 } 6105 6106 scrollBy(dx, dy); 6107 } 6108 6109 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6110 } 6111 6112 changed = true; 6113 } 6114 6115 if (isFocused()) { 6116 // This offsets because getInterestingRect() is in terms of 6117 // viewport coordinates, but requestRectangleOnScreen() 6118 // is in terms of content coordinates. 6119 6120 Rect r = new Rect(x, top, x + 1, bottom); 6121 getInterestingRect(r, line); 6122 r.offset(mScrollX, mScrollY); 6123 6124 if (requestRectangleOnScreen(r)) { 6125 changed = true; 6126 } 6127 } 6128 6129 return changed; 6130 } 6131 6132 /** 6133 * Move the cursor, if needed, so that it is at an offset that is visible 6134 * to the user. This will not move the cursor if it represents more than 6135 * one character (a selection range). This will only work if the 6136 * TextView contains spannable text; otherwise it will do nothing. 6137 * 6138 * @return True if the cursor was actually moved, false otherwise. 6139 */ 6140 public boolean moveCursorToVisibleOffset() { 6141 if (!(mText instanceof Spannable)) { 6142 return false; 6143 } 6144 int start = getSelectionStart(); 6145 int end = getSelectionEnd(); 6146 if (start != end) { 6147 return false; 6148 } 6149 6150 // First: make sure the line is visible on screen: 6151 6152 int line = mLayout.getLineForOffset(start); 6153 6154 final int top = mLayout.getLineTop(line); 6155 final int bottom = mLayout.getLineTop(line + 1); 6156 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6157 int vslack = (bottom - top) / 2; 6158 if (vslack > vspace / 4) 6159 vslack = vspace / 4; 6160 final int vs = mScrollY; 6161 6162 if (top < (vs+vslack)) { 6163 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 6164 } else if (bottom > (vspace+vs-vslack)) { 6165 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 6166 } 6167 6168 // Next: make sure the character is visible on screen: 6169 6170 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6171 final int hs = mScrollX; 6172 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 6173 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 6174 6175 // line might contain bidirectional text 6176 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 6177 final int highChar = leftChar > rightChar ? leftChar : rightChar; 6178 6179 int newStart = start; 6180 if (newStart < lowChar) { 6181 newStart = lowChar; 6182 } else if (newStart > highChar) { 6183 newStart = highChar; 6184 } 6185 6186 if (newStart != start) { 6187 Selection.setSelection((Spannable)mText, newStart); 6188 return true; 6189 } 6190 6191 return false; 6192 } 6193 6194 @Override 6195 public void computeScroll() { 6196 if (mScroller != null) { 6197 if (mScroller.computeScrollOffset()) { 6198 mScrollX = mScroller.getCurrX(); 6199 mScrollY = mScroller.getCurrY(); 6200 postInvalidate(); // So we draw again 6201 } 6202 } 6203 } 6204 6205 private void getInterestingRect(Rect r, int line) { 6206 convertFromViewportToContentCoordinates(r); 6207 6208 // Rectangle can can be expanded on first and last line to take 6209 // padding into account. 6210 // TODO Take left/right padding into account too? 6211 if (line == 0) r.top -= getExtendedPaddingTop(); 6212 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 6213 } 6214 6215 private void convertFromViewportToContentCoordinates(Rect r) { 6216 final int horizontalOffset = viewportToContentHorizontalOffset(); 6217 r.left += horizontalOffset; 6218 r.right += horizontalOffset; 6219 6220 final int verticalOffset = viewportToContentVerticalOffset(); 6221 r.top += verticalOffset; 6222 r.bottom += verticalOffset; 6223 } 6224 6225 private int viewportToContentHorizontalOffset() { 6226 return getCompoundPaddingLeft() - mScrollX; 6227 } 6228 6229 private int viewportToContentVerticalOffset() { 6230 int offset = getExtendedPaddingTop() - mScrollY; 6231 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 6232 offset += getVerticalOffset(false); 6233 } 6234 return offset; 6235 } 6236 6237 @Override 6238 public void debug(int depth) { 6239 super.debug(depth); 6240 6241 String output = debugIndent(depth); 6242 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 6243 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 6244 + "} "; 6245 6246 if (mText != null) { 6247 6248 output += "mText=\"" + mText + "\" "; 6249 if (mLayout != null) { 6250 output += "mLayout width=" + mLayout.getWidth() 6251 + " height=" + mLayout.getHeight(); 6252 } 6253 } else { 6254 output += "mText=NULL"; 6255 } 6256 Log.d(VIEW_LOG_TAG, output); 6257 } 6258 6259 /** 6260 * Convenience for {@link Selection#getSelectionStart}. 6261 */ 6262 @ViewDebug.ExportedProperty(category = "text") 6263 public int getSelectionStart() { 6264 return Selection.getSelectionStart(getText()); 6265 } 6266 6267 /** 6268 * Convenience for {@link Selection#getSelectionEnd}. 6269 */ 6270 @ViewDebug.ExportedProperty(category = "text") 6271 public int getSelectionEnd() { 6272 return Selection.getSelectionEnd(getText()); 6273 } 6274 6275 /** 6276 * Return true iff there is a selection inside this text view. 6277 */ 6278 public boolean hasSelection() { 6279 final int selectionStart = getSelectionStart(); 6280 final int selectionEnd = getSelectionEnd(); 6281 6282 return selectionStart >= 0 && selectionStart != selectionEnd; 6283 } 6284 6285 /** 6286 * Sets the properties of this field (lines, horizontally scrolling, 6287 * transformation method) to be for a single-line input. 6288 * 6289 * @attr ref android.R.styleable#TextView_singleLine 6290 */ 6291 public void setSingleLine() { 6292 setSingleLine(true); 6293 } 6294 6295 /** 6296 * If true, sets the properties of this field (lines, horizontally 6297 * scrolling, transformation method) to be for a single-line input; 6298 * if false, restores these to the default conditions. 6299 * Note that calling this with false restores default conditions, 6300 * not necessarily those that were in effect prior to calling 6301 * it with true. 6302 * 6303 * @attr ref android.R.styleable#TextView_singleLine 6304 */ 6305 @android.view.RemotableViewMethod 6306 public void setSingleLine(boolean singleLine) { 6307 setInputTypeSingleLine(singleLine); 6308 applySingleLine(singleLine, true); 6309 } 6310 6311 /** 6312 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 6313 * @param singleLine 6314 */ 6315 private void setInputTypeSingleLine(boolean singleLine) { 6316 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 6317 if (singleLine) { 6318 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 6319 } else { 6320 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 6321 } 6322 } 6323 } 6324 6325 private void applySingleLine(boolean singleLine, boolean applyTransformation) { 6326 mSingleLine = singleLine; 6327 if (singleLine) { 6328 setLines(1); 6329 setHorizontallyScrolling(true); 6330 if (applyTransformation) { 6331 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 6332 } 6333 setBackgroundDrawable(mEditTextSingleLineBackground); 6334 } else { 6335 setMaxLines(Integer.MAX_VALUE); 6336 setHorizontallyScrolling(false); 6337 if (applyTransformation) { 6338 setTransformationMethod(null); 6339 } 6340 // mEditTextMultilineBackground is defined and used only in EditText 6341 if (mEditTextMultilineBackground != null) { 6342 setBackgroundDrawable(mEditTextMultilineBackground); 6343 } 6344 } 6345 } 6346 6347 /** 6348 * Causes words in the text that are longer than the view is wide 6349 * to be ellipsized instead of broken in the middle. You may also 6350 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 6351 * to constrain the text to a single line. Use <code>null</code> 6352 * to turn off ellipsizing. 6353 * 6354 * @attr ref android.R.styleable#TextView_ellipsize 6355 */ 6356 public void setEllipsize(TextUtils.TruncateAt where) { 6357 mEllipsize = where; 6358 6359 if (mLayout != null) { 6360 nullLayouts(); 6361 requestLayout(); 6362 invalidate(); 6363 } 6364 } 6365 6366 /** 6367 * Sets how many times to repeat the marquee animation. Only applied if the 6368 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 6369 * 6370 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 6371 */ 6372 public void setMarqueeRepeatLimit(int marqueeLimit) { 6373 mMarqueeRepeatLimit = marqueeLimit; 6374 } 6375 6376 /** 6377 * Returns where, if anywhere, words that are longer than the view 6378 * is wide should be ellipsized. 6379 */ 6380 @ViewDebug.ExportedProperty 6381 public TextUtils.TruncateAt getEllipsize() { 6382 return mEllipsize; 6383 } 6384 6385 /** 6386 * Set the TextView so that when it takes focus, all the text is 6387 * selected. 6388 * 6389 * @attr ref android.R.styleable#TextView_selectAllOnFocus 6390 */ 6391 @android.view.RemotableViewMethod 6392 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 6393 mSelectAllOnFocus = selectAllOnFocus; 6394 6395 if (selectAllOnFocus && !(mText instanceof Spannable)) { 6396 setText(mText, BufferType.SPANNABLE); 6397 } 6398 } 6399 6400 /** 6401 * Set whether the cursor is visible. The default is true. 6402 * 6403 * @attr ref android.R.styleable#TextView_cursorVisible 6404 */ 6405 @android.view.RemotableViewMethod 6406 public void setCursorVisible(boolean visible) { 6407 mCursorVisible = visible; 6408 invalidate(); 6409 6410 makeBlink(); 6411 6412 // InsertionPointCursorController depends on mCursorVisible 6413 prepareCursorControllers(); 6414 } 6415 6416 private boolean canMarquee() { 6417 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 6418 return width > 0 && mLayout.getLineWidth(0) > width; 6419 } 6420 6421 private void startMarquee() { 6422 // Do not ellipsize EditText 6423 if (mInput != null) return; 6424 6425 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 6426 return; 6427 } 6428 6429 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 6430 getLineCount() == 1 && canMarquee()) { 6431 6432 if (mMarquee == null) mMarquee = new Marquee(this); 6433 mMarquee.start(mMarqueeRepeatLimit); 6434 } 6435 } 6436 6437 private void stopMarquee() { 6438 if (mMarquee != null && !mMarquee.isStopped()) { 6439 mMarquee.stop(); 6440 } 6441 } 6442 6443 private void startStopMarquee(boolean start) { 6444 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6445 if (start) { 6446 startMarquee(); 6447 } else { 6448 stopMarquee(); 6449 } 6450 } 6451 } 6452 6453 private static final class Marquee extends Handler { 6454 // TODO: Add an option to configure this 6455 private static final float MARQUEE_DELTA_MAX = 0.07f; 6456 private static final int MARQUEE_DELAY = 1200; 6457 private static final int MARQUEE_RESTART_DELAY = 1200; 6458 private static final int MARQUEE_RESOLUTION = 1000 / 30; 6459 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 6460 6461 private static final byte MARQUEE_STOPPED = 0x0; 6462 private static final byte MARQUEE_STARTING = 0x1; 6463 private static final byte MARQUEE_RUNNING = 0x2; 6464 6465 private static final int MESSAGE_START = 0x1; 6466 private static final int MESSAGE_TICK = 0x2; 6467 private static final int MESSAGE_RESTART = 0x3; 6468 6469 private final WeakReference<TextView> mView; 6470 6471 private byte mStatus = MARQUEE_STOPPED; 6472 private final float mScrollUnit; 6473 private float mMaxScroll; 6474 float mMaxFadeScroll; 6475 private float mGhostStart; 6476 private float mGhostOffset; 6477 private float mFadeStop; 6478 private int mRepeatLimit; 6479 6480 float mScroll; 6481 6482 Marquee(TextView v) { 6483 final float density = v.getContext().getResources().getDisplayMetrics().density; 6484 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 6485 mView = new WeakReference<TextView>(v); 6486 } 6487 6488 @Override 6489 public void handleMessage(Message msg) { 6490 switch (msg.what) { 6491 case MESSAGE_START: 6492 mStatus = MARQUEE_RUNNING; 6493 tick(); 6494 break; 6495 case MESSAGE_TICK: 6496 tick(); 6497 break; 6498 case MESSAGE_RESTART: 6499 if (mStatus == MARQUEE_RUNNING) { 6500 if (mRepeatLimit >= 0) { 6501 mRepeatLimit--; 6502 } 6503 start(mRepeatLimit); 6504 } 6505 break; 6506 } 6507 } 6508 6509 void tick() { 6510 if (mStatus != MARQUEE_RUNNING) { 6511 return; 6512 } 6513 6514 removeMessages(MESSAGE_TICK); 6515 6516 final TextView textView = mView.get(); 6517 if (textView != null && (textView.isFocused() || textView.isSelected())) { 6518 mScroll += mScrollUnit; 6519 if (mScroll > mMaxScroll) { 6520 mScroll = mMaxScroll; 6521 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 6522 } else { 6523 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 6524 } 6525 textView.invalidate(); 6526 } 6527 } 6528 6529 void stop() { 6530 mStatus = MARQUEE_STOPPED; 6531 removeMessages(MESSAGE_START); 6532 removeMessages(MESSAGE_RESTART); 6533 removeMessages(MESSAGE_TICK); 6534 resetScroll(); 6535 } 6536 6537 private void resetScroll() { 6538 mScroll = 0.0f; 6539 final TextView textView = mView.get(); 6540 if (textView != null) textView.invalidate(); 6541 } 6542 6543 void start(int repeatLimit) { 6544 if (repeatLimit == 0) { 6545 stop(); 6546 return; 6547 } 6548 mRepeatLimit = repeatLimit; 6549 final TextView textView = mView.get(); 6550 if (textView != null && textView.mLayout != null) { 6551 mStatus = MARQUEE_STARTING; 6552 mScroll = 0.0f; 6553 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 6554 textView.getCompoundPaddingRight(); 6555 final float lineWidth = textView.mLayout.getLineWidth(0); 6556 final float gap = textWidth / 3.0f; 6557 mGhostStart = lineWidth - textWidth + gap; 6558 mMaxScroll = mGhostStart + textWidth; 6559 mGhostOffset = lineWidth + gap; 6560 mFadeStop = lineWidth + textWidth / 6.0f; 6561 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 6562 6563 textView.invalidate(); 6564 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 6565 } 6566 } 6567 6568 float getGhostOffset() { 6569 return mGhostOffset; 6570 } 6571 6572 boolean shouldDrawLeftFade() { 6573 return mScroll <= mFadeStop; 6574 } 6575 6576 boolean shouldDrawGhost() { 6577 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 6578 } 6579 6580 boolean isRunning() { 6581 return mStatus == MARQUEE_RUNNING; 6582 } 6583 6584 boolean isStopped() { 6585 return mStatus == MARQUEE_STOPPED; 6586 } 6587 } 6588 6589 /** 6590 * This method is called when the text is changed, in case any 6591 * subclasses would like to know. 6592 * 6593 * @param text The text the TextView is displaying. 6594 * @param start The offset of the start of the range of the text 6595 * that was modified. 6596 * @param before The offset of the former end of the range of the 6597 * text that was modified. If text was simply inserted, 6598 * this will be the same as <code>start</code>. 6599 * If text was replaced with new text or deleted, the 6600 * length of the old text was <code>before-start</code>. 6601 * @param after The offset of the end of the range of the text 6602 * that was modified. If text was simply deleted, 6603 * this will be the same as <code>start</code>. 6604 * If text was replaced with new text or inserted, 6605 * the length of the new text is <code>after-start</code>. 6606 */ 6607 protected void onTextChanged(CharSequence text, 6608 int start, int before, int after) { 6609 } 6610 6611 /** 6612 * This method is called when the selection has changed, in case any 6613 * subclasses would like to know. 6614 * 6615 * @param selStart The new selection start location. 6616 * @param selEnd The new selection end location. 6617 */ 6618 protected void onSelectionChanged(int selStart, int selEnd) { 6619 } 6620 6621 /** 6622 * Adds a TextWatcher to the list of those whose methods are called 6623 * whenever this TextView's text changes. 6624 * <p> 6625 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 6626 * not called after {@link #setText} calls. Now, doing {@link #setText} 6627 * if there are any text changed listeners forces the buffer type to 6628 * Editable if it would not otherwise be and does call this method. 6629 */ 6630 public void addTextChangedListener(TextWatcher watcher) { 6631 if (mListeners == null) { 6632 mListeners = new ArrayList<TextWatcher>(); 6633 } 6634 6635 mListeners.add(watcher); 6636 } 6637 6638 /** 6639 * Removes the specified TextWatcher from the list of those whose 6640 * methods are called 6641 * whenever this TextView's text changes. 6642 */ 6643 public void removeTextChangedListener(TextWatcher watcher) { 6644 if (mListeners != null) { 6645 int i = mListeners.indexOf(watcher); 6646 6647 if (i >= 0) { 6648 mListeners.remove(i); 6649 } 6650 } 6651 } 6652 6653 private void sendBeforeTextChanged(CharSequence text, int start, int before, 6654 int after) { 6655 if (mListeners != null) { 6656 final ArrayList<TextWatcher> list = mListeners; 6657 final int count = list.size(); 6658 for (int i = 0; i < count; i++) { 6659 list.get(i).beforeTextChanged(text, start, before, after); 6660 } 6661 } 6662 } 6663 6664 /** 6665 * Not private so it can be called from an inner class without going 6666 * through a thunk. 6667 */ 6668 void sendOnTextChanged(CharSequence text, int start, int before, 6669 int after) { 6670 if (mListeners != null) { 6671 final ArrayList<TextWatcher> list = mListeners; 6672 final int count = list.size(); 6673 for (int i = 0; i < count; i++) { 6674 list.get(i).onTextChanged(text, start, before, after); 6675 } 6676 } 6677 } 6678 6679 /** 6680 * Not private so it can be called from an inner class without going 6681 * through a thunk. 6682 */ 6683 void sendAfterTextChanged(Editable text) { 6684 if (mListeners != null) { 6685 final ArrayList<TextWatcher> list = mListeners; 6686 final int count = list.size(); 6687 for (int i = 0; i < count; i++) { 6688 list.get(i).afterTextChanged(text); 6689 } 6690 } 6691 } 6692 6693 /** 6694 * Not private so it can be called from an inner class without going 6695 * through a thunk. 6696 */ 6697 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 6698 final InputMethodState ims = mInputMethodState; 6699 if (ims == null || ims.mBatchEditNesting == 0) { 6700 updateAfterEdit(); 6701 } 6702 if (ims != null) { 6703 ims.mContentChanged = true; 6704 if (ims.mChangedStart < 0) { 6705 ims.mChangedStart = start; 6706 ims.mChangedEnd = start+before; 6707 } else { 6708 ims.mChangedStart = Math.min(ims.mChangedStart, start); 6709 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 6710 } 6711 ims.mChangedDelta += after-before; 6712 } 6713 6714 sendOnTextChanged(buffer, start, before, after); 6715 onTextChanged(buffer, start, before, after); 6716 6717 // Hide the controller if the amount of content changed 6718 if (before != after) { 6719 hideControllers(); 6720 } 6721 } 6722 6723 /** 6724 * Not private so it can be called from an inner class without going 6725 * through a thunk. 6726 */ 6727 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 6728 // XXX Make the start and end move together if this ends up 6729 // spending too much time invalidating. 6730 6731 boolean selChanged = false; 6732 int newSelStart=-1, newSelEnd=-1; 6733 6734 final InputMethodState ims = mInputMethodState; 6735 6736 if (what == Selection.SELECTION_END) { 6737 mHighlightPathBogus = true; 6738 selChanged = true; 6739 newSelEnd = newStart; 6740 6741 if (!isFocused()) { 6742 mSelectionMoved = true; 6743 } 6744 6745 if (oldStart >= 0 || newStart >= 0) { 6746 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 6747 registerForPreDraw(); 6748 6749 if (isFocused()) { 6750 mShowCursor = SystemClock.uptimeMillis(); 6751 makeBlink(); 6752 } 6753 } 6754 } 6755 6756 if (what == Selection.SELECTION_START) { 6757 mHighlightPathBogus = true; 6758 selChanged = true; 6759 newSelStart = newStart; 6760 6761 if (!isFocused()) { 6762 mSelectionMoved = true; 6763 } 6764 6765 if (oldStart >= 0 || newStart >= 0) { 6766 int end = Selection.getSelectionEnd(buf); 6767 invalidateCursor(end, oldStart, newStart); 6768 } 6769 } 6770 6771 if (selChanged) { 6772 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 6773 if (newSelStart < 0) { 6774 newSelStart = Selection.getSelectionStart(buf); 6775 } 6776 if (newSelEnd < 0) { 6777 newSelEnd = Selection.getSelectionEnd(buf); 6778 } 6779 onSelectionChanged(newSelStart, newSelEnd); 6780 } 6781 } 6782 6783 if (what instanceof UpdateAppearance || 6784 what instanceof ParagraphStyle) { 6785 if (ims == null || ims.mBatchEditNesting == 0) { 6786 invalidate(); 6787 mHighlightPathBogus = true; 6788 checkForResize(); 6789 } else { 6790 ims.mContentChanged = true; 6791 } 6792 } 6793 6794 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 6795 mHighlightPathBogus = true; 6796 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 6797 ims.mSelectionModeChanged = true; 6798 } 6799 6800 if (Selection.getSelectionStart(buf) >= 0) { 6801 if (ims == null || ims.mBatchEditNesting == 0) { 6802 invalidateCursor(); 6803 } else { 6804 ims.mCursorChanged = true; 6805 } 6806 } 6807 } 6808 6809 if (what instanceof ParcelableSpan) { 6810 // If this is a span that can be sent to a remote process, 6811 // the current extract editor would be interested in it. 6812 if (ims != null && ims.mExtracting != null) { 6813 if (ims.mBatchEditNesting != 0) { 6814 if (oldStart >= 0) { 6815 if (ims.mChangedStart > oldStart) { 6816 ims.mChangedStart = oldStart; 6817 } 6818 if (ims.mChangedStart > oldEnd) { 6819 ims.mChangedStart = oldEnd; 6820 } 6821 } 6822 if (newStart >= 0) { 6823 if (ims.mChangedStart > newStart) { 6824 ims.mChangedStart = newStart; 6825 } 6826 if (ims.mChangedStart > newEnd) { 6827 ims.mChangedStart = newEnd; 6828 } 6829 } 6830 } else { 6831 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 6832 + oldStart + "-" + oldEnd + "," 6833 + newStart + "-" + newEnd + what); 6834 ims.mContentChanged = true; 6835 } 6836 } 6837 } 6838 } 6839 6840 private class ChangeWatcher 6841 implements TextWatcher, SpanWatcher { 6842 6843 private CharSequence mBeforeText; 6844 6845 public void beforeTextChanged(CharSequence buffer, int start, 6846 int before, int after) { 6847 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 6848 + " before=" + before + " after=" + after + ": " + buffer); 6849 6850 if (AccessibilityManager.getInstance(mContext).isEnabled() 6851 && !isPasswordInputType(mInputType) 6852 && !hasPasswordTransformationMethod()) { 6853 mBeforeText = buffer.toString(); 6854 } 6855 6856 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 6857 } 6858 6859 public void onTextChanged(CharSequence buffer, int start, 6860 int before, int after) { 6861 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 6862 + " before=" + before + " after=" + after + ": " + buffer); 6863 TextView.this.handleTextChanged(buffer, start, before, after); 6864 6865 if (AccessibilityManager.getInstance(mContext).isEnabled() && 6866 (isFocused() || isSelected() && 6867 isShown())) { 6868 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 6869 mBeforeText = null; 6870 } 6871 } 6872 6873 public void afterTextChanged(Editable buffer) { 6874 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 6875 TextView.this.sendAfterTextChanged(buffer); 6876 6877 if (MetaKeyKeyListener.getMetaState(buffer, 6878 MetaKeyKeyListener.META_SELECTING) != 0) { 6879 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 6880 } 6881 } 6882 6883 public void onSpanChanged(Spannable buf, 6884 Object what, int s, int e, int st, int en) { 6885 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 6886 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 6887 TextView.this.spanChange(buf, what, s, st, e, en); 6888 } 6889 6890 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 6891 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 6892 + " what=" + what + ": " + buf); 6893 TextView.this.spanChange(buf, what, -1, s, -1, e); 6894 } 6895 6896 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 6897 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 6898 + " what=" + what + ": " + buf); 6899 TextView.this.spanChange(buf, what, s, -1, e, -1); 6900 } 6901 } 6902 6903 private void makeBlink() { 6904 if (!mCursorVisible || !isTextEditable()) { 6905 if (mBlink != null) { 6906 mBlink.removeCallbacks(mBlink); 6907 } 6908 6909 return; 6910 } 6911 6912 if (mBlink == null) 6913 mBlink = new Blink(this); 6914 6915 mBlink.removeCallbacks(mBlink); 6916 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 6917 } 6918 6919 /** 6920 * @hide 6921 */ 6922 @Override 6923 public void dispatchFinishTemporaryDetach() { 6924 mDispatchTemporaryDetach = true; 6925 super.dispatchFinishTemporaryDetach(); 6926 mDispatchTemporaryDetach = false; 6927 } 6928 6929 @Override 6930 public void onStartTemporaryDetach() { 6931 super.onStartTemporaryDetach(); 6932 // Only track when onStartTemporaryDetach() is called directly, 6933 // usually because this instance is an editable field in a list 6934 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 6935 } 6936 6937 @Override 6938 public void onFinishTemporaryDetach() { 6939 super.onFinishTemporaryDetach(); 6940 // Only track when onStartTemporaryDetach() is called directly, 6941 // usually because this instance is an editable field in a list 6942 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 6943 } 6944 6945 @Override 6946 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 6947 if (mTemporaryDetach) { 6948 // If we are temporarily in the detach state, then do nothing. 6949 super.onFocusChanged(focused, direction, previouslyFocusedRect); 6950 return; 6951 } 6952 6953 mShowCursor = SystemClock.uptimeMillis(); 6954 6955 ensureEndedBatchEdit(); 6956 6957 if (focused) { 6958 int selStart = getSelectionStart(); 6959 int selEnd = getSelectionEnd(); 6960 6961 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 6962 // If a tap was used to give focus to that view, move cursor at tap position. 6963 // Has to be done before onTakeFocus, which can be overloaded. 6964 final int lastTapPosition = getLastTapPosition(); 6965 if (lastTapPosition >= 0) { 6966 Selection.setSelection((Spannable) mText, lastTapPosition); 6967 } 6968 6969 if (mMovement != null) { 6970 mMovement.onTakeFocus(this, (Spannable) mText, direction); 6971 } 6972 6973 // The DecorView does not have focus when the 'Done' ExtractEditText button is 6974 // pressed. Since it is the ViewRoot's mView, it requests focus before 6975 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 6976 // This special case ensure that we keep current selection in that case. 6977 // It would be better to know why the DecorView does not have focus at that time. 6978 if (((this instanceof ExtractEditText) || mSelectionMoved) && 6979 selStart >= 0 && selEnd >= 0) { 6980 /* 6981 * Someone intentionally set the selection, so let them 6982 * do whatever it is that they wanted to do instead of 6983 * the default on-focus behavior. We reset the selection 6984 * here instead of just skipping the onTakeFocus() call 6985 * because some movement methods do something other than 6986 * just setting the selection in theirs and we still 6987 * need to go through that path. 6988 */ 6989 Selection.setSelection((Spannable) mText, selStart, selEnd); 6990 } 6991 6992 if (mSelectAllOnFocus) { 6993 selectAll(); 6994 } 6995 6996 mTouchFocusSelected = true; 6997 } 6998 6999 mFrozenWithFocus = false; 7000 mSelectionMoved = false; 7001 7002 if (mText instanceof Spannable) { 7003 Spannable sp = (Spannable) mText; 7004 MetaKeyKeyListener.resetMetaState(sp); 7005 } 7006 7007 makeBlink(); 7008 7009 if (mError != null) { 7010 showError(); 7011 } 7012 } else { 7013 if (mError != null) { 7014 hideError(); 7015 } 7016 // Don't leave us in the middle of a batch edit. 7017 onEndBatchEdit(); 7018 7019 hideInsertionPointCursorController(); 7020 if (this instanceof ExtractEditText) { 7021 // terminateTextSelectionMode removes selection, which we want to keep when 7022 // ExtractEditText goes out of focus. 7023 final int selStart = getSelectionStart(); 7024 final int selEnd = getSelectionEnd(); 7025 terminateSelectionActionMode(); 7026 Selection.setSelection((Spannable) mText, selStart, selEnd); 7027 } else { 7028 terminateSelectionActionMode(); 7029 } 7030 7031 // No need to create the controller 7032 if (mSelectionModifierCursorController != null) { 7033 mSelectionModifierCursorController.resetTouchOffsets(); 7034 } 7035 } 7036 7037 startStopMarquee(focused); 7038 7039 if (mTransformation != null) { 7040 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 7041 } 7042 7043 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7044 } 7045 7046 private int getLastTapPosition() { 7047 // No need to create the controller at that point, no last tap position saved 7048 if (mSelectionModifierCursorController != null) { 7049 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 7050 if (lastTapPosition >= 0) { 7051 // Safety check, should not be possible. 7052 if (lastTapPosition > mText.length()) { 7053 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 7054 + mText.length() + ")"); 7055 lastTapPosition = mText.length(); 7056 } 7057 return lastTapPosition; 7058 } 7059 } 7060 7061 return -1; 7062 } 7063 7064 @Override 7065 public void onWindowFocusChanged(boolean hasWindowFocus) { 7066 super.onWindowFocusChanged(hasWindowFocus); 7067 7068 if (hasWindowFocus) { 7069 if (mBlink != null) { 7070 mBlink.uncancel(); 7071 7072 if (isFocused()) { 7073 mShowCursor = SystemClock.uptimeMillis(); 7074 makeBlink(); 7075 } 7076 } 7077 } else { 7078 if (mBlink != null) { 7079 mBlink.cancel(); 7080 } 7081 // Don't leave us in the middle of a batch edit. 7082 onEndBatchEdit(); 7083 if (mInputContentType != null) { 7084 mInputContentType.enterDown = false; 7085 } 7086 hideControllers(); 7087 } 7088 7089 startStopMarquee(hasWindowFocus); 7090 } 7091 7092 @Override 7093 protected void onVisibilityChanged(View changedView, int visibility) { 7094 super.onVisibilityChanged(changedView, visibility); 7095 if (visibility != VISIBLE) { 7096 hideControllers(); 7097 } 7098 } 7099 7100 /** 7101 * Use {@link BaseInputConnection#removeComposingSpans 7102 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 7103 * state from this text view. 7104 */ 7105 public void clearComposingText() { 7106 if (mText instanceof Spannable) { 7107 BaseInputConnection.removeComposingSpans((Spannable)mText); 7108 } 7109 } 7110 7111 @Override 7112 public void setSelected(boolean selected) { 7113 boolean wasSelected = isSelected(); 7114 7115 super.setSelected(selected); 7116 7117 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7118 if (selected) { 7119 startMarquee(); 7120 } else { 7121 stopMarquee(); 7122 } 7123 } 7124 } 7125 7126 class CommitSelectionReceiver extends ResultReceiver { 7127 private final int mPrevStart, mPrevEnd; 7128 7129 public CommitSelectionReceiver(int prevStart, int prevEnd) { 7130 super(getHandler()); 7131 mPrevStart = prevStart; 7132 mPrevEnd = prevEnd; 7133 } 7134 7135 @Override 7136 protected void onReceiveResult(int resultCode, Bundle resultData) { 7137 // If this tap was actually used to show the IMM, leave cursor or selection unchanged 7138 // by restoring its previous position. 7139 if (resultCode == InputMethodManager.RESULT_SHOWN) { 7140 final int len = mText.length(); 7141 int start = Math.min(len, mPrevStart); 7142 int end = Math.min(len, mPrevEnd); 7143 Selection.setSelection((Spannable)mText, start, end); 7144 7145 if (hasSelection()) { 7146 startSelectionActionMode(); 7147 } 7148 } 7149 } 7150 } 7151 7152 @Override 7153 public boolean onTouchEvent(MotionEvent event) { 7154 final int action = event.getActionMasked(); 7155 7156 if (hasInsertionController()) { 7157 getInsertionController().onTouchEvent(event); 7158 } 7159 if (hasSelectionController()) { 7160 getSelectionController().onTouchEvent(event); 7161 } 7162 7163 if (action == MotionEvent.ACTION_DOWN) { 7164 mLastDownPositionX = (int) event.getX(); 7165 mLastDownPositionY = (int) event.getY(); 7166 7167 // Reset this state; it will be re-set if super.onTouchEvent 7168 // causes focus to move to the view. 7169 mTouchFocusSelected = false; 7170 mIgnoreActionUpEvent = false; 7171 } 7172 7173 final boolean superResult = super.onTouchEvent(event); 7174 7175 /* 7176 * Don't handle the release after a long press, because it will 7177 * move the selection away from whatever the menu action was 7178 * trying to affect. 7179 */ 7180 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 7181 mDiscardNextActionUp = false; 7182 return superResult; 7183 } 7184 7185 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 7186 && mText instanceof Spannable && mLayout != null) { 7187 boolean handled = false; 7188 7189 // Save previous selection, in case this event is used to show the IME. 7190 int oldSelStart = getSelectionStart(); 7191 int oldSelEnd = getSelectionEnd(); 7192 7193 final int oldScrollX = mScrollX; 7194 final int oldScrollY = mScrollY; 7195 7196 if (mMovement != null) { 7197 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 7198 } 7199 7200 if (isTextEditable() || mTextIsSelectable) { 7201 if (mScrollX != oldScrollX || mScrollY != oldScrollY) { 7202 // Hide insertion anchor while scrolling. Leave selection. 7203 hideInsertionPointCursorController(); 7204 // No need to create the controller, since there is nothing to update. 7205 if (mSelectionModifierCursorController != null && 7206 mSelectionModifierCursorController.isShowing()) { 7207 mSelectionModifierCursorController.updatePosition(); 7208 } 7209 } 7210 if (action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && isFocused()) { 7211 InputMethodManager imm = (InputMethodManager) 7212 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 7213 7214 CommitSelectionReceiver csr = null; 7215 if (getSelectionStart() != oldSelStart || getSelectionEnd() != oldSelEnd || 7216 didTouchFocusSelect()) { 7217 csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd); 7218 } 7219 7220 if (!mTextIsSelectable) { 7221 // Show the IME, except when selecting in read-only text. 7222 handled |= imm.showSoftInput(this, 0, csr) && (csr != null); 7223 } 7224 7225 stopSelectionActionMode(); 7226 boolean selectAllGotFocus = mSelectAllOnFocus && mTouchFocusSelected; 7227 if (hasInsertionController() && !selectAllGotFocus) { 7228 getInsertionController().show(); 7229 } 7230 } 7231 } 7232 7233 if (handled) { 7234 return true; 7235 } 7236 } 7237 7238 return superResult; 7239 } 7240 7241 private void prepareCursorControllers() { 7242 boolean windowSupportsHandles = false; 7243 7244 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 7245 if (params instanceof WindowManager.LayoutParams) { 7246 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 7247 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 7248 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 7249 } 7250 7251 mInsertionControllerEnabled = windowSupportsHandles && isTextEditable() && mCursorVisible && 7252 mLayout != null; 7253 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 7254 mLayout != null; 7255 7256 if (!mInsertionControllerEnabled) { 7257 hideInsertionPointCursorController(); 7258 mInsertionPointCursorController = null; 7259 } 7260 7261 if (!mSelectionControllerEnabled) { 7262 stopSelectionActionMode(); 7263 mSelectionModifierCursorController = null; 7264 } 7265 } 7266 7267 /** 7268 * @return True iff this TextView contains a text that can be edited, or if this is 7269 * a selectable TextView. 7270 */ 7271 private boolean isTextEditable() { 7272 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 7273 } 7274 7275 /** 7276 * Returns true, only while processing a touch gesture, if the initial 7277 * touch down event caused focus to move to the text view and as a result 7278 * its selection changed. Only valid while processing the touch gesture 7279 * of interest. 7280 */ 7281 public boolean didTouchFocusSelect() { 7282 return mTouchFocusSelected; 7283 } 7284 7285 @Override 7286 public void cancelLongPress() { 7287 super.cancelLongPress(); 7288 mIgnoreActionUpEvent = true; 7289 } 7290 7291 @Override 7292 public boolean onTrackballEvent(MotionEvent event) { 7293 if (mMovement != null && mText instanceof Spannable && 7294 mLayout != null) { 7295 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 7296 return true; 7297 } 7298 } 7299 7300 return super.onTrackballEvent(event); 7301 } 7302 7303 public void setScroller(Scroller s) { 7304 mScroller = s; 7305 } 7306 7307 private static class Blink extends Handler implements Runnable { 7308 private final WeakReference<TextView> mView; 7309 private boolean mCancelled; 7310 7311 public Blink(TextView v) { 7312 mView = new WeakReference<TextView>(v); 7313 } 7314 7315 public void run() { 7316 if (mCancelled) { 7317 return; 7318 } 7319 7320 removeCallbacks(Blink.this); 7321 7322 TextView tv = mView.get(); 7323 7324 if (tv != null && tv.isFocused()) { 7325 int st = tv.getSelectionStart(); 7326 int en = tv.getSelectionEnd(); 7327 7328 if (st == en && st >= 0 && en >= 0) { 7329 if (tv.mLayout != null) { 7330 tv.invalidateCursorPath(); 7331 } 7332 7333 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 7334 } 7335 } 7336 } 7337 7338 void cancel() { 7339 if (!mCancelled) { 7340 removeCallbacks(Blink.this); 7341 mCancelled = true; 7342 } 7343 } 7344 7345 void uncancel() { 7346 mCancelled = false; 7347 } 7348 } 7349 7350 @Override 7351 protected float getLeftFadingEdgeStrength() { 7352 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 7353 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7354 if (mMarquee != null && !mMarquee.isStopped()) { 7355 final Marquee marquee = mMarquee; 7356 if (marquee.shouldDrawLeftFade()) { 7357 return marquee.mScroll / getHorizontalFadingEdgeLength(); 7358 } else { 7359 return 0.0f; 7360 } 7361 } else if (getLineCount() == 1) { 7362 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 7363 case Gravity.LEFT: 7364 return 0.0f; 7365 case Gravity.RIGHT: 7366 return (mLayout.getLineRight(0) - (mRight - mLeft) - 7367 getCompoundPaddingLeft() - getCompoundPaddingRight() - 7368 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 7369 case Gravity.CENTER_HORIZONTAL: 7370 return 0.0f; 7371 } 7372 } 7373 } 7374 return super.getLeftFadingEdgeStrength(); 7375 } 7376 7377 @Override 7378 protected float getRightFadingEdgeStrength() { 7379 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 7380 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7381 if (mMarquee != null && !mMarquee.isStopped()) { 7382 final Marquee marquee = mMarquee; 7383 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 7384 } else if (getLineCount() == 1) { 7385 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 7386 case Gravity.LEFT: 7387 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 7388 getCompoundPaddingRight(); 7389 final float lineWidth = mLayout.getLineWidth(0); 7390 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 7391 case Gravity.RIGHT: 7392 return 0.0f; 7393 case Gravity.CENTER_HORIZONTAL: 7394 case Gravity.FILL_HORIZONTAL: 7395 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 7396 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 7397 getHorizontalFadingEdgeLength(); 7398 } 7399 } 7400 } 7401 return super.getRightFadingEdgeStrength(); 7402 } 7403 7404 @Override 7405 protected int computeHorizontalScrollRange() { 7406 if (mLayout != null) { 7407 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 7408 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 7409 } 7410 7411 return super.computeHorizontalScrollRange(); 7412 } 7413 7414 @Override 7415 protected int computeVerticalScrollRange() { 7416 if (mLayout != null) 7417 return mLayout.getHeight(); 7418 7419 return super.computeVerticalScrollRange(); 7420 } 7421 7422 @Override 7423 protected int computeVerticalScrollExtent() { 7424 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 7425 } 7426 7427 public enum BufferType { 7428 NORMAL, SPANNABLE, EDITABLE, 7429 } 7430 7431 /** 7432 * Returns the TextView_textColor attribute from the 7433 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 7434 * from the TextView_textAppearance attribute, if TextView_textColor 7435 * was not set directly. 7436 */ 7437 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 7438 ColorStateList colors; 7439 colors = attrs.getColorStateList(com.android.internal.R.styleable. 7440 TextView_textColor); 7441 7442 if (colors == null) { 7443 int ap = attrs.getResourceId(com.android.internal.R.styleable. 7444 TextView_textAppearance, -1); 7445 if (ap != -1) { 7446 TypedArray appearance; 7447 appearance = context.obtainStyledAttributes(ap, 7448 com.android.internal.R.styleable.TextAppearance); 7449 colors = appearance.getColorStateList(com.android.internal.R.styleable. 7450 TextAppearance_textColor); 7451 appearance.recycle(); 7452 } 7453 } 7454 7455 return colors; 7456 } 7457 7458 /** 7459 * Returns the default color from the TextView_textColor attribute 7460 * from the AttributeSet, if set, or the default color from the 7461 * TextAppearance_textColor from the TextView_textAppearance attribute, 7462 * if TextView_textColor was not set directly. 7463 */ 7464 public static int getTextColor(Context context, 7465 TypedArray attrs, 7466 int def) { 7467 ColorStateList colors = getTextColors(context, attrs); 7468 7469 if (colors == null) { 7470 return def; 7471 } else { 7472 return colors.getDefaultColor(); 7473 } 7474 } 7475 7476 @Override 7477 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7478 switch (keyCode) { 7479 case KeyEvent.KEYCODE_A: 7480 if (canSelectText()) { 7481 return onTextContextMenuItem(ID_SELECT_ALL); 7482 } 7483 7484 break; 7485 7486 case KeyEvent.KEYCODE_X: 7487 if (canCut()) { 7488 return onTextContextMenuItem(ID_CUT); 7489 } 7490 7491 break; 7492 7493 case KeyEvent.KEYCODE_C: 7494 if (canCopy()) { 7495 return onTextContextMenuItem(ID_COPY); 7496 } 7497 7498 break; 7499 7500 case KeyEvent.KEYCODE_V: 7501 if (canPaste()) { 7502 return onTextContextMenuItem(ID_PASTE); 7503 } 7504 7505 break; 7506 } 7507 7508 return super.onKeyShortcut(keyCode, event); 7509 } 7510 7511 private boolean canSelectText() { 7512 return hasSelectionController() && mText.length() != 0; 7513 } 7514 7515 private boolean textCanBeSelected() { 7516 // prepareCursorController() relies on this method. 7517 // If you change this condition, make sure prepareCursorController is called anywhere 7518 // the value of this condition might be changed. 7519 return mText instanceof Spannable && mMovement != null && mMovement.canSelectArbitrarily(); 7520 } 7521 7522 private boolean canCut() { 7523 if (hasPasswordTransformationMethod()) { 7524 return false; 7525 } 7526 7527 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 7528 return true; 7529 } 7530 7531 return false; 7532 } 7533 7534 private boolean canCopy() { 7535 if (hasPasswordTransformationMethod()) { 7536 return false; 7537 } 7538 7539 if (mText.length() > 0 && hasSelection()) { 7540 return true; 7541 } 7542 7543 return false; 7544 } 7545 7546 private boolean canPaste() { 7547 return (mText instanceof Editable && 7548 mInput != null && 7549 getSelectionStart() >= 0 && 7550 getSelectionEnd() >= 0 && 7551 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 7552 hasPrimaryClip()); 7553 } 7554 7555 private boolean isWordCharacter(int position) { 7556 final char c = mTransformed.charAt(position); 7557 final int type = Character.getType(c); 7558 return (c == '\'' || c == '"' || 7559 type == Character.UPPERCASE_LETTER || 7560 type == Character.LOWERCASE_LETTER || 7561 type == Character.TITLECASE_LETTER || 7562 type == Character.MODIFIER_LETTER || 7563 type == Character.DECIMAL_DIGIT_NUMBER); 7564 } 7565 7566 /** 7567 * Returns the offsets delimiting the 'word' located at position offset. 7568 * 7569 * @param offset An offset in the text. 7570 * @return The offsets for the start and end of the word located at <code>offset</code>. 7571 * The two ints offsets are packed in a long, with the starting offset shifted by 32 bits. 7572 * Returns a negative value if no valid word was found. 7573 */ 7574 private long getWordLimitsAt(int offset) { 7575 int klass = mInputType & InputType.TYPE_MASK_CLASS; 7576 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 7577 7578 // Text selection is not permitted in password fields 7579 if (variation == InputType.TYPE_TEXT_VARIATION_PASSWORD || 7580 variation == InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD || 7581 variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) { 7582 return -1; 7583 } 7584 7585 final int len = mText.length(); 7586 7587 // Specific text fields: always select the entire text 7588 if (klass == InputType.TYPE_CLASS_NUMBER || 7589 klass == InputType.TYPE_CLASS_PHONE || 7590 klass == InputType.TYPE_CLASS_DATETIME || 7591 variation == InputType.TYPE_TEXT_VARIATION_URI || 7592 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 7593 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 7594 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 7595 return len > 0 ? packRangeInLong(0, len) : -1; 7596 } 7597 7598 int end = Math.min(offset, len); 7599 if (end < 0) { 7600 return -1; 7601 } 7602 7603 final int MAX_LENGTH = 48; 7604 int start = end; 7605 7606 for (; start > 0; start--) { 7607 if (start == end) { 7608 // Cases where the text ends with a '.' and we select from the end of the line 7609 // (right after the dot), or when we select from the space character in "aaa, bbb". 7610 final char c = mTransformed.charAt(start); 7611 final int type = Character.getType(c); 7612 if (type == Character.OTHER_PUNCTUATION) continue; 7613 } 7614 if (!isWordCharacter(start - 1)) break; 7615 if ((end - start) > MAX_LENGTH) return -1; 7616 } 7617 7618 for (; end < len; end++) { 7619 if (!isWordCharacter(end)) break; 7620 if ((end - start) > MAX_LENGTH) return -1; 7621 } 7622 7623 if (start == end) { 7624 return -1; 7625 } 7626 7627 boolean hasLetter = false; 7628 for (int i = start; i < end; i++) { 7629 if (Character.isLetter(mTransformed.charAt(i))) { 7630 hasLetter = true; 7631 break; 7632 } 7633 } 7634 7635 if (!hasLetter) { 7636 return -1; 7637 } 7638 7639 // Two ints packed in a long 7640 return packRangeInLong(start, end); 7641 } 7642 7643 private static long packRangeInLong(int start, int end) { 7644 return (((long) start) << 32) | end; 7645 } 7646 7647 private static int extractRangeStartFromLong(long range) { 7648 return (int) (range >>> 32); 7649 } 7650 7651 private static int extractRangeEndFromLong(long range) { 7652 return (int) (range & 0x00000000FFFFFFFFL); 7653 } 7654 7655 private void selectAll() { 7656 Selection.setSelection((Spannable) mText, 0, mText.length()); 7657 } 7658 7659 private void selectCurrentWord() { 7660 if (!canSelectText()) { 7661 return; 7662 } 7663 7664 if (hasPasswordTransformationMethod()) { 7665 // selectCurrentWord is not available on a password field and would return an 7666 // arbitrary 10-charater selection around pressed position. Select all instead. 7667 // Note that cut/copy menu entries are not available for passwords. 7668 // This is however useful to delete or paste to replace the entire content. 7669 selectAll(); 7670 return; 7671 } 7672 7673 int minOffset, maxOffset; 7674 7675 if (mContextMenuTriggeredByKey) { 7676 minOffset = getSelectionStart(); 7677 maxOffset = getSelectionEnd(); 7678 } else { 7679 SelectionModifierCursorController selectionController = getSelectionController(); 7680 minOffset = selectionController.getMinTouchOffset(); 7681 maxOffset = selectionController.getMaxTouchOffset(); 7682 } 7683 7684 int selectionStart, selectionEnd; 7685 7686 long wordLimits = getWordLimitsAt(minOffset); 7687 if (wordLimits >= 0) { 7688 selectionStart = extractRangeStartFromLong(wordLimits); 7689 } else { 7690 selectionStart = Math.max(minOffset - 5, 0); 7691 } 7692 7693 wordLimits = getWordLimitsAt(maxOffset); 7694 if (wordLimits >= 0) { 7695 selectionEnd = extractRangeEndFromLong(wordLimits); 7696 } else { 7697 selectionEnd = Math.min(maxOffset + 5, mText.length()); 7698 } 7699 7700 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 7701 } 7702 7703 @Override 7704 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 7705 if (!isShown()) { 7706 return false; 7707 } 7708 7709 final boolean isPassword = hasPasswordTransformationMethod(); 7710 7711 if (!isPassword) { 7712 CharSequence text = getText(); 7713 if (TextUtils.isEmpty(text)) { 7714 text = getHint(); 7715 } 7716 if (!TextUtils.isEmpty(text)) { 7717 if (text.length() > AccessibilityEvent.MAX_TEXT_LENGTH) { 7718 text = text.subSequence(0, AccessibilityEvent.MAX_TEXT_LENGTH + 1); 7719 } 7720 event.getText().add(text); 7721 } 7722 } else { 7723 event.setPassword(isPassword); 7724 } 7725 return false; 7726 } 7727 7728 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 7729 int fromIndex, int removedCount, int addedCount) { 7730 AccessibilityEvent event = 7731 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 7732 event.setFromIndex(fromIndex); 7733 event.setRemovedCount(removedCount); 7734 event.setAddedCount(addedCount); 7735 event.setBeforeText(beforeText); 7736 sendAccessibilityEventUnchecked(event); 7737 } 7738 7739 @Override 7740 protected void onCreateContextMenu(ContextMenu menu) { 7741 super.onCreateContextMenu(menu); 7742 boolean added = false; 7743 mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown; 7744 // Problem with context menu on long press: the menu appears while the key in down and when 7745 // the key is released, the view does not receive the key_up event. This ensures that the 7746 // state is reset whenever the context menu action is displayed. 7747 // mContextMenuTriggeredByKey saved that state so that it is available in 7748 // onTextContextMenuItem. We cannot simply clear these flags in onTextContextMenuItem since 7749 // it may not be called (if the user/ discards the context menu with the back key). 7750 mDPadCenterIsDown = mEnterKeyIsDown = false; 7751 7752 MenuHandler handler = new MenuHandler(); 7753 7754 if (mText instanceof Spanned) { 7755 int selStart = getSelectionStart(); 7756 int selEnd = getSelectionEnd(); 7757 7758 int min = Math.min(selStart, selEnd); 7759 int max = Math.max(selStart, selEnd); 7760 7761 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, 7762 URLSpan.class); 7763 if (urls.length == 1) { 7764 menu.add(0, ID_COPY_URL, 0, 7765 com.android.internal.R.string.copyUrl). 7766 setOnMenuItemClickListener(handler); 7767 7768 added = true; 7769 } 7770 } 7771 7772 // The context menu is not empty, which will prevent the selection mode from starting. 7773 // Add a entry to start it in the context menu. 7774 // TODO Does not handle the case where a subclass does not call super.thisMethod or 7775 // populates the menu AFTER this call. 7776 if (menu.size() > 0) { 7777 menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode). 7778 setOnMenuItemClickListener(handler); 7779 added = true; 7780 } 7781 7782 if (added) { 7783 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 7784 } 7785 } 7786 7787 /** 7788 * Returns whether this text view is a current input method target. The 7789 * default implementation just checks with {@link InputMethodManager}. 7790 */ 7791 public boolean isInputMethodTarget() { 7792 InputMethodManager imm = InputMethodManager.peekInstance(); 7793 return imm != null && imm.isActive(this); 7794 } 7795 7796 // Selection context mode 7797 private static final int ID_SELECT_ALL = android.R.id.selectAll; 7798 private static final int ID_CUT = android.R.id.cut; 7799 private static final int ID_COPY = android.R.id.copy; 7800 private static final int ID_PASTE = android.R.id.paste; 7801 // Context menu entries 7802 private static final int ID_COPY_URL = android.R.id.copyUrl; 7803 private static final int ID_SELECTION_MODE = android.R.id.selectTextMode; 7804 7805 private class MenuHandler implements MenuItem.OnMenuItemClickListener { 7806 public boolean onMenuItemClick(MenuItem item) { 7807 return onTextContextMenuItem(item.getItemId()); 7808 } 7809 } 7810 7811 /** 7812 * Called when a context menu option for the text view is selected. Currently 7813 * this will be {@link android.R.id#copyUrl} or {@link android.R.id#selectTextMode}. 7814 */ 7815 public boolean onTextContextMenuItem(int id) { 7816 int min = 0; 7817 int max = mText.length(); 7818 7819 if (isFocused()) { 7820 final int selStart = getSelectionStart(); 7821 final int selEnd = getSelectionEnd(); 7822 7823 min = Math.max(0, Math.min(selStart, selEnd)); 7824 max = Math.max(0, Math.max(selStart, selEnd)); 7825 } 7826 7827 ClipboardManager clipboard = (ClipboardManager)getContext() 7828 .getSystemService(Context.CLIPBOARD_SERVICE); 7829 7830 switch (id) { 7831 case ID_COPY_URL: 7832 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class); 7833 if (urls.length >= 1) { 7834 ClipData clip = null; 7835 for (int i=0; i<urls.length; i++) { 7836 Uri uri = Uri.parse(urls[0].getURL()); 7837 if (clip == null) { 7838 clip = ClipData.newRawUri(null, null, uri); 7839 } else { 7840 clip.addItem(new ClipData.Item(uri)); 7841 } 7842 } 7843 if (clip != null) { 7844 setPrimaryClip(clip); 7845 } 7846 } 7847 return true; 7848 7849 case ID_SELECTION_MODE: 7850 startSelectionActionMode(); 7851 return true; 7852 } 7853 7854 return false; 7855 } 7856 7857 /** 7858 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 7859 * by [min, max] when replacing this region by paste. 7860 * Note that if there was two spaces (or more) at that position before, they are kept. We just 7861 * make sure we do not add an extra one from the paste content. 7862 */ 7863 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 7864 // Paste adds/removes spaces before or after insertion as needed. 7865 if (paste.length() > 0 && Character.isSpaceChar(paste.charAt(0))) { 7866 if (min > 0 && Character.isSpaceChar(mTransformed.charAt(min - 1))) { 7867 // Two spaces at beginning of paste: remove one 7868 final int originalLength = mText.length(); 7869 ((Editable) mText).delete(min - 1, min); 7870 // Due to filters, there is no guarantee that exactly one character was 7871 // removed. Count instead. 7872 final int delta = mText.length() - originalLength; 7873 min += delta; 7874 max += delta; 7875 } 7876 } else { 7877 if (min > 0 && !Character.isSpaceChar(mTransformed.charAt(min - 1))) { 7878 // No space at beginning of paste: add one 7879 final int originalLength = mText.length(); 7880 ((Editable) mText).replace(min, min, " "); 7881 // Taking possible filters into account as above. 7882 final int delta = mText.length() - originalLength; 7883 min += delta; 7884 max += delta; 7885 } 7886 } 7887 7888 if (paste.length() > 0 && Character.isSpaceChar(paste.charAt(paste.length() - 1))) { 7889 if (max < mText.length() && Character.isSpaceChar(mTransformed.charAt(max))) { 7890 // Two spaces at end of paste: remove one 7891 ((Editable) mText).delete(max, max + 1); 7892 } 7893 } else { 7894 if (max < mText.length() && !Character.isSpaceChar(mTransformed.charAt(max))) { 7895 // No space at end of paste: add one 7896 ((Editable) mText).replace(max, max, " "); 7897 } 7898 } 7899 7900 return packRangeInLong(min, max); 7901 } 7902 7903 private DragThumbnailBuilder getTextThumbnailBuilder(CharSequence text) { 7904 TextView thumbnail = (TextView) inflate(mContext, 7905 com.android.internal.R.layout.text_drag_thumbnail, null); 7906 7907 if (thumbnail == null) { 7908 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 7909 } 7910 7911 if (text.length() > DRAG_THUMBNAIL_MAX_TEXT_LENGTH) { 7912 text = text.subSequence(0, DRAG_THUMBNAIL_MAX_TEXT_LENGTH); 7913 } 7914 thumbnail.setText(text); 7915 thumbnail.setTextColor(getTextColors()); 7916 7917 thumbnail.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 7918 thumbnail.setGravity(Gravity.CENTER); 7919 7920 thumbnail.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 7921 ViewGroup.LayoutParams.WRAP_CONTENT)); 7922 7923 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 7924 thumbnail.measure(size, size); 7925 7926 thumbnail.layout(0, 0, thumbnail.getMeasuredWidth(), thumbnail.getMeasuredHeight()); 7927 thumbnail.invalidate(); 7928 return new DragThumbnailBuilder(thumbnail); 7929 } 7930 7931 private static class DragLocalState { 7932 public TextView sourceTextView; 7933 public int start, end; 7934 7935 public DragLocalState(TextView sourceTextView, int start, int end) { 7936 this.sourceTextView = sourceTextView; 7937 this.start = start; 7938 this.end = end; 7939 } 7940 } 7941 7942 @Override 7943 public boolean performLongClick() { 7944 if (super.performLongClick()) { 7945 mDiscardNextActionUp = true; 7946 return true; 7947 } 7948 7949 if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 7950 mInsertionControllerEnabled) { 7951 // Long press in empty space moves cursor and shows the Paste affordance if available. 7952 final int offset = getOffset(mLastDownPositionX, mLastDownPositionY); 7953 stopSelectionActionMode(); 7954 Selection.setSelection((Spannable)mText, offset); 7955 getInsertionController().show(0); 7956 mDiscardNextActionUp = true; 7957 return true; 7958 } 7959 7960 if (mSelectionActionMode != null) { 7961 if (touchPositionIsInSelection()) { 7962 // Start a drag 7963 final int start = getSelectionStart(); 7964 final int end = getSelectionEnd(); 7965 CharSequence selectedText = mTransformed.subSequence(start, end); 7966 ClipData data = ClipData.newPlainText(null, null, selectedText); 7967 DragLocalState localState = new DragLocalState(this, start, end); 7968 startDrag(data, getTextThumbnailBuilder(selectedText), false, localState); 7969 stopSelectionActionMode(); 7970 } else { 7971 selectCurrentWord(); 7972 getSelectionController().show(); 7973 } 7974 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 7975 mDiscardNextActionUp = true; 7976 return true; 7977 } 7978 7979 if (startSelectionActionMode()) { 7980 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 7981 mDiscardNextActionUp = true; 7982 return true; 7983 } 7984 7985 return false; 7986 } 7987 7988 private boolean touchPositionIsInSelection() { 7989 int selectionStart = getSelectionStart(); 7990 int selectionEnd = getSelectionEnd(); 7991 7992 if (selectionStart == selectionEnd) { 7993 return false; 7994 } 7995 7996 if (selectionStart > selectionEnd) { 7997 int tmp = selectionStart; 7998 selectionStart = selectionEnd; 7999 selectionEnd = tmp; 8000 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8001 } 8002 8003 SelectionModifierCursorController selectionController = getSelectionController(); 8004 int minOffset = selectionController.getMinTouchOffset(); 8005 int maxOffset = selectionController.getMaxTouchOffset(); 8006 8007 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 8008 } 8009 8010 /** 8011 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 8012 * selection is initiated in this View. 8013 * 8014 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 8015 * Paste actions, depending on what this View supports. 8016 * 8017 * A custom implementation can add new entries in the default menu in its 8018 * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions 8019 * can also be removed from the menu using {@link Menu#removeItem(int)} and passing 8020 * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or 8021 * {@link android.R.id#paste} ids as parameters. 8022 * 8023 * Action click events should be handled by the custom implementation of 8024 * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 8025 * 8026 * Note that text selection mode is not started when a TextView receives focus and the 8027 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 8028 * that case, to allow for quick replacement. 8029 */ 8030 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 8031 mCustomSelectionActionModeCallback = actionModeCallback; 8032 } 8033 8034 /** 8035 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 8036 * 8037 * @return The current custom selection callback. 8038 */ 8039 public ActionMode.Callback getCustomSelectionActionModeCallback() { 8040 return mCustomSelectionActionModeCallback; 8041 } 8042 8043 /** 8044 * 8045 * @return true if the selection mode was actually started. 8046 */ 8047 private boolean startSelectionActionMode() { 8048 if (mSelectionActionMode != null) { 8049 // Selection action mode is already started 8050 return false; 8051 } 8052 8053 selectCurrentWord(); 8054 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 8055 mSelectionActionMode = startActionMode(actionModeCallback); 8056 return mSelectionActionMode != null; 8057 } 8058 8059 /** 8060 * Same as {@link #stopSelectionActionMode()}, except that there is no cursor controller 8061 * fade out animation. Needed since the drawable and their alpha values are shared by all 8062 * TextViews. Switching from one TextView to another would fade the cursor controllers in the 8063 * new one otherwise. 8064 */ 8065 private void terminateSelectionActionMode() { 8066 stopSelectionActionMode(); 8067 8068 // No need to create the controller, nothing to cancel in that case. 8069 if (mSelectionModifierCursorController != null) { 8070 mSelectionModifierCursorController.cancelFadeOutAnimation(); 8071 } 8072 } 8073 8074 private void stopSelectionActionMode() { 8075 if (mSelectionActionMode != null) { 8076 mSelectionActionMode.finish(); 8077 } 8078 } 8079 8080 /** 8081 * Paste clipboard content between min and max positions. 8082 */ 8083 private void paste(int min, int max) { 8084 ClipboardManager clipboard = 8085 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 8086 ClipData clip = clipboard.getPrimaryClip(); 8087 if (clip != null) { 8088 boolean didfirst = false; 8089 for (int i=0; i<clip.getItemCount(); i++) { 8090 CharSequence paste = clip.getItem(i).coerceToText(getContext()); 8091 if (paste != null) { 8092 if (!didfirst) { 8093 long minMax = prepareSpacesAroundPaste(min, max, paste); 8094 min = extractRangeStartFromLong(minMax); 8095 max = extractRangeEndFromLong(minMax); 8096 Selection.setSelection((Spannable) mText, max); 8097 ((Editable) mText).replace(min, max, paste); 8098 } else { 8099 ((Editable) mText).insert(getSelectionEnd(), "\n"); 8100 ((Editable) mText).insert(getSelectionEnd(), paste); 8101 } 8102 } 8103 } 8104 stopSelectionActionMode(); 8105 sLastCutOrCopyTime = 0; 8106 } 8107 } 8108 8109 private void setPrimaryClip(ClipData clip) { 8110 ClipboardManager clipboard = (ClipboardManager) getContext(). 8111 getSystemService(Context.CLIPBOARD_SERVICE); 8112 clipboard.setPrimaryClip(clip); 8113 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 8114 } 8115 8116 /** 8117 * An ActionMode Callback class that is used to provide actions while in text selection mode. 8118 * 8119 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 8120 * on which of these this TextView supports. 8121 */ 8122 private class SelectionActionModeCallback implements ActionMode.Callback { 8123 8124 @Override 8125 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 8126 if (!hasSelectionController()) { 8127 Log.w(LOG_TAG, "TextView has no selection controller. Action mode cancelled."); 8128 return false; 8129 } 8130 8131 if (!requestFocus()) { 8132 return false; 8133 } 8134 8135 TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme); 8136 8137 mode.setTitle(mContext.getString(com.android.internal.R.string.textSelectionCABTitle)); 8138 mode.setSubtitle(null); 8139 8140 if (canSelectText()) { 8141 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 8142 setAlphabeticShortcut('a'). 8143 setShowAsAction( 8144 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8145 } 8146 8147 if (canCut()) { 8148 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 8149 setIcon(styledAttributes.getResourceId( 8150 R.styleable.Theme_actionModeCutDrawable, 0)). 8151 setAlphabeticShortcut('x'). 8152 setShowAsAction( 8153 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8154 } 8155 8156 if (canCopy()) { 8157 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 8158 setIcon(styledAttributes.getResourceId( 8159 R.styleable.Theme_actionModeCopyDrawable, 0)). 8160 setAlphabeticShortcut('c'). 8161 setShowAsAction( 8162 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8163 } 8164 8165 if (canPaste()) { 8166 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 8167 setIcon(styledAttributes.getResourceId( 8168 R.styleable.Theme_actionModePasteDrawable, 0)). 8169 setAlphabeticShortcut('v'). 8170 setShowAsAction( 8171 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8172 } 8173 8174 styledAttributes.recycle(); 8175 8176 if (mCustomSelectionActionModeCallback != null) { 8177 mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu); 8178 } 8179 8180 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 8181 getSelectionController().show(); 8182 return true; 8183 } else { 8184 return false; 8185 } 8186 } 8187 8188 @Override 8189 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 8190 if (mCustomSelectionActionModeCallback != null) { 8191 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 8192 } 8193 return true; 8194 } 8195 8196 @Override 8197 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 8198 if (mCustomSelectionActionModeCallback != null && 8199 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 8200 return true; 8201 } 8202 8203 final int itemId = item.getItemId(); 8204 8205 if (itemId == ID_SELECT_ALL) { 8206 selectAll(); 8207 // Update controller positions after selection change. 8208 if (hasSelectionController()) { 8209 getSelectionController().show(); 8210 } 8211 return true; 8212 } 8213 8214 int min = 0; 8215 int max = mText.length(); 8216 8217 if (isFocused()) { 8218 final int selStart = getSelectionStart(); 8219 final int selEnd = getSelectionEnd(); 8220 8221 min = Math.max(0, Math.min(selStart, selEnd)); 8222 max = Math.max(0, Math.max(selStart, selEnd)); 8223 } 8224 8225 switch (item.getItemId()) { 8226 case ID_PASTE: 8227 paste(min, max); 8228 return true; 8229 8230 case ID_CUT: 8231 setPrimaryClip(ClipData.newPlainText(null, null, 8232 mTransformed.subSequence(min, max))); 8233 ((Editable) mText).delete(min, max); 8234 stopSelectionActionMode(); 8235 return true; 8236 8237 case ID_COPY: 8238 setPrimaryClip(ClipData.newPlainText(null, null, 8239 mTransformed.subSequence(min, max))); 8240 stopSelectionActionMode(); 8241 return true; 8242 } 8243 8244 return false; 8245 } 8246 8247 @Override 8248 public void onDestroyActionMode(ActionMode mode) { 8249 if (mCustomSelectionActionModeCallback != null) { 8250 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 8251 } 8252 Selection.setSelection((Spannable) mText, getSelectionStart()); 8253 hideSelectionModifierCursorController(); 8254 mSelectionActionMode = null; 8255 } 8256 } 8257 8258 /** 8259 * A CursorController instance can be used to control a cursor in the text. 8260 * It is not used outside of {@link TextView}. 8261 * @hide 8262 */ 8263 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 8264 /** 8265 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 8266 * See also {@link #hide()}. 8267 */ 8268 public void show(); 8269 8270 /** 8271 * Hide the cursor controller from screen. 8272 * See also {@link #show()}. 8273 */ 8274 public void hide(); 8275 8276 /** 8277 * @return true if the CursorController is currently visible 8278 */ 8279 public boolean isShowing(); 8280 8281 /** 8282 * Update the controller's position. 8283 */ 8284 public void updatePosition(HandleView handle, int x, int y); 8285 8286 public void updatePosition(); 8287 8288 /** 8289 * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller 8290 * a chance to become active and/or visible. 8291 * @param event The touch event 8292 */ 8293 public boolean onTouchEvent(MotionEvent event); 8294 } 8295 8296 private class PastePopupMenu implements OnClickListener { 8297 private PopupWindow mContainer; 8298 private int mPositionX; 8299 private int mPositionY; 8300 private View mPasteView, mNoPasteView; 8301 8302 public PastePopupMenu() { 8303 mContainer = new PopupWindow(TextView.this.mContext, null, 8304 com.android.internal.R.attr.textSelectHandleWindowStyle); 8305 mContainer.setSplitTouchEnabled(true); 8306 mContainer.setClippingEnabled(false); 8307 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8308 8309 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 8310 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 8311 } 8312 8313 private void updateContent() { 8314 View view = canPaste() ? mPasteView : mNoPasteView; 8315 8316 if (view == null) { 8317 final int layout = canPaste() ? mTextEditPasteWindowLayout : 8318 mTextEditNoPasteWindowLayout; 8319 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 8320 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 8321 if (inflater != null) { 8322 view = inflater.inflate(layout, null); 8323 } 8324 8325 if (view == null) { 8326 throw new IllegalArgumentException("Unable to inflate TextEdit paste window"); 8327 } 8328 8329 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8330 view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8331 ViewGroup.LayoutParams.WRAP_CONTENT)); 8332 view.measure(size, size); 8333 8334 view.setOnClickListener(this); 8335 8336 if (canPaste()) mPasteView = view; 8337 else mNoPasteView = view; 8338 } 8339 8340 mContainer.setContentView(view); 8341 } 8342 8343 public void show() { 8344 updateContent(); 8345 final int[] coords = mTempCoords; 8346 TextView.this.getLocationInWindow(coords); 8347 positionAtCursor(); 8348 coords[0] += mPositionX; 8349 coords[1] += mPositionY; 8350 coords[0] = Math.max(0, coords[0]); 8351 final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels; 8352 coords[0] = Math.min(screenWidth - mContainer.getContentView().getMeasuredWidth(), 8353 coords[0]); 8354 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); 8355 } 8356 8357 public void hide() { 8358 mContainer.dismiss(); 8359 } 8360 8361 public boolean isShowing() { 8362 return mContainer.isShowing(); 8363 } 8364 8365 @Override 8366 public void onClick(View v) { 8367 if (canPaste()) { 8368 paste(getSelectionStart(), getSelectionEnd()); 8369 } 8370 hide(); 8371 } 8372 8373 void positionAtCursor() { 8374 final int offset = TextView.this.getSelectionStart(); 8375 View contentView = mContainer.getContentView(); 8376 final int width = contentView.getMeasuredWidth(); 8377 final int height = contentView.getMeasuredHeight(); 8378 final int line = mLayout.getLineForOffset(offset); 8379 final int lineTop = mLayout.getLineTop(line); 8380 8381 final Rect bounds = sCursorControllerTempRect; 8382 bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f); 8383 bounds.top = lineTop - height; 8384 8385 bounds.right = bounds.left + width; 8386 bounds.bottom = bounds.top + height; 8387 8388 convertFromViewportToContentCoordinates(bounds); 8389 8390 mPositionX = bounds.left; 8391 mPositionY = bounds.top; 8392 } 8393 } 8394 8395 private class HandleView extends View { 8396 private boolean mPositionOnTop = false; 8397 private Drawable mDrawable; 8398 private PopupWindow mContainer; 8399 private int mPositionX; 8400 private int mPositionY; 8401 private CursorController mController; 8402 private boolean mIsDragging; 8403 private float mTouchToWindowOffsetX; 8404 private float mTouchToWindowOffsetY; 8405 private float mHotspotX; 8406 private float mHotspotY; 8407 private int mHeight; 8408 private float mTouchOffsetY; 8409 private int mLastParentX; 8410 private int mLastParentY; 8411 private float mDownPositionX, mDownPositionY; 8412 private int mContainerPositionX, mContainerPositionY; 8413 private long mTouchTimer; 8414 private boolean mIsInsertionHandle = false; 8415 private PastePopupMenu mPastePopupWindow; 8416 private LongPressCallback mLongPressCallback; 8417 8418 public static final int LEFT = 0; 8419 public static final int CENTER = 1; 8420 public static final int RIGHT = 2; 8421 8422 class LongPressCallback implements Runnable { 8423 public void run() { 8424 mController.hide(); 8425 startSelectionActionMode(); 8426 } 8427 } 8428 8429 public HandleView(CursorController controller, int pos) { 8430 super(TextView.this.mContext); 8431 mController = controller; 8432 mContainer = new PopupWindow(TextView.this.mContext, null, 8433 com.android.internal.R.attr.textSelectHandleWindowStyle); 8434 mContainer.setSplitTouchEnabled(true); 8435 mContainer.setClippingEnabled(false); 8436 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8437 8438 setOrientation(pos); 8439 } 8440 8441 public void setOrientation(int pos) { 8442 int handleWidth; 8443 switch (pos) { 8444 case LEFT: { 8445 if (mSelectHandleLeft == null) { 8446 mSelectHandleLeft = mContext.getResources().getDrawable( 8447 mTextSelectHandleLeftRes); 8448 } 8449 mDrawable = mSelectHandleLeft; 8450 handleWidth = mDrawable.getIntrinsicWidth(); 8451 mHotspotX = (handleWidth * 3) / 4; 8452 break; 8453 } 8454 8455 case RIGHT: { 8456 if (mSelectHandleRight == null) { 8457 mSelectHandleRight = mContext.getResources().getDrawable( 8458 mTextSelectHandleRightRes); 8459 } 8460 mDrawable = mSelectHandleRight; 8461 handleWidth = mDrawable.getIntrinsicWidth(); 8462 mHotspotX = handleWidth / 4; 8463 break; 8464 } 8465 8466 case CENTER: 8467 default: { 8468 if (mSelectHandleCenter == null) { 8469 mSelectHandleCenter = mContext.getResources().getDrawable( 8470 mTextSelectHandleRes); 8471 } 8472 mDrawable = mSelectHandleCenter; 8473 handleWidth = mDrawable.getIntrinsicWidth(); 8474 mHotspotX = handleWidth / 2; 8475 mIsInsertionHandle = true; 8476 break; 8477 } 8478 } 8479 8480 final int handleHeight = mDrawable.getIntrinsicHeight(); 8481 8482 mTouchOffsetY = -handleHeight * 0.3f; 8483 mHotspotY = 0; 8484 mHeight = handleHeight; 8485 invalidate(); 8486 } 8487 8488 @Override 8489 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 8490 setMeasuredDimension(mDrawable.getIntrinsicWidth(), 8491 mDrawable.getIntrinsicHeight()); 8492 } 8493 8494 public void show() { 8495 if (!isPositionVisible()) { 8496 hide(); 8497 return; 8498 } 8499 mContainer.setContentView(this); 8500 final int[] coords = mTempCoords; 8501 TextView.this.getLocationInWindow(coords); 8502 mContainerPositionX = coords[0] + mPositionX; 8503 mContainerPositionY = coords[1] + mPositionY; 8504 mContainer.showAtLocation(TextView.this, 0, mContainerPositionX, mContainerPositionY); 8505 8506 // Hide paste view when handle is moved on screen. 8507 if (mPastePopupWindow != null) { 8508 mPastePopupWindow.hide(); 8509 } 8510 } 8511 8512 public void hide() { 8513 mIsDragging = false; 8514 mContainer.dismiss(); 8515 if (mPastePopupWindow != null) { 8516 mPastePopupWindow.hide(); 8517 } 8518 } 8519 8520 public boolean isShowing() { 8521 return mContainer.isShowing(); 8522 } 8523 8524 private boolean isPositionVisible() { 8525 // Always show a dragging handle. 8526 if (mIsDragging) { 8527 return true; 8528 } 8529 8530 if (isInBatchEditMode()) { 8531 return false; 8532 } 8533 8534 final int extendedPaddingTop = getExtendedPaddingTop(); 8535 final int extendedPaddingBottom = getExtendedPaddingBottom(); 8536 final int compoundPaddingLeft = getCompoundPaddingLeft(); 8537 final int compoundPaddingRight = getCompoundPaddingRight(); 8538 8539 final TextView hostView = TextView.this; 8540 final int left = 0; 8541 final int right = hostView.getWidth(); 8542 final int top = 0; 8543 final int bottom = hostView.getHeight(); 8544 8545 if (mTempRect == null) { 8546 mTempRect = new Rect(); 8547 } 8548 final Rect clip = mTempRect; 8549 clip.left = left + compoundPaddingLeft; 8550 clip.top = top + extendedPaddingTop; 8551 clip.right = right - compoundPaddingRight; 8552 clip.bottom = bottom - extendedPaddingBottom; 8553 8554 final ViewParent parent = hostView.getParent(); 8555 if (parent == null || !parent.getChildVisibleRect(hostView, clip, null)) { 8556 return false; 8557 } 8558 8559 final int[] coords = mTempCoords; 8560 hostView.getLocationInWindow(coords); 8561 final int posX = coords[0] + mPositionX + (int) mHotspotX; 8562 final int posY = coords[1] + mPositionY + (int) mHotspotY; 8563 8564 return posX >= clip.left && posX <= clip.right && 8565 posY >= clip.top && posY <= clip.bottom; 8566 } 8567 8568 private void moveTo(int x, int y) { 8569 mPositionX = x - TextView.this.mScrollX; 8570 mPositionY = y - TextView.this.mScrollY; 8571 if (isPositionVisible()) { 8572 int[] coords = null; 8573 if (mContainer.isShowing()) { 8574 coords = mTempCoords; 8575 TextView.this.getLocationInWindow(coords); 8576 final int containerPositionX = coords[0] + mPositionX; 8577 final int containerPositionY = coords[1] + mPositionY; 8578 8579 if (containerPositionX != mContainerPositionX || 8580 containerPositionY != mContainerPositionY) { 8581 mContainerPositionX = containerPositionX; 8582 mContainerPositionY = containerPositionY; 8583 8584 mContainer.update(mContainerPositionX, mContainerPositionY, 8585 mRight - mLeft, mBottom - mTop); 8586 8587 // Hide paste popup window as soon as a scroll occurs. 8588 if (mPastePopupWindow != null) { 8589 mPastePopupWindow.hide(); 8590 } 8591 } 8592 } else { 8593 show(); 8594 } 8595 8596 if (mIsDragging) { 8597 if (coords == null) { 8598 coords = mTempCoords; 8599 TextView.this.getLocationInWindow(coords); 8600 } 8601 if (coords[0] != mLastParentX || coords[1] != mLastParentY) { 8602 mTouchToWindowOffsetX += coords[0] - mLastParentX; 8603 mTouchToWindowOffsetY += coords[1] - mLastParentY; 8604 mLastParentX = coords[0]; 8605 mLastParentY = coords[1]; 8606 } 8607 // Hide paste popup window as soon as the handle is dragged. 8608 if (mPastePopupWindow != null) { 8609 mPastePopupWindow.hide(); 8610 } 8611 } 8612 } else { 8613 hide(); 8614 } 8615 } 8616 8617 @Override 8618 protected void onDraw(Canvas c) { 8619 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 8620 if (mPositionOnTop) { 8621 c.save(); 8622 c.rotate(180, (mRight - mLeft) / 2, (mBottom - mTop) / 2); 8623 mDrawable.draw(c); 8624 c.restore(); 8625 } else { 8626 mDrawable.draw(c); 8627 } 8628 } 8629 8630 @Override 8631 public boolean onTouchEvent(MotionEvent ev) { 8632 switch (ev.getActionMasked()) { 8633 case MotionEvent.ACTION_DOWN: { 8634 mDownPositionX = ev.getRawX(); 8635 mDownPositionY = ev.getRawY(); 8636 mTouchToWindowOffsetX = mDownPositionX - mPositionX; 8637 mTouchToWindowOffsetY = mDownPositionY - mPositionY; 8638 final int[] coords = mTempCoords; 8639 TextView.this.getLocationInWindow(coords); 8640 mLastParentX = coords[0]; 8641 mLastParentY = coords[1]; 8642 mIsDragging = true; 8643 if (mIsInsertionHandle) { 8644 mTouchTimer = SystemClock.uptimeMillis(); 8645 if (mLongPressCallback == null) { 8646 mLongPressCallback = new LongPressCallback(); 8647 } 8648 postDelayed(mLongPressCallback, ViewConfiguration.getLongPressTimeout()); 8649 } 8650 break; 8651 } 8652 8653 case MotionEvent.ACTION_MOVE: { 8654 final float rawX = ev.getRawX(); 8655 final float rawY = ev.getRawY(); 8656 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 8657 final float newPosY = rawY - mTouchToWindowOffsetY + mHotspotY + mTouchOffsetY; 8658 8659 mController.updatePosition(this, Math.round(newPosX), Math.round(newPosY)); 8660 8661 if (mIsInsertionHandle) { 8662 final float dx = rawX - mDownPositionX; 8663 final float dy = rawY - mDownPositionY; 8664 final float distanceSquared = dx * dx + dy * dy; 8665 if (distanceSquared >= mSquaredTouchSlopDistance) { 8666 removeCallbacks(mLongPressCallback); 8667 } 8668 } 8669 break; 8670 } 8671 8672 case MotionEvent.ACTION_UP: 8673 if (mIsInsertionHandle) { 8674 removeCallbacks(mLongPressCallback); 8675 long delay = SystemClock.uptimeMillis() - mTouchTimer; 8676 if (delay < ViewConfiguration.getTapTimeout()) { 8677 if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) { 8678 // Tapping on the handle dismisses the displayed paste view, 8679 mPastePopupWindow.hide(); 8680 } else { 8681 ((InsertionPointCursorController) mController).show(0); 8682 } 8683 } 8684 } 8685 mIsDragging = false; 8686 break; 8687 8688 case MotionEvent.ACTION_CANCEL: 8689 if (mIsInsertionHandle) { 8690 removeCallbacks(mLongPressCallback); 8691 } 8692 mIsDragging = false; 8693 } 8694 return true; 8695 } 8696 8697 public boolean isDragging() { 8698 return mIsDragging; 8699 } 8700 8701 void positionAtCursor(final int offset, boolean bottom) { 8702 final int width = mDrawable.getIntrinsicWidth(); 8703 final int height = mDrawable.getIntrinsicHeight(); 8704 final int line = mLayout.getLineForOffset(offset); 8705 final int lineTop = mLayout.getLineTop(line); 8706 final int lineBottom = mLayout.getLineBottom(line); 8707 8708 final Rect bounds = sCursorControllerTempRect; 8709 bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - mHotspotX) 8710 + TextView.this.mScrollX; 8711 bounds.top = (bottom ? lineBottom : lineTop - mHeight) + TextView.this.mScrollY; 8712 8713 bounds.right = bounds.left + width; 8714 bounds.bottom = bounds.top + height; 8715 8716 convertFromViewportToContentCoordinates(bounds); 8717 moveTo(bounds.left, bounds.top); 8718 } 8719 8720 void showPastePopupWindow() { 8721 if (mIsInsertionHandle) { 8722 if (mPastePopupWindow == null) { 8723 // Lazy initialisation: create when actually shown only. 8724 mPastePopupWindow = new PastePopupMenu(); 8725 } 8726 mPastePopupWindow.show(); 8727 } 8728 } 8729 } 8730 8731 private class InsertionPointCursorController implements CursorController { 8732 private static final int DELAY_BEFORE_FADE_OUT = 4100; 8733 private static final int DELAY_BEFORE_PASTE = 2000; 8734 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; 8735 8736 // The cursor controller image. Lazily created. 8737 private HandleView mHandle; 8738 8739 private final Runnable mHider = new Runnable() { 8740 public void run() { 8741 hide(); 8742 } 8743 }; 8744 8745 private final Runnable mPastePopupShower = new Runnable() { 8746 public void run() { 8747 getHandle().showPastePopupWindow(); 8748 } 8749 }; 8750 8751 public void show() { 8752 show(DELAY_BEFORE_PASTE); 8753 } 8754 8755 public void show(int delayBeforePaste) { 8756 updatePosition(); 8757 hideDelayed(); 8758 getHandle().show(); 8759 removeCallbacks(mPastePopupShower); 8760 if (canPaste()) { 8761 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 8762 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) 8763 delayBeforePaste = 0; 8764 postDelayed(mPastePopupShower, delayBeforePaste); 8765 } 8766 } 8767 8768 public void hide() { 8769 if (mHandle != null) { 8770 mHandle.hide(); 8771 } 8772 removeCallbacks(mHider); 8773 removeCallbacks(mPastePopupShower); 8774 } 8775 8776 private void hideDelayed() { 8777 removeCallbacks(mHider); 8778 postDelayed(mHider, DELAY_BEFORE_FADE_OUT); 8779 } 8780 8781 public boolean isShowing() { 8782 return mHandle != null && mHandle.isShowing(); 8783 } 8784 8785 public void updatePosition(HandleView handle, int x, int y) { 8786 final int previousOffset = getSelectionStart(); 8787 int offset = getHysteresisOffset(x, y, previousOffset); 8788 8789 if (offset != previousOffset) { 8790 Selection.setSelection((Spannable) mText, offset); 8791 updatePosition(); 8792 } 8793 hideDelayed(); 8794 } 8795 8796 public void updatePosition() { 8797 final int offset = getSelectionStart(); 8798 8799 if (offset < 0) { 8800 // Should never happen, safety check. 8801 Log.w(LOG_TAG, "Update cursor controller position called with no cursor"); 8802 hide(); 8803 return; 8804 } 8805 8806 getHandle().positionAtCursor(offset, true); 8807 } 8808 8809 public boolean onTouchEvent(MotionEvent ev) { 8810 return false; 8811 } 8812 8813 public void onTouchModeChanged(boolean isInTouchMode) { 8814 if (!isInTouchMode) { 8815 hide(); 8816 } 8817 } 8818 8819 private HandleView getHandle() { 8820 if (mHandle == null) { 8821 mHandle = new HandleView(this, HandleView.CENTER); 8822 } 8823 return mHandle; 8824 } 8825 } 8826 8827 private class SelectionModifierCursorController implements CursorController { 8828 // The cursor controller images, lazily created when shown. 8829 private HandleView mStartHandle, mEndHandle; 8830 // The offsets of that last touch down event. Remembered to start selection there. 8831 private int mMinTouchOffset, mMaxTouchOffset; 8832 // Whether selection anchors are active 8833 private boolean mIsShowing; 8834 8835 // Double tap detection 8836 private long mPreviousTapUpTime = 0; 8837 private int mPreviousTapPositionX; 8838 private int mPreviousTapPositionY; 8839 8840 SelectionModifierCursorController() { 8841 resetTouchOffsets(); 8842 } 8843 8844 public void show() { 8845 if (isInBatchEditMode()) { 8846 return; 8847 } 8848 8849 // Lazy object creation has to be done before updatePosition() is called. 8850 if (mStartHandle == null) mStartHandle = new HandleView(this, HandleView.LEFT); 8851 if (mEndHandle == null) mEndHandle = new HandleView(this, HandleView.RIGHT); 8852 8853 mIsShowing = true; 8854 updatePosition(); 8855 8856 mStartHandle.show(); 8857 mEndHandle.show(); 8858 8859 hideInsertionPointCursorController(); 8860 } 8861 8862 public void hide() { 8863 if (mStartHandle != null) mStartHandle.hide(); 8864 if (mEndHandle != null) mEndHandle.hide(); 8865 mIsShowing = false; 8866 } 8867 8868 public boolean isShowing() { 8869 return mIsShowing; 8870 } 8871 8872 public void cancelFadeOutAnimation() { 8873 hide(); 8874 } 8875 8876 public void updatePosition(HandleView handle, int x, int y) { 8877 int selectionStart = getSelectionStart(); 8878 int selectionEnd = getSelectionEnd(); 8879 8880 final int previousOffset = handle == mStartHandle ? selectionStart : selectionEnd; 8881 int offset = getHysteresisOffset(x, y, previousOffset); 8882 8883 // Handle the case where start and end are swapped, making sure start <= end 8884 if (handle == mStartHandle) { 8885 if (selectionStart == offset || offset > selectionEnd) { 8886 return; // no change, no need to redraw; 8887 } 8888 // If the user "closes" the selection entirely they were probably trying to 8889 // select a single character. Help them out. 8890 if (offset == selectionEnd) { 8891 offset = selectionEnd - 1; 8892 } 8893 selectionStart = offset; 8894 } else { 8895 if (selectionEnd == offset || offset < selectionStart) { 8896 return; // no change, no need to redraw; 8897 } 8898 // If the user "closes" the selection entirely they were probably trying to 8899 // select a single character. Help them out. 8900 if (offset == selectionStart) { 8901 offset = selectionStart + 1; 8902 } 8903 selectionEnd = offset; 8904 } 8905 8906 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8907 updatePosition(); 8908 } 8909 8910 public void updatePosition() { 8911 if (!isShowing()) { 8912 return; 8913 } 8914 8915 final int selectionStart = getSelectionStart(); 8916 final int selectionEnd = getSelectionEnd(); 8917 8918 if ((selectionStart < 0) || (selectionEnd < 0)) { 8919 // Should never happen, safety check. 8920 Log.w(LOG_TAG, "Update selection controller position called with no cursor"); 8921 hide(); 8922 return; 8923 } 8924 8925 // The handles have been created since the controller isShowing(). 8926 mStartHandle.positionAtCursor(selectionStart, true); 8927 mEndHandle.positionAtCursor(selectionEnd, true); 8928 } 8929 8930 public boolean onTouchEvent(MotionEvent event) { 8931 // This is done even when the View does not have focus, so that long presses can start 8932 // selection and tap can move cursor from this tap position. 8933 if (isTextEditable() || mTextIsSelectable) { 8934 switch (event.getActionMasked()) { 8935 case MotionEvent.ACTION_DOWN: 8936 final int x = (int) event.getX(); 8937 final int y = (int) event.getY(); 8938 8939 // Remember finger down position, to be able to start selection from there 8940 mMinTouchOffset = mMaxTouchOffset = getOffset(x, y); 8941 8942 // Double tap detection 8943 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 8944 if (duration <= ViewConfiguration.getDoubleTapTimeout() && 8945 isPositionOnText(x, y)) { 8946 final int deltaX = x - mPreviousTapPositionX; 8947 final int deltaY = y - mPreviousTapPositionY; 8948 final int distanceSquared = deltaX * deltaX + deltaY * deltaY; 8949 if (distanceSquared < mSquaredTouchSlopDistance) { 8950 startSelectionActionMode(); 8951 mDiscardNextActionUp = true; 8952 } 8953 } 8954 8955 mPreviousTapPositionX = x; 8956 mPreviousTapPositionY = y; 8957 8958 break; 8959 8960 case MotionEvent.ACTION_POINTER_DOWN: 8961 case MotionEvent.ACTION_POINTER_UP: 8962 // Handle multi-point gestures. Keep min and max offset positions. 8963 // Only activated for devices that correctly handle multi-touch. 8964 if (mContext.getPackageManager().hasSystemFeature( 8965 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 8966 updateMinAndMaxOffsets(event); 8967 } 8968 break; 8969 8970 case MotionEvent.ACTION_UP: 8971 mPreviousTapUpTime = SystemClock.uptimeMillis(); 8972 break; 8973 } 8974 } 8975 return false; 8976 } 8977 8978 /** 8979 * @param event 8980 */ 8981 private void updateMinAndMaxOffsets(MotionEvent event) { 8982 int pointerCount = event.getPointerCount(); 8983 for (int index = 0; index < pointerCount; index++) { 8984 final int x = (int) event.getX(index); 8985 final int y = (int) event.getY(index); 8986 int offset = getOffset(x, y); 8987 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 8988 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 8989 } 8990 } 8991 8992 public int getMinTouchOffset() { 8993 return mMinTouchOffset; 8994 } 8995 8996 public int getMaxTouchOffset() { 8997 return mMaxTouchOffset; 8998 } 8999 9000 public void resetTouchOffsets() { 9001 mMinTouchOffset = mMaxTouchOffset = -1; 9002 } 9003 9004 /** 9005 * @return true iff this controller is currently used to move the selection start. 9006 */ 9007 public boolean isSelectionStartDragged() { 9008 return mStartHandle != null && mStartHandle.isDragging(); 9009 } 9010 9011 public void onTouchModeChanged(boolean isInTouchMode) { 9012 if (!isInTouchMode) { 9013 hide(); 9014 } 9015 } 9016 } 9017 9018 private void hideInsertionPointCursorController() { 9019 // No need to create the controller to hide it. 9020 if (mInsertionPointCursorController != null) { 9021 mInsertionPointCursorController.hide(); 9022 } 9023 } 9024 9025 private void hideSelectionModifierCursorController() { 9026 // No need to create the controller to hide it. 9027 if (mSelectionModifierCursorController != null) { 9028 mSelectionModifierCursorController.hide(); 9029 } 9030 } 9031 9032 private void hideControllers() { 9033 hideInsertionPointCursorController(); 9034 hideSelectionModifierCursorController(); 9035 } 9036 9037 /** 9038 * Get the offset character closest to the specified absolute position. 9039 * 9040 * @param x The horizontal absolute position of a point on screen 9041 * @param y The vertical absolute position of a point on screen 9042 * @return the character offset for the character whose position is closest to the specified 9043 * position. Returns -1 if there is no layout. 9044 * 9045 * @hide 9046 */ 9047 public int getOffset(int x, int y) { 9048 if (getLayout() == null) return -1; 9049 final int line = getLineAtCoordinate(y); 9050 final int offset = getOffsetAtCoordinate(line, x); 9051 return offset; 9052 } 9053 9054 int getHysteresisOffset(int x, int y, int previousOffset) { 9055 final Layout layout = getLayout(); 9056 if (layout == null) return -1; 9057 9058 int line = getLineAtCoordinate(y); 9059 final int previousLine = layout.getLineForOffset(previousOffset); 9060 final int previousLineTop = layout.getLineTop(previousLine); 9061 final int previousLineBottom = layout.getLineBottom(previousLine); 9062 final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 8; 9063 9064 // If new line is just before or after previous line and y position is less than 9065 // hysteresisThreshold away from previous line, keep cursor on previous line. 9066 if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) || 9067 ((line == previousLine - 1) && ((previousLineTop - y) < hysteresisThreshold))) { 9068 line = previousLine; 9069 } 9070 9071 return getOffsetAtCoordinate(line, x); 9072 } 9073 9074 private int convertToLocalHorizontalCoordinate(int x) { 9075 x -= getTotalPaddingLeft(); 9076 // Clamp the position to inside of the view. 9077 x = Math.max(0, x); 9078 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 9079 x += getScrollX(); 9080 return x; 9081 } 9082 9083 private int getLineAtCoordinate(int y) { 9084 y -= getTotalPaddingTop(); 9085 // Clamp the position to inside of the view. 9086 y = Math.max(0, y); 9087 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 9088 y += getScrollY(); 9089 return getLayout().getLineForVertical(y); 9090 } 9091 9092 private int getOffsetAtCoordinate(int line, int x) { 9093 x = convertToLocalHorizontalCoordinate(x); 9094 return getLayout().getOffsetForHorizontal(line, x); 9095 } 9096 9097 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 9098 * in the view. Returns false when the position is in the empty space of left/right of text. 9099 */ 9100 private boolean isPositionOnText(int x, int y) { 9101 if (getLayout() == null) return false; 9102 9103 final int line = getLineAtCoordinate(y); 9104 x = convertToLocalHorizontalCoordinate(x); 9105 9106 if (x < getLayout().getLineLeft(line)) return false; 9107 if (x > getLayout().getLineRight(line)) return false; 9108 return true; 9109 } 9110 9111 @Override 9112 public boolean onDragEvent(DragEvent event) { 9113 switch (event.getAction()) { 9114 case DragEvent.ACTION_DRAG_STARTED: 9115 return hasInsertionController(); 9116 9117 case DragEvent.ACTION_DRAG_ENTERED: 9118 TextView.this.requestFocus(); 9119 return true; 9120 9121 case DragEvent.ACTION_DRAG_LOCATION: 9122 final int offset = getOffset((int) event.getX(), (int) event.getY()); 9123 Selection.setSelection((Spannable)mText, offset); 9124 return true; 9125 9126 case DragEvent.ACTION_DROP: 9127 onDrop(event); 9128 return true; 9129 9130 case DragEvent.ACTION_DRAG_ENDED: 9131 case DragEvent.ACTION_DRAG_EXITED: 9132 default: 9133 return true; 9134 } 9135 } 9136 9137 private void onDrop(DragEvent event) { 9138 StringBuilder content = new StringBuilder(""); 9139 ClipData clipData = event.getClipData(); 9140 final int itemCount = clipData.getItemCount(); 9141 for (int i=0; i < itemCount; i++) { 9142 Item item = clipData.getItem(i); 9143 content.append(item.coerceToText(TextView.this.mContext)); 9144 } 9145 9146 final int offset = getOffset((int) event.getX(), (int) event.getY()); 9147 9148 Object localState = event.getLocalState(); 9149 DragLocalState dragLocalState = null; 9150 if (localState instanceof DragLocalState) { 9151 dragLocalState = (DragLocalState) localState; 9152 } 9153 boolean dragDropIntoItself = dragLocalState != null && 9154 dragLocalState.sourceTextView == this; 9155 9156 if (dragDropIntoItself) { 9157 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 9158 // A drop inside the original selection discards the drop. 9159 return; 9160 } 9161 } 9162 9163 final int originalLength = mText.length(); 9164 long minMax = prepareSpacesAroundPaste(offset, offset, content); 9165 int min = extractRangeStartFromLong(minMax); 9166 int max = extractRangeEndFromLong(minMax); 9167 9168 Selection.setSelection((Spannable) mText, max); 9169 ((Editable) mText).replace(min, max, content); 9170 9171 if (dragDropIntoItself) { 9172 int dragSourceStart = dragLocalState.start; 9173 int dragSourceEnd = dragLocalState.end; 9174 if (max <= dragSourceStart) { 9175 // Inserting text before selection has shifted positions 9176 final int shift = mText.length() - originalLength; 9177 dragSourceStart += shift; 9178 dragSourceEnd += shift; 9179 } 9180 9181 // Delete original selection 9182 ((Editable) mText).delete(dragSourceStart, dragSourceEnd); 9183 9184 // Make sure we do not leave two adjacent spaces. 9185 if ((dragSourceStart == 0 || 9186 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 9187 (dragSourceStart == mText.length() || 9188 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 9189 final int pos = dragSourceStart == mText.length() ? 9190 dragSourceStart - 1 : dragSourceStart; 9191 ((Editable) mText).delete(pos, pos + 1); 9192 } 9193 } 9194 } 9195 9196 /** 9197 * @return True if this view supports insertion handles. 9198 */ 9199 boolean hasInsertionController() { 9200 return mInsertionControllerEnabled; 9201 } 9202 9203 /** 9204 * @return True if this view supports selection handles. 9205 */ 9206 boolean hasSelectionController() { 9207 return mSelectionControllerEnabled; 9208 } 9209 9210 InsertionPointCursorController getInsertionController() { 9211 if (!mInsertionControllerEnabled) { 9212 return null; 9213 } 9214 9215 if (mInsertionPointCursorController == null) { 9216 mInsertionPointCursorController = new InsertionPointCursorController(); 9217 9218 final ViewTreeObserver observer = getViewTreeObserver(); 9219 if (observer != null) { 9220 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 9221 } 9222 } 9223 9224 return mInsertionPointCursorController; 9225 } 9226 9227 SelectionModifierCursorController getSelectionController() { 9228 if (!mSelectionControllerEnabled) { 9229 return null; 9230 } 9231 9232 if (mSelectionModifierCursorController == null) { 9233 mSelectionModifierCursorController = new SelectionModifierCursorController(); 9234 9235 final ViewTreeObserver observer = getViewTreeObserver(); 9236 if (observer != null) { 9237 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 9238 } 9239 } 9240 9241 return mSelectionModifierCursorController; 9242 } 9243 9244 boolean isInBatchEditMode() { 9245 final InputMethodState ims = mInputMethodState; 9246 if (ims != null) { 9247 return ims.mBatchEditNesting > 0; 9248 } 9249 return mInBatchEditControllers; 9250 } 9251 9252 @ViewDebug.ExportedProperty(category = "text") 9253 private CharSequence mText; 9254 private CharSequence mTransformed; 9255 private BufferType mBufferType = BufferType.NORMAL; 9256 9257 private int mInputType = EditorInfo.TYPE_NULL; 9258 private CharSequence mHint; 9259 private Layout mHintLayout; 9260 9261 private KeyListener mInput; 9262 9263 private MovementMethod mMovement; 9264 private TransformationMethod mTransformation; 9265 private ChangeWatcher mChangeWatcher; 9266 9267 private ArrayList<TextWatcher> mListeners = null; 9268 9269 // display attributes 9270 private final TextPaint mTextPaint; 9271 private boolean mUserSetTextScaleX; 9272 private final Paint mHighlightPaint; 9273 private int mHighlightColor = 0xCC475925; 9274 /** 9275 * This is temporarily visible to fix bug 3085564 in webView. Do not rely on 9276 * this field being protected. Will be restored as private when lineHeight 9277 * feature request 3215097 is implemented 9278 * @hide 9279 */ 9280 protected Layout mLayout; 9281 9282 private long mShowCursor; 9283 private Blink mBlink; 9284 private boolean mCursorVisible = true; 9285 9286 // Cursor Controllers. 9287 private InsertionPointCursorController mInsertionPointCursorController; 9288 private SelectionModifierCursorController mSelectionModifierCursorController; 9289 private ActionMode mSelectionActionMode; 9290 private boolean mInsertionControllerEnabled; 9291 private boolean mSelectionControllerEnabled; 9292 private boolean mInBatchEditControllers; 9293 9294 // These are needed to desambiguate a long click. If the long click comes from ones of these, we 9295 // select from the current cursor position. Otherwise, select from long pressed position. 9296 private boolean mDPadCenterIsDown = false; 9297 private boolean mEnterKeyIsDown = false; 9298 private boolean mContextMenuTriggeredByKey = false; 9299 // Created once and shared by different CursorController helper methods. 9300 // Only one cursor controller is active at any time which prevent race conditions. 9301 private static Rect sCursorControllerTempRect = new Rect(); 9302 9303 private boolean mSelectAllOnFocus = false; 9304 9305 private int mGravity = Gravity.TOP | Gravity.LEFT; 9306 private boolean mHorizontallyScrolling; 9307 9308 private int mAutoLinkMask; 9309 private boolean mLinksClickable = true; 9310 9311 private float mSpacingMult = 1; 9312 private float mSpacingAdd = 0; 9313 private int mLineHeight = 0; 9314 private boolean mTextIsSelectable = false; 9315 9316 private static final int LINES = 1; 9317 private static final int EMS = LINES; 9318 private static final int PIXELS = 2; 9319 9320 private int mMaximum = Integer.MAX_VALUE; 9321 private int mMaxMode = LINES; 9322 private int mMinimum = 0; 9323 private int mMinMode = LINES; 9324 9325 private int mMaxWidth = Integer.MAX_VALUE; 9326 private int mMaxWidthMode = PIXELS; 9327 private int mMinWidth = 0; 9328 private int mMinWidthMode = PIXELS; 9329 9330 private boolean mSingleLine; 9331 private int mDesiredHeightAtMeasure = -1; 9332 private boolean mIncludePad = true; 9333 9334 // tmp primitives, so we don't alloc them on each draw 9335 private Path mHighlightPath; 9336 private boolean mHighlightPathBogus = true; 9337 private static final RectF sTempRect = new RectF(); 9338 9339 // XXX should be much larger 9340 private static final int VERY_WIDE = 16384; 9341 9342 private static final int BLINK = 500; 9343 9344 private static final int ANIMATED_SCROLL_GAP = 250; 9345 private long mLastScroll; 9346 private Scroller mScroller = null; 9347 9348 private BoringLayout.Metrics mBoring; 9349 private BoringLayout.Metrics mHintBoring; 9350 9351 private BoringLayout mSavedLayout, mSavedHintLayout; 9352 9353 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 9354 private InputFilter[] mFilters = NO_FILTERS; 9355 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 9356 private static int DRAG_THUMBNAIL_MAX_TEXT_LENGTH = 20; 9357 // System wide time for last cut or copy action. 9358 private static long sLastCutOrCopyTime; 9359 // Used to highlight a word when it is corrected by the IME 9360 private CorrectionHighlighter mCorrectionHighlighter; 9361} 9362