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