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