TextView.java revision 770a681b2f5b00e699920317bff04a24676ae143
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.ArrowKeyMovementMethod; 67import android.text.method.DateKeyListener; 68import android.text.method.DateTimeKeyListener; 69import android.text.method.DialerKeyListener; 70import android.text.method.DigitsKeyListener; 71import android.text.method.KeyListener; 72import android.text.method.LinkMovementMethod; 73import android.text.method.MetaKeyKeyListener; 74import android.text.method.MovementMethod; 75import android.text.method.PasswordTransformationMethod; 76import android.text.method.SingleLineTransformationMethod; 77import android.text.method.TextKeyListener; 78import android.text.method.TimeKeyListener; 79import android.text.method.TransformationMethod; 80import android.text.style.ParagraphStyle; 81import android.text.style.URLSpan; 82import android.text.style.UpdateAppearance; 83import android.text.util.Linkify; 84import android.util.AttributeSet; 85import android.util.FloatMath; 86import android.util.Log; 87import android.util.TypedValue; 88import android.view.ContextMenu; 89import android.view.Gravity; 90import android.view.KeyEvent; 91import android.view.LayoutInflater; 92import android.view.MenuItem; 93import android.view.MotionEvent; 94import android.view.View; 95import android.view.ViewConfiguration; 96import android.view.ViewDebug; 97import android.view.ViewGroup.LayoutParams; 98import android.view.ViewRoot; 99import android.view.ViewTreeObserver; 100import android.view.accessibility.AccessibilityEvent; 101import android.view.accessibility.AccessibilityManager; 102import android.view.animation.AnimationUtils; 103import android.view.inputmethod.BaseInputConnection; 104import android.view.inputmethod.CompletionInfo; 105import android.view.inputmethod.EditorInfo; 106import android.view.inputmethod.ExtractedText; 107import android.view.inputmethod.ExtractedTextRequest; 108import android.view.inputmethod.InputConnection; 109import android.view.inputmethod.InputMethodManager; 110import android.widget.RemoteViews.RemoteView; 111 112import java.io.IOException; 113import java.lang.ref.WeakReference; 114import java.util.ArrayList; 115 116/** 117 * Displays text to the user and optionally allows them to edit it. A TextView 118 * is a complete text editor, however the basic class is configured to not 119 * allow editing; see {@link EditText} for a subclass that configures the text 120 * view for editing. 121 * 122 * <p> 123 * <b>XML attributes</b> 124 * <p> 125 * See {@link android.R.styleable#TextView TextView Attributes}, 126 * {@link android.R.styleable#View View Attributes} 127 * 128 * @attr ref android.R.styleable#TextView_text 129 * @attr ref android.R.styleable#TextView_bufferType 130 * @attr ref android.R.styleable#TextView_hint 131 * @attr ref android.R.styleable#TextView_textColor 132 * @attr ref android.R.styleable#TextView_textColorHighlight 133 * @attr ref android.R.styleable#TextView_textColorHint 134 * @attr ref android.R.styleable#TextView_textAppearance 135 * @attr ref android.R.styleable#TextView_textColorLink 136 * @attr ref android.R.styleable#TextView_textSize 137 * @attr ref android.R.styleable#TextView_textScaleX 138 * @attr ref android.R.styleable#TextView_typeface 139 * @attr ref android.R.styleable#TextView_textStyle 140 * @attr ref android.R.styleable#TextView_cursorVisible 141 * @attr ref android.R.styleable#TextView_maxLines 142 * @attr ref android.R.styleable#TextView_maxHeight 143 * @attr ref android.R.styleable#TextView_lines 144 * @attr ref android.R.styleable#TextView_height 145 * @attr ref android.R.styleable#TextView_minLines 146 * @attr ref android.R.styleable#TextView_minHeight 147 * @attr ref android.R.styleable#TextView_maxEms 148 * @attr ref android.R.styleable#TextView_maxWidth 149 * @attr ref android.R.styleable#TextView_ems 150 * @attr ref android.R.styleable#TextView_width 151 * @attr ref android.R.styleable#TextView_minEms 152 * @attr ref android.R.styleable#TextView_minWidth 153 * @attr ref android.R.styleable#TextView_gravity 154 * @attr ref android.R.styleable#TextView_scrollHorizontally 155 * @attr ref android.R.styleable#TextView_password 156 * @attr ref android.R.styleable#TextView_singleLine 157 * @attr ref android.R.styleable#TextView_selectAllOnFocus 158 * @attr ref android.R.styleable#TextView_includeFontPadding 159 * @attr ref android.R.styleable#TextView_maxLength 160 * @attr ref android.R.styleable#TextView_shadowColor 161 * @attr ref android.R.styleable#TextView_shadowDx 162 * @attr ref android.R.styleable#TextView_shadowDy 163 * @attr ref android.R.styleable#TextView_shadowRadius 164 * @attr ref android.R.styleable#TextView_autoLink 165 * @attr ref android.R.styleable#TextView_linksClickable 166 * @attr ref android.R.styleable#TextView_numeric 167 * @attr ref android.R.styleable#TextView_digits 168 * @attr ref android.R.styleable#TextView_phoneNumber 169 * @attr ref android.R.styleable#TextView_inputMethod 170 * @attr ref android.R.styleable#TextView_capitalize 171 * @attr ref android.R.styleable#TextView_autoText 172 * @attr ref android.R.styleable#TextView_editable 173 * @attr ref android.R.styleable#TextView_freezesText 174 * @attr ref android.R.styleable#TextView_ellipsize 175 * @attr ref android.R.styleable#TextView_drawableTop 176 * @attr ref android.R.styleable#TextView_drawableBottom 177 * @attr ref android.R.styleable#TextView_drawableRight 178 * @attr ref android.R.styleable#TextView_drawableLeft 179 * @attr ref android.R.styleable#TextView_drawablePadding 180 * @attr ref android.R.styleable#TextView_lineSpacingExtra 181 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 182 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 183 * @attr ref android.R.styleable#TextView_inputType 184 * @attr ref android.R.styleable#TextView_imeOptions 185 * @attr ref android.R.styleable#TextView_privateImeOptions 186 * @attr ref android.R.styleable#TextView_imeActionLabel 187 * @attr ref android.R.styleable#TextView_imeActionId 188 * @attr ref android.R.styleable#TextView_editorExtras 189 */ 190@RemoteView 191public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { 192 static final String LOG_TAG = "TextView"; 193 static final boolean DEBUG_EXTRACT = false; 194 195 private static int PRIORITY = 100; 196 197 private final int[] mTempCoords = new int[2]; 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 canSelectText, 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 canSelectText, 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 3756 @Override 3757 protected void onDetachedFromWindow() { 3758 super.onDetachedFromWindow(); 3759 3760 if (mPreDrawState != PREDRAW_NOT_REGISTERED) { 3761 final ViewTreeObserver observer = getViewTreeObserver(); 3762 if (observer != null) { 3763 observer.removeOnPreDrawListener(this); 3764 mPreDrawState = PREDRAW_NOT_REGISTERED; 3765 } 3766 } 3767 3768 if (mError != null) { 3769 hideError(); 3770 } 3771 } 3772 3773 @Override 3774 protected boolean isPaddingOffsetRequired() { 3775 return mShadowRadius != 0 || mDrawables != null; 3776 } 3777 3778 @Override 3779 protected int getLeftPaddingOffset() { 3780 return getCompoundPaddingLeft() - mPaddingLeft + 3781 (int) Math.min(0, mShadowDx - mShadowRadius); 3782 } 3783 3784 @Override 3785 protected int getTopPaddingOffset() { 3786 return (int) Math.min(0, mShadowDy - mShadowRadius); 3787 } 3788 3789 @Override 3790 protected int getBottomPaddingOffset() { 3791 return (int) Math.max(0, mShadowDy + mShadowRadius); 3792 } 3793 3794 @Override 3795 protected int getRightPaddingOffset() { 3796 return -(getCompoundPaddingRight() - mPaddingRight) + 3797 (int) Math.max(0, mShadowDx + mShadowRadius); 3798 } 3799 3800 @Override 3801 protected boolean verifyDrawable(Drawable who) { 3802 final boolean verified = super.verifyDrawable(who); 3803 if (!verified && mDrawables != null) { 3804 return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || 3805 who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom; 3806 } 3807 return verified; 3808 } 3809 3810 @Override 3811 public void invalidateDrawable(Drawable drawable) { 3812 if (verifyDrawable(drawable)) { 3813 final Rect dirty = drawable.getBounds(); 3814 int scrollX = mScrollX; 3815 int scrollY = mScrollY; 3816 3817 // IMPORTANT: The coordinates below are based on the coordinates computed 3818 // for each compound drawable in onDraw(). Make sure to update each section 3819 // accordingly. 3820 final TextView.Drawables drawables = mDrawables; 3821 if (drawables != null) { 3822 if (drawable == drawables.mDrawableLeft) { 3823 final int compoundPaddingTop = getCompoundPaddingTop(); 3824 final int compoundPaddingBottom = getCompoundPaddingBottom(); 3825 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 3826 3827 scrollX += mPaddingLeft; 3828 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 3829 } else if (drawable == drawables.mDrawableRight) { 3830 final int compoundPaddingTop = getCompoundPaddingTop(); 3831 final int compoundPaddingBottom = getCompoundPaddingBottom(); 3832 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 3833 3834 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 3835 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 3836 } else if (drawable == drawables.mDrawableTop) { 3837 final int compoundPaddingLeft = getCompoundPaddingLeft(); 3838 final int compoundPaddingRight = getCompoundPaddingRight(); 3839 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 3840 3841 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 3842 scrollY += mPaddingTop; 3843 } else if (drawable == drawables.mDrawableBottom) { 3844 final int compoundPaddingLeft = getCompoundPaddingLeft(); 3845 final int compoundPaddingRight = getCompoundPaddingRight(); 3846 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 3847 3848 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 3849 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 3850 } 3851 } 3852 3853 invalidate(dirty.left + scrollX, dirty.top + scrollY, 3854 dirty.right + scrollX, dirty.bottom + scrollY); 3855 } 3856 } 3857 3858 @Override 3859 protected void onDraw(Canvas canvas) { 3860 restartMarqueeIfNeeded(); 3861 3862 // Draw the background for this view 3863 super.onDraw(canvas); 3864 3865 final int compoundPaddingLeft = getCompoundPaddingLeft(); 3866 final int compoundPaddingTop = getCompoundPaddingTop(); 3867 final int compoundPaddingRight = getCompoundPaddingRight(); 3868 final int compoundPaddingBottom = getCompoundPaddingBottom(); 3869 final int scrollX = mScrollX; 3870 final int scrollY = mScrollY; 3871 final int right = mRight; 3872 final int left = mLeft; 3873 final int bottom = mBottom; 3874 final int top = mTop; 3875 3876 final Drawables dr = mDrawables; 3877 if (dr != null) { 3878 /* 3879 * Compound, not extended, because the icon is not clipped 3880 * if the text height is smaller. 3881 */ 3882 3883 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 3884 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 3885 3886 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 3887 // Make sure to update invalidateDrawable() when changing this code. 3888 if (dr.mDrawableLeft != null) { 3889 canvas.save(); 3890 canvas.translate(scrollX + mPaddingLeft, 3891 scrollY + compoundPaddingTop + 3892 (vspace - dr.mDrawableHeightLeft) / 2); 3893 dr.mDrawableLeft.draw(canvas); 3894 canvas.restore(); 3895 } 3896 3897 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 3898 // Make sure to update invalidateDrawable() when changing this code. 3899 if (dr.mDrawableRight != null) { 3900 canvas.save(); 3901 canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight, 3902 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 3903 dr.mDrawableRight.draw(canvas); 3904 canvas.restore(); 3905 } 3906 3907 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 3908 // Make sure to update invalidateDrawable() when changing this code. 3909 if (dr.mDrawableTop != null) { 3910 canvas.save(); 3911 canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, 3912 scrollY + mPaddingTop); 3913 dr.mDrawableTop.draw(canvas); 3914 canvas.restore(); 3915 } 3916 3917 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 3918 // Make sure to update invalidateDrawable() when changing this code. 3919 if (dr.mDrawableBottom != null) { 3920 canvas.save(); 3921 canvas.translate(scrollX + compoundPaddingLeft + 3922 (hspace - dr.mDrawableWidthBottom) / 2, 3923 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 3924 dr.mDrawableBottom.draw(canvas); 3925 canvas.restore(); 3926 } 3927 } 3928 3929 if (mPreDrawState == PREDRAW_DONE) { 3930 final ViewTreeObserver observer = getViewTreeObserver(); 3931 if (observer != null) { 3932 observer.removeOnPreDrawListener(this); 3933 mPreDrawState = PREDRAW_NOT_REGISTERED; 3934 } 3935 } 3936 3937 int color = mCurTextColor; 3938 3939 if (mLayout == null) { 3940 assumeLayout(); 3941 } 3942 3943 Layout layout = mLayout; 3944 int cursorcolor = color; 3945 3946 if (mHint != null && mText.length() == 0) { 3947 if (mHintTextColor != null) { 3948 color = mCurHintTextColor; 3949 } 3950 3951 layout = mHintLayout; 3952 } 3953 3954 mTextPaint.setColor(color); 3955 mTextPaint.drawableState = getDrawableState(); 3956 3957 canvas.save(); 3958 /* Would be faster if we didn't have to do this. Can we chop the 3959 (displayable) text so that we don't need to do this ever? 3960 */ 3961 3962 int extendedPaddingTop = getExtendedPaddingTop(); 3963 int extendedPaddingBottom = getExtendedPaddingBottom(); 3964 3965 float clipLeft = compoundPaddingLeft + scrollX; 3966 float clipTop = extendedPaddingTop + scrollY; 3967 float clipRight = right - left - compoundPaddingRight + scrollX; 3968 float clipBottom = bottom - top - extendedPaddingBottom + scrollY; 3969 3970 if (mShadowRadius != 0) { 3971 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 3972 clipRight += Math.max(0, mShadowDx + mShadowRadius); 3973 3974 clipTop += Math.min(0, mShadowDy - mShadowRadius); 3975 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 3976 } 3977 3978 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 3979 3980 int voffsetText = 0; 3981 int voffsetCursor = 0; 3982 3983 // translate in by our padding 3984 { 3985 /* shortcircuit calling getVerticaOffset() */ 3986 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 3987 voffsetText = getVerticalOffset(false); 3988 voffsetCursor = getVerticalOffset(true); 3989 } 3990 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 3991 } 3992 3993 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 3994 if (!mSingleLine && getLineCount() == 1 && canMarquee() && 3995 (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 3996 canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft - 3997 getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f); 3998 } 3999 4000 if (mMarquee != null && mMarquee.isRunning()) { 4001 canvas.translate(-mMarquee.mScroll, 0.0f); 4002 } 4003 } 4004 4005 Path highlight = null; 4006 int selStart = -1, selEnd = -1; 4007 4008 // If there is no movement method, then there can be no selection. 4009 // Check that first and attempt to skip everything having to do with 4010 // the cursor. 4011 // XXX This is not strictly true -- a program could set the 4012 // selection manually if it really wanted to. 4013 if (mMovement != null && (isFocused() || isPressed())) { 4014 selStart = getSelectionStart(); 4015 selEnd = getSelectionEnd(); 4016 4017 if (mCursorVisible && selStart >= 0 && isEnabled()) { 4018 if (mHighlightPath == null) 4019 mHighlightPath = new Path(); 4020 4021 if (selStart == selEnd) { 4022 if ((SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) { 4023 if (mHighlightPathBogus) { 4024 mHighlightPath.reset(); 4025 mLayout.getCursorPath(selStart, mHighlightPath, mText); 4026 mHighlightPathBogus = false; 4027 } 4028 4029 // XXX should pass to skin instead of drawing directly 4030 mHighlightPaint.setColor(cursorcolor); 4031 mHighlightPaint.setStyle(Paint.Style.STROKE); 4032 4033 highlight = mHighlightPath; 4034 } 4035 } else { 4036 if (mHighlightPathBogus) { 4037 mHighlightPath.reset(); 4038 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 4039 mHighlightPathBogus = false; 4040 } 4041 4042 // XXX should pass to skin instead of drawing directly 4043 mHighlightPaint.setColor(mHighlightColor); 4044 mHighlightPaint.setStyle(Paint.Style.FILL); 4045 4046 highlight = mHighlightPath; 4047 } 4048 } 4049 } 4050 4051 /* Comment out until we decide what to do about animations 4052 boolean isLinearTextOn = false; 4053 if (currentTransformation != null) { 4054 isLinearTextOn = mTextPaint.isLinearTextOn(); 4055 Matrix m = currentTransformation.getMatrix(); 4056 if (!m.isIdentity()) { 4057 // mTextPaint.setLinearTextOn(true); 4058 } 4059 } 4060 */ 4061 4062 final InputMethodState ims = mInputMethodState; 4063 if (ims != null && ims.mBatchEditNesting == 0) { 4064 InputMethodManager imm = InputMethodManager.peekInstance(); 4065 if (imm != null) { 4066 if (imm.isActive(this)) { 4067 boolean reported = false; 4068 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4069 // We are in extract mode and the content has changed 4070 // in some way... just report complete new text to the 4071 // input method. 4072 reported = reportExtractedText(); 4073 } 4074 if (!reported && highlight != null) { 4075 int candStart = -1; 4076 int candEnd = -1; 4077 if (mText instanceof Spannable) { 4078 Spannable sp = (Spannable)mText; 4079 candStart = EditableInputConnection.getComposingSpanStart(sp); 4080 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 4081 } 4082 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 4083 } 4084 } 4085 4086 if (imm.isWatchingCursor(this) && highlight != null) { 4087 highlight.computeBounds(ims.mTmpRectF, true); 4088 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 4089 4090 canvas.getMatrix().mapPoints(ims.mTmpOffset); 4091 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 4092 4093 ims.mTmpRectF.offset(0, voffsetCursor - voffsetText); 4094 4095 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 4096 (int)(ims.mTmpRectF.top + 0.5), 4097 (int)(ims.mTmpRectF.right + 0.5), 4098 (int)(ims.mTmpRectF.bottom + 0.5)); 4099 4100 imm.updateCursor(this, 4101 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 4102 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 4103 } 4104 } 4105 } 4106 4107 layout.draw(canvas, highlight, mHighlightPaint, voffsetCursor - voffsetText); 4108 4109 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 4110 canvas.translate((int) mMarquee.getGhostOffset(), 0.0f); 4111 layout.draw(canvas, highlight, mHighlightPaint, voffsetCursor - voffsetText); 4112 } 4113 4114 /* Comment out until we decide what to do about animations 4115 if (currentTransformation != null) { 4116 mTextPaint.setLinearTextOn(isLinearTextOn); 4117 } 4118 */ 4119 4120 canvas.restore(); 4121 } 4122 4123 @Override 4124 public void getFocusedRect(Rect r) { 4125 if (mLayout == null) { 4126 super.getFocusedRect(r); 4127 return; 4128 } 4129 4130 int sel = getSelectionEnd(); 4131 if (sel < 0) { 4132 super.getFocusedRect(r); 4133 return; 4134 } 4135 4136 int line = mLayout.getLineForOffset(sel); 4137 r.top = mLayout.getLineTop(line); 4138 r.bottom = mLayout.getLineBottom(line); 4139 4140 r.left = (int) mLayout.getPrimaryHorizontal(sel); 4141 r.right = r.left + 1; 4142 4143 // Adjust for padding and gravity. 4144 int paddingLeft = getCompoundPaddingLeft(); 4145 int paddingTop = getExtendedPaddingTop(); 4146 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4147 paddingTop += getVerticalOffset(false); 4148 } 4149 r.offset(paddingLeft, paddingTop); 4150 } 4151 4152 /** 4153 * Return the number of lines of text, or 0 if the internal Layout has not 4154 * been built. 4155 */ 4156 public int getLineCount() { 4157 return mLayout != null ? mLayout.getLineCount() : 0; 4158 } 4159 4160 /** 4161 * Return the baseline for the specified line (0...getLineCount() - 1) 4162 * If bounds is not null, return the top, left, right, bottom extents 4163 * of the specified line in it. If the internal Layout has not been built, 4164 * return 0 and set bounds to (0, 0, 0, 0) 4165 * @param line which line to examine (0..getLineCount() - 1) 4166 * @param bounds Optional. If not null, it returns the extent of the line 4167 * @return the Y-coordinate of the baseline 4168 */ 4169 public int getLineBounds(int line, Rect bounds) { 4170 if (mLayout == null) { 4171 if (bounds != null) { 4172 bounds.set(0, 0, 0, 0); 4173 } 4174 return 0; 4175 } 4176 else { 4177 int baseline = mLayout.getLineBounds(line, bounds); 4178 4179 int voffset = getExtendedPaddingTop(); 4180 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4181 voffset += getVerticalOffset(true); 4182 } 4183 if (bounds != null) { 4184 bounds.offset(getCompoundPaddingLeft(), voffset); 4185 } 4186 return baseline + voffset; 4187 } 4188 } 4189 4190 @Override 4191 public int getBaseline() { 4192 if (mLayout == null) { 4193 return super.getBaseline(); 4194 } 4195 4196 int voffset = 0; 4197 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4198 voffset = getVerticalOffset(true); 4199 } 4200 4201 return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); 4202 } 4203 4204 @Override 4205 public boolean onKeyDown(int keyCode, KeyEvent event) { 4206 int which = doKeyDown(keyCode, event, null); 4207 if (which == 0) { 4208 // Go through default dispatching. 4209 return super.onKeyDown(keyCode, event); 4210 } 4211 4212 return true; 4213 } 4214 4215 @Override 4216 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4217 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 4218 4219 int which = doKeyDown(keyCode, down, event); 4220 if (which == 0) { 4221 // Go through default dispatching. 4222 return super.onKeyMultiple(keyCode, repeatCount, event); 4223 } 4224 if (which == -1) { 4225 // Consumed the whole thing. 4226 return true; 4227 } 4228 4229 repeatCount--; 4230 4231 // We are going to dispatch the remaining events to either the input 4232 // or movement method. To do this, we will just send a repeated stream 4233 // of down and up events until we have done the complete repeatCount. 4234 // It would be nice if those interfaces had an onKeyMultiple() method, 4235 // but adding that is a more complicated change. 4236 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 4237 if (which == 1) { 4238 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4239 while (--repeatCount > 0) { 4240 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 4241 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4242 } 4243 if (mError != null && !mErrorWasChanged) { 4244 setError(null, null); 4245 } 4246 4247 } else if (which == 2) { 4248 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4249 while (--repeatCount > 0) { 4250 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 4251 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4252 } 4253 } 4254 4255 return true; 4256 } 4257 4258 /** 4259 * Returns true if pressing ENTER in this field advances focus instead 4260 * of inserting the character. This is true mostly in single-line fields, 4261 * but also in mail addresses and subjects which will display on multiple 4262 * lines but where it doesn't make sense to insert newlines. 4263 */ 4264 private boolean shouldAdvanceFocusOnEnter() { 4265 if (mInput == null) { 4266 return false; 4267 } 4268 4269 if (mSingleLine) { 4270 return true; 4271 } 4272 4273 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 4274 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 4275 4276 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 4277 variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 4278 return true; 4279 } 4280 } 4281 4282 return false; 4283 } 4284 4285 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 4286 if (!isEnabled()) { 4287 return 0; 4288 } 4289 4290 switch (keyCode) { 4291 case KeyEvent.KEYCODE_ENTER: 4292 // If ALT modifier is held, then we always insert a 4293 // newline character. 4294 if ((event.getMetaState()&KeyEvent.META_ALT_ON) == 0) { 4295 4296 // When mInputContentType is set, we know that we are 4297 // running in a "modern" cupcake environment, so don't need 4298 // to worry about the application trying to capture 4299 // enter key events. 4300 if (mInputContentType != null) { 4301 4302 // If there is an action listener, given them a 4303 // chance to consume the event. 4304 if (mInputContentType.onEditorActionListener != null && 4305 mInputContentType.onEditorActionListener.onEditorAction( 4306 this, EditorInfo.IME_NULL, event)) { 4307 mInputContentType.enterDown = true; 4308 // We are consuming the enter key for them. 4309 return -1; 4310 } 4311 } 4312 4313 // If our editor should move focus when enter is pressed, or 4314 // this is a generated event from an IME action button, then 4315 // don't let it be inserted into the text. 4316 if ((event.getFlags()&KeyEvent.FLAG_EDITOR_ACTION) != 0 4317 || shouldAdvanceFocusOnEnter()) { 4318 return -1; 4319 } 4320 } 4321 break; 4322 4323 case KeyEvent.KEYCODE_DPAD_CENTER: 4324 if (shouldAdvanceFocusOnEnter()) { 4325 return 0; 4326 } 4327 break; 4328 4329 // Has to be done on key down (and not on key up) to correctly be intercepted. 4330 case KeyEvent.KEYCODE_BACK: 4331 if (mIsInTextSelectionMode) { 4332 stopTextSelectionMode(); 4333 return -1; 4334 } 4335 break; 4336 } 4337 4338 if (mInput != null) { 4339 /* 4340 * Keep track of what the error was before doing the input 4341 * so that if an input filter changed the error, we leave 4342 * that error showing. Otherwise, we take down whatever 4343 * error was showing when the user types something. 4344 */ 4345 mErrorWasChanged = false; 4346 4347 boolean doDown = true; 4348 if (otherEvent != null) { 4349 try { 4350 beginBatchEdit(); 4351 boolean handled = mInput.onKeyOther(this, (Editable) mText, 4352 otherEvent); 4353 if (mError != null && !mErrorWasChanged) { 4354 setError(null, null); 4355 } 4356 doDown = false; 4357 if (handled) { 4358 return -1; 4359 } 4360 } catch (AbstractMethodError e) { 4361 // onKeyOther was added after 1.0, so if it isn't 4362 // implemented we need to try to dispatch as a regular down. 4363 } finally { 4364 endBatchEdit(); 4365 } 4366 } 4367 4368 if (doDown) { 4369 beginBatchEdit(); 4370 if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) { 4371 endBatchEdit(); 4372 if (mError != null && !mErrorWasChanged) { 4373 setError(null, null); 4374 } 4375 return 1; 4376 } 4377 endBatchEdit(); 4378 } 4379 } 4380 4381 // bug 650865: sometimes we get a key event before a layout. 4382 // don't try to move around if we don't know the layout. 4383 4384 if (mMovement != null && mLayout != null) { 4385 boolean doDown = true; 4386 if (otherEvent != null) { 4387 try { 4388 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 4389 otherEvent); 4390 doDown = false; 4391 if (handled) { 4392 return -1; 4393 } 4394 } catch (AbstractMethodError e) { 4395 // onKeyOther was added after 1.0, so if it isn't 4396 // implemented we need to try to dispatch as a regular down. 4397 } 4398 } 4399 if (doDown) { 4400 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 4401 return 2; 4402 } 4403 } 4404 4405 return 0; 4406 } 4407 4408 @Override 4409 public boolean onKeyUp(int keyCode, KeyEvent event) { 4410 if (!isEnabled()) { 4411 return super.onKeyUp(keyCode, event); 4412 } 4413 4414 hideControllers(); 4415 4416 switch (keyCode) { 4417 case KeyEvent.KEYCODE_DPAD_CENTER: 4418 /* 4419 * If there is a click listener, just call through to 4420 * super, which will invoke it. 4421 * 4422 * If there isn't a click listener, try to show the soft 4423 * input method. (It will also 4424 * call performClick(), but that won't do anything in 4425 * this case.) 4426 */ 4427 if (mOnClickListener == null) { 4428 if (mMovement != null && mText instanceof Editable 4429 && mLayout != null && onCheckIsTextEditor()) { 4430 InputMethodManager imm = (InputMethodManager) 4431 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 4432 imm.showSoftInput(this, 0); 4433 } 4434 } 4435 return super.onKeyUp(keyCode, event); 4436 4437 case KeyEvent.KEYCODE_ENTER: 4438 if (mInputContentType != null 4439 && mInputContentType.onEditorActionListener != null 4440 && mInputContentType.enterDown) { 4441 mInputContentType.enterDown = false; 4442 if (mInputContentType.onEditorActionListener.onEditorAction( 4443 this, EditorInfo.IME_NULL, event)) { 4444 return true; 4445 } 4446 } 4447 4448 if ((event.getFlags()&KeyEvent.FLAG_EDITOR_ACTION) != 0 4449 || shouldAdvanceFocusOnEnter()) { 4450 /* 4451 * If there is a click listener, just call through to 4452 * super, which will invoke it. 4453 * 4454 * If there isn't a click listener, try to advance focus, 4455 * but still call through to super, which will reset the 4456 * pressed state and longpress state. (It will also 4457 * call performClick(), but that won't do anything in 4458 * this case.) 4459 */ 4460 if (mOnClickListener == null) { 4461 View v = focusSearch(FOCUS_DOWN); 4462 4463 if (v != null) { 4464 if (!v.requestFocus(FOCUS_DOWN)) { 4465 throw new IllegalStateException("focus search returned a view " + 4466 "that wasn't able to take focus!"); 4467 } 4468 4469 /* 4470 * Return true because we handled the key; super 4471 * will return false because there was no click 4472 * listener. 4473 */ 4474 super.onKeyUp(keyCode, event); 4475 return true; 4476 } else if ((event.getFlags() 4477 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 4478 // No target for next focus, but make sure the IME 4479 // if this came from it. 4480 InputMethodManager imm = InputMethodManager.peekInstance(); 4481 if (imm != null) { 4482 imm.hideSoftInputFromWindow(getWindowToken(), 0); 4483 } 4484 } 4485 } 4486 4487 return super.onKeyUp(keyCode, event); 4488 } 4489 break; 4490 } 4491 4492 if (mInput != null) 4493 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 4494 return true; 4495 4496 if (mMovement != null && mLayout != null) 4497 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 4498 return true; 4499 4500 return super.onKeyUp(keyCode, event); 4501 } 4502 4503 @Override public boolean onCheckIsTextEditor() { 4504 return mInputType != EditorInfo.TYPE_NULL; 4505 } 4506 4507 @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 4508 if (onCheckIsTextEditor()) { 4509 if (mInputMethodState == null) { 4510 mInputMethodState = new InputMethodState(); 4511 } 4512 outAttrs.inputType = mInputType; 4513 if (mInputContentType != null) { 4514 outAttrs.imeOptions = mInputContentType.imeOptions; 4515 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 4516 outAttrs.actionLabel = mInputContentType.imeActionLabel; 4517 outAttrs.actionId = mInputContentType.imeActionId; 4518 outAttrs.extras = mInputContentType.extras; 4519 } else { 4520 outAttrs.imeOptions = EditorInfo.IME_NULL; 4521 } 4522 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 4523 == EditorInfo.IME_ACTION_UNSPECIFIED) { 4524 if (focusSearch(FOCUS_DOWN) != null) { 4525 // An action has not been set, but the enter key will move to 4526 // the next focus, so set the action to that. 4527 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 4528 } else { 4529 // An action has not been set, and there is no focus to move 4530 // to, so let's just supply a "done" action. 4531 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 4532 } 4533 if (!shouldAdvanceFocusOnEnter()) { 4534 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 4535 } 4536 } 4537 if ((outAttrs.inputType & (InputType.TYPE_MASK_CLASS 4538 | InputType.TYPE_TEXT_FLAG_MULTI_LINE)) 4539 == (InputType.TYPE_CLASS_TEXT 4540 | InputType.TYPE_TEXT_FLAG_MULTI_LINE)) { 4541 // Multi-line text editors should always show an enter key. 4542 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 4543 } 4544 outAttrs.hintText = mHint; 4545 if (mText instanceof Editable) { 4546 InputConnection ic = new EditableInputConnection(this); 4547 outAttrs.initialSelStart = getSelectionStart(); 4548 outAttrs.initialSelEnd = getSelectionEnd(); 4549 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 4550 return ic; 4551 } 4552 } 4553 return null; 4554 } 4555 4556 /** 4557 * If this TextView contains editable content, extract a portion of it 4558 * based on the information in <var>request</var> in to <var>outText</var>. 4559 * @return Returns true if the text was successfully extracted, else false. 4560 */ 4561 public boolean extractText(ExtractedTextRequest request, 4562 ExtractedText outText) { 4563 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 4564 EXTRACT_UNKNOWN, outText); 4565 } 4566 4567 static final int EXTRACT_NOTHING = -2; 4568 static final int EXTRACT_UNKNOWN = -1; 4569 4570 boolean extractTextInternal(ExtractedTextRequest request, 4571 int partialStartOffset, int partialEndOffset, int delta, 4572 ExtractedText outText) { 4573 final CharSequence content = mText; 4574 if (content != null) { 4575 if (partialStartOffset != EXTRACT_NOTHING) { 4576 final int N = content.length(); 4577 if (partialStartOffset < 0) { 4578 outText.partialStartOffset = outText.partialEndOffset = -1; 4579 partialStartOffset = 0; 4580 partialEndOffset = N; 4581 } else { 4582 // Now use the delta to determine the actual amount of text 4583 // we need. 4584 partialEndOffset += delta; 4585 // Adjust offsets to ensure we contain full spans. 4586 if (content instanceof Spanned) { 4587 Spanned spanned = (Spanned)content; 4588 Object[] spans = spanned.getSpans(partialStartOffset, 4589 partialEndOffset, ParcelableSpan.class); 4590 int i = spans.length; 4591 while (i > 0) { 4592 i--; 4593 int j = spanned.getSpanStart(spans[i]); 4594 if (j < partialStartOffset) partialStartOffset = j; 4595 j = spanned.getSpanEnd(spans[i]); 4596 if (j > partialEndOffset) partialEndOffset = j; 4597 } 4598 } 4599 outText.partialStartOffset = partialStartOffset; 4600 outText.partialEndOffset = partialEndOffset - delta; 4601 4602 if (partialStartOffset > N) { 4603 partialStartOffset = N; 4604 } else if (partialStartOffset < 0) { 4605 partialStartOffset = 0; 4606 } 4607 if (partialEndOffset > N) { 4608 partialEndOffset = N; 4609 } else if (partialEndOffset < 0) { 4610 partialEndOffset = 0; 4611 } 4612 } 4613 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 4614 outText.text = content.subSequence(partialStartOffset, 4615 partialEndOffset); 4616 } else { 4617 outText.text = TextUtils.substring(content, partialStartOffset, 4618 partialEndOffset); 4619 } 4620 } else { 4621 outText.partialStartOffset = 0; 4622 outText.partialEndOffset = 0; 4623 outText.text = ""; 4624 } 4625 outText.flags = 0; 4626 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 4627 outText.flags |= ExtractedText.FLAG_SELECTING; 4628 } 4629 if (mSingleLine) { 4630 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 4631 } 4632 outText.startOffset = 0; 4633 outText.selectionStart = getSelectionStart(); 4634 outText.selectionEnd = getSelectionEnd(); 4635 return true; 4636 } 4637 return false; 4638 } 4639 4640 boolean reportExtractedText() { 4641 final InputMethodState ims = mInputMethodState; 4642 if (ims != null) { 4643 final boolean contentChanged = ims.mContentChanged; 4644 if (contentChanged || ims.mSelectionModeChanged) { 4645 ims.mContentChanged = false; 4646 ims.mSelectionModeChanged = false; 4647 final ExtractedTextRequest req = mInputMethodState.mExtracting; 4648 if (req != null) { 4649 InputMethodManager imm = InputMethodManager.peekInstance(); 4650 if (imm != null) { 4651 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 4652 + ims.mChangedStart + " end=" + ims.mChangedEnd 4653 + " delta=" + ims.mChangedDelta); 4654 if (ims.mChangedStart < 0 && !contentChanged) { 4655 ims.mChangedStart = EXTRACT_NOTHING; 4656 } 4657 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 4658 ims.mChangedDelta, ims.mTmpExtracted)) { 4659 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 4660 + ims.mTmpExtracted.partialStartOffset 4661 + " end=" + ims.mTmpExtracted.partialEndOffset 4662 + ": " + ims.mTmpExtracted.text); 4663 imm.updateExtractedText(this, req.token, 4664 mInputMethodState.mTmpExtracted); 4665 ims.mChangedStart = EXTRACT_UNKNOWN; 4666 ims.mChangedEnd = EXTRACT_UNKNOWN; 4667 ims.mChangedDelta = 0; 4668 ims.mContentChanged = false; 4669 return true; 4670 } 4671 } 4672 } 4673 } 4674 } 4675 return false; 4676 } 4677 4678 /** 4679 * This is used to remove all style-impacting spans from text before new 4680 * extracted text is being replaced into it, so that we don't have any 4681 * lingering spans applied during the replace. 4682 */ 4683 static void removeParcelableSpans(Spannable spannable, int start, int end) { 4684 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 4685 int i = spans.length; 4686 while (i > 0) { 4687 i--; 4688 spannable.removeSpan(spans[i]); 4689 } 4690 } 4691 4692 /** 4693 * Apply to this text view the given extracted text, as previously 4694 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 4695 */ 4696 public void setExtractedText(ExtractedText text) { 4697 Editable content = getEditableText(); 4698 if (text.text != null) { 4699 if (content == null) { 4700 setText(text.text, TextView.BufferType.EDITABLE); 4701 } else if (text.partialStartOffset < 0) { 4702 removeParcelableSpans(content, 0, content.length()); 4703 content.replace(0, content.length(), text.text); 4704 } else { 4705 final int N = content.length(); 4706 int start = text.partialStartOffset; 4707 if (start > N) start = N; 4708 int end = text.partialEndOffset; 4709 if (end > N) end = N; 4710 removeParcelableSpans(content, start, end); 4711 content.replace(start, end, text.text); 4712 } 4713 } 4714 4715 // Now set the selection position... make sure it is in range, to 4716 // avoid crashes. If this is a partial update, it is possible that 4717 // the underlying text may have changed, causing us problems here. 4718 // Also we just don't want to trust clients to do the right thing. 4719 Spannable sp = (Spannable)getText(); 4720 final int N = sp.length(); 4721 int start = text.selectionStart; 4722 if (start < 0) start = 0; 4723 else if (start > N) start = N; 4724 int end = text.selectionEnd; 4725 if (end < 0) end = 0; 4726 else if (end > N) end = N; 4727 Selection.setSelection(sp, start, end); 4728 4729 // Finally, update the selection mode. 4730 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 4731 MetaKeyKeyListener.startSelecting(this, sp); 4732 } else { 4733 MetaKeyKeyListener.stopSelecting(this, sp); 4734 } 4735 } 4736 4737 /** 4738 * @hide 4739 */ 4740 public void setExtracting(ExtractedTextRequest req) { 4741 if (mInputMethodState != null) { 4742 mInputMethodState.mExtracting = req; 4743 } 4744 } 4745 4746 /** 4747 * Called by the framework in response to a text completion from 4748 * the current input method, provided by it calling 4749 * {@link InputConnection#commitCompletion 4750 * InputConnection.commitCompletion()}. The default implementation does 4751 * nothing; text views that are supporting auto-completion should override 4752 * this to do their desired behavior. 4753 * 4754 * @param text The auto complete text the user has selected. 4755 */ 4756 public void onCommitCompletion(CompletionInfo text) { 4757 } 4758 4759 public void beginBatchEdit() { 4760 final InputMethodState ims = mInputMethodState; 4761 if (ims != null) { 4762 int nesting = ++ims.mBatchEditNesting; 4763 if (nesting == 1) { 4764 ims.mCursorChanged = false; 4765 ims.mChangedDelta = 0; 4766 if (ims.mContentChanged) { 4767 // We already have a pending change from somewhere else, 4768 // so turn this into a full update. 4769 ims.mChangedStart = 0; 4770 ims.mChangedEnd = mText.length(); 4771 } else { 4772 ims.mChangedStart = EXTRACT_UNKNOWN; 4773 ims.mChangedEnd = EXTRACT_UNKNOWN; 4774 ims.mContentChanged = false; 4775 } 4776 onBeginBatchEdit(); 4777 } 4778 } 4779 } 4780 4781 public void endBatchEdit() { 4782 final InputMethodState ims = mInputMethodState; 4783 if (ims != null) { 4784 int nesting = --ims.mBatchEditNesting; 4785 if (nesting == 0) { 4786 finishBatchEdit(ims); 4787 } 4788 } 4789 } 4790 4791 void ensureEndedBatchEdit() { 4792 final InputMethodState ims = mInputMethodState; 4793 if (ims != null && ims.mBatchEditNesting != 0) { 4794 ims.mBatchEditNesting = 0; 4795 finishBatchEdit(ims); 4796 } 4797 } 4798 4799 void finishBatchEdit(final InputMethodState ims) { 4800 onEndBatchEdit(); 4801 4802 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4803 updateAfterEdit(); 4804 reportExtractedText(); 4805 } else if (ims.mCursorChanged) { 4806 // Cheezy way to get us to report the current cursor location. 4807 invalidateCursor(); 4808 } 4809 } 4810 4811 void updateAfterEdit() { 4812 invalidate(); 4813 int curs = getSelectionStart(); 4814 4815 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == 4816 Gravity.BOTTOM) { 4817 registerForPreDraw(); 4818 } 4819 4820 if (curs >= 0) { 4821 mHighlightPathBogus = true; 4822 4823 if (isFocused()) { 4824 mShowCursor = SystemClock.uptimeMillis(); 4825 makeBlink(); 4826 } 4827 } 4828 4829 checkForResize(); 4830 } 4831 4832 /** 4833 * Called by the framework in response to a request to begin a batch 4834 * of edit operations through a call to link {@link #beginBatchEdit()}. 4835 */ 4836 public void onBeginBatchEdit() { 4837 } 4838 4839 /** 4840 * Called by the framework in response to a request to end a batch 4841 * of edit operations through a call to link {@link #endBatchEdit}. 4842 */ 4843 public void onEndBatchEdit() { 4844 } 4845 4846 /** 4847 * Called by the framework in response to a private command from the 4848 * current method, provided by it calling 4849 * {@link InputConnection#performPrivateCommand 4850 * InputConnection.performPrivateCommand()}. 4851 * 4852 * @param action The action name of the command. 4853 * @param data Any additional data for the command. This may be null. 4854 * @return Return true if you handled the command, else false. 4855 */ 4856 public boolean onPrivateIMECommand(String action, Bundle data) { 4857 return false; 4858 } 4859 4860 private void nullLayouts() { 4861 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 4862 mSavedLayout = (BoringLayout) mLayout; 4863 } 4864 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 4865 mSavedHintLayout = (BoringLayout) mHintLayout; 4866 } 4867 4868 mLayout = mHintLayout = null; 4869 } 4870 4871 /** 4872 * Make a new Layout based on the already-measured size of the view, 4873 * on the assumption that it was measured correctly at some point. 4874 */ 4875 private void assumeLayout() { 4876 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 4877 4878 if (width < 1) { 4879 width = 0; 4880 } 4881 4882 int physicalWidth = width; 4883 4884 if (mHorizontallyScrolling) { 4885 width = VERY_WIDE; 4886 } 4887 4888 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 4889 physicalWidth, false); 4890 } 4891 4892 /** 4893 * The width passed in is now the desired layout width, 4894 * not the full view width with padding. 4895 * {@hide} 4896 */ 4897 protected void makeNewLayout(int w, int hintWidth, 4898 BoringLayout.Metrics boring, 4899 BoringLayout.Metrics hintBoring, 4900 int ellipsisWidth, boolean bringIntoView) { 4901 stopMarquee(); 4902 4903 mHighlightPathBogus = true; 4904 4905 if (w < 0) { 4906 w = 0; 4907 } 4908 if (hintWidth < 0) { 4909 hintWidth = 0; 4910 } 4911 4912 Layout.Alignment alignment; 4913 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 4914 case Gravity.CENTER_HORIZONTAL: 4915 alignment = Layout.Alignment.ALIGN_CENTER; 4916 break; 4917 4918 case Gravity.RIGHT: 4919 alignment = Layout.Alignment.ALIGN_OPPOSITE; 4920 break; 4921 4922 default: 4923 alignment = Layout.Alignment.ALIGN_NORMAL; 4924 } 4925 4926 boolean shouldEllipsize = mEllipsize != null && mInput == null; 4927 4928 if (mText instanceof Spannable) { 4929 mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w, 4930 alignment, mSpacingMult, 4931 mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null, 4932 ellipsisWidth); 4933 } else { 4934 if (boring == UNKNOWN_BORING) { 4935 boring = BoringLayout.isBoring(mTransformed, mTextPaint, 4936 mBoring); 4937 if (boring != null) { 4938 mBoring = boring; 4939 } 4940 } 4941 4942 if (boring != null) { 4943 if (boring.width <= w && 4944 (mEllipsize == null || boring.width <= ellipsisWidth)) { 4945 if (mSavedLayout != null) { 4946 mLayout = mSavedLayout. 4947 replaceOrMake(mTransformed, mTextPaint, 4948 w, alignment, mSpacingMult, mSpacingAdd, 4949 boring, mIncludePad); 4950 } else { 4951 mLayout = BoringLayout.make(mTransformed, mTextPaint, 4952 w, alignment, mSpacingMult, mSpacingAdd, 4953 boring, mIncludePad); 4954 } 4955 4956 mSavedLayout = (BoringLayout) mLayout; 4957 } else if (shouldEllipsize && boring.width <= w) { 4958 if (mSavedLayout != null) { 4959 mLayout = mSavedLayout. 4960 replaceOrMake(mTransformed, mTextPaint, 4961 w, alignment, mSpacingMult, mSpacingAdd, 4962 boring, mIncludePad, mEllipsize, 4963 ellipsisWidth); 4964 } else { 4965 mLayout = BoringLayout.make(mTransformed, mTextPaint, 4966 w, alignment, mSpacingMult, mSpacingAdd, 4967 boring, mIncludePad, mEllipsize, 4968 ellipsisWidth); 4969 } 4970 } else if (shouldEllipsize) { 4971 mLayout = new StaticLayout(mTransformed, 4972 0, mTransformed.length(), 4973 mTextPaint, w, alignment, mSpacingMult, 4974 mSpacingAdd, mIncludePad, mEllipsize, 4975 ellipsisWidth); 4976 } else { 4977 mLayout = new StaticLayout(mTransformed, mTextPaint, 4978 w, alignment, mSpacingMult, mSpacingAdd, 4979 mIncludePad); 4980 } 4981 } else if (shouldEllipsize) { 4982 mLayout = new StaticLayout(mTransformed, 4983 0, mTransformed.length(), 4984 mTextPaint, w, alignment, mSpacingMult, 4985 mSpacingAdd, mIncludePad, mEllipsize, 4986 ellipsisWidth); 4987 } else { 4988 mLayout = new StaticLayout(mTransformed, mTextPaint, 4989 w, alignment, mSpacingMult, mSpacingAdd, 4990 mIncludePad); 4991 } 4992 } 4993 4994 shouldEllipsize = mEllipsize != null; 4995 mHintLayout = null; 4996 4997 if (mHint != null) { 4998 if (shouldEllipsize) hintWidth = w; 4999 5000 if (hintBoring == UNKNOWN_BORING) { 5001 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, 5002 mHintBoring); 5003 if (hintBoring != null) { 5004 mHintBoring = hintBoring; 5005 } 5006 } 5007 5008 if (hintBoring != null) { 5009 if (hintBoring.width <= hintWidth && 5010 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 5011 if (mSavedHintLayout != null) { 5012 mHintLayout = mSavedHintLayout. 5013 replaceOrMake(mHint, mTextPaint, 5014 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5015 hintBoring, mIncludePad); 5016 } else { 5017 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5018 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5019 hintBoring, mIncludePad); 5020 } 5021 5022 mSavedHintLayout = (BoringLayout) mHintLayout; 5023 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 5024 if (mSavedHintLayout != null) { 5025 mHintLayout = mSavedHintLayout. 5026 replaceOrMake(mHint, mTextPaint, 5027 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5028 hintBoring, mIncludePad, mEllipsize, 5029 ellipsisWidth); 5030 } else { 5031 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5032 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5033 hintBoring, mIncludePad, mEllipsize, 5034 ellipsisWidth); 5035 } 5036 } else if (shouldEllipsize) { 5037 mHintLayout = new StaticLayout(mHint, 5038 0, mHint.length(), 5039 mTextPaint, hintWidth, alignment, mSpacingMult, 5040 mSpacingAdd, mIncludePad, mEllipsize, 5041 ellipsisWidth); 5042 } else { 5043 mHintLayout = new StaticLayout(mHint, mTextPaint, 5044 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5045 mIncludePad); 5046 } 5047 } else if (shouldEllipsize) { 5048 mHintLayout = new StaticLayout(mHint, 5049 0, mHint.length(), 5050 mTextPaint, hintWidth, alignment, mSpacingMult, 5051 mSpacingAdd, mIncludePad, mEllipsize, 5052 ellipsisWidth); 5053 } else { 5054 mHintLayout = new StaticLayout(mHint, mTextPaint, 5055 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5056 mIncludePad); 5057 } 5058 } 5059 5060 if (bringIntoView) { 5061 registerForPreDraw(); 5062 } 5063 5064 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 5065 if (!compressText(ellipsisWidth)) { 5066 final int height = mLayoutParams.height; 5067 // If the size of the view does not depend on the size of the text, try to 5068 // start the marquee immediately 5069 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 5070 startMarquee(); 5071 } else { 5072 // Defer the start of the marquee until we know our width (see setFrame()) 5073 mRestartMarquee = true; 5074 } 5075 } 5076 } 5077 5078 // CursorControllers need a non-null mLayout 5079 prepareCursorControllers(); 5080 } 5081 5082 private boolean compressText(float width) { 5083 // Only compress the text if it hasn't been compressed by the previous pass 5084 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 5085 mTextPaint.getTextScaleX() == 1.0f) { 5086 final float textWidth = mLayout.getLineWidth(0); 5087 final float overflow = (textWidth + 1.0f - width) / width; 5088 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 5089 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 5090 post(new Runnable() { 5091 public void run() { 5092 requestLayout(); 5093 } 5094 }); 5095 return true; 5096 } 5097 } 5098 5099 return false; 5100 } 5101 5102 private static int desired(Layout layout) { 5103 int n = layout.getLineCount(); 5104 CharSequence text = layout.getText(); 5105 float max = 0; 5106 5107 // if any line was wrapped, we can't use it. 5108 // but it's ok for the last line not to have a newline 5109 5110 for (int i = 0; i < n - 1; i++) { 5111 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 5112 return -1; 5113 } 5114 5115 for (int i = 0; i < n; i++) { 5116 max = Math.max(max, layout.getLineWidth(i)); 5117 } 5118 5119 return (int) FloatMath.ceil(max); 5120 } 5121 5122 /** 5123 * Set whether the TextView includes extra top and bottom padding to make 5124 * room for accents that go above the normal ascent and descent. 5125 * The default is true. 5126 * 5127 * @attr ref android.R.styleable#TextView_includeFontPadding 5128 */ 5129 public void setIncludeFontPadding(boolean includepad) { 5130 mIncludePad = includepad; 5131 5132 if (mLayout != null) { 5133 nullLayouts(); 5134 requestLayout(); 5135 invalidate(); 5136 } 5137 } 5138 5139 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 5140 5141 @Override 5142 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5143 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5144 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5145 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5146 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5147 5148 int width; 5149 int height; 5150 5151 BoringLayout.Metrics boring = UNKNOWN_BORING; 5152 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 5153 5154 int des = -1; 5155 boolean fromexisting = false; 5156 5157 if (widthMode == MeasureSpec.EXACTLY) { 5158 // Parent has told us how big to be. So be it. 5159 width = widthSize; 5160 } else { 5161 if (mLayout != null && mEllipsize == null) { 5162 des = desired(mLayout); 5163 } 5164 5165 if (des < 0) { 5166 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring); 5167 if (boring != null) { 5168 mBoring = boring; 5169 } 5170 } else { 5171 fromexisting = true; 5172 } 5173 5174 if (boring == null || boring == UNKNOWN_BORING) { 5175 if (des < 0) { 5176 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 5177 } 5178 5179 width = des; 5180 } else { 5181 width = boring.width; 5182 } 5183 5184 final Drawables dr = mDrawables; 5185 if (dr != null) { 5186 width = Math.max(width, dr.mDrawableWidthTop); 5187 width = Math.max(width, dr.mDrawableWidthBottom); 5188 } 5189 5190 if (mHint != null) { 5191 int hintDes = -1; 5192 int hintWidth; 5193 5194 if (mHintLayout != null && mEllipsize == null) { 5195 hintDes = desired(mHintLayout); 5196 } 5197 5198 if (hintDes < 0) { 5199 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 5200 if (hintBoring != null) { 5201 mHintBoring = hintBoring; 5202 } 5203 } 5204 5205 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 5206 if (hintDes < 0) { 5207 hintDes = (int) FloatMath.ceil( 5208 Layout.getDesiredWidth(mHint, mTextPaint)); 5209 } 5210 5211 hintWidth = hintDes; 5212 } else { 5213 hintWidth = hintBoring.width; 5214 } 5215 5216 if (hintWidth > width) { 5217 width = hintWidth; 5218 } 5219 } 5220 5221 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 5222 5223 if (mMaxWidthMode == EMS) { 5224 width = Math.min(width, mMaxWidth * getLineHeight()); 5225 } else { 5226 width = Math.min(width, mMaxWidth); 5227 } 5228 5229 if (mMinWidthMode == EMS) { 5230 width = Math.max(width, mMinWidth * getLineHeight()); 5231 } else { 5232 width = Math.max(width, mMinWidth); 5233 } 5234 5235 // Check against our minimum width 5236 width = Math.max(width, getSuggestedMinimumWidth()); 5237 5238 if (widthMode == MeasureSpec.AT_MOST) { 5239 width = Math.min(widthSize, width); 5240 } 5241 } 5242 5243 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5244 int unpaddedWidth = want; 5245 int hintWant = want; 5246 5247 if (mHorizontallyScrolling) 5248 want = VERY_WIDE; 5249 5250 int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth(); 5251 5252 if (mLayout == null) { 5253 makeNewLayout(want, hintWant, boring, hintBoring, 5254 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5255 } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) || 5256 (mLayout.getEllipsizedWidth() != 5257 width - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 5258 if (mHint == null && mEllipsize == null && 5259 want > mLayout.getWidth() && 5260 (mLayout instanceof BoringLayout || 5261 (fromexisting && des >= 0 && des <= want))) { 5262 mLayout.increaseWidthTo(want); 5263 } else { 5264 makeNewLayout(want, hintWant, boring, hintBoring, 5265 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5266 } 5267 } else { 5268 // Width has not changed. 5269 } 5270 5271 if (heightMode == MeasureSpec.EXACTLY) { 5272 // Parent has told us how big to be. So be it. 5273 height = heightSize; 5274 mDesiredHeightAtMeasure = -1; 5275 } else { 5276 int desired = getDesiredHeight(); 5277 5278 height = desired; 5279 mDesiredHeightAtMeasure = desired; 5280 5281 if (heightMode == MeasureSpec.AT_MOST) { 5282 height = Math.min(desired, heightSize); 5283 } 5284 } 5285 5286 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 5287 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 5288 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 5289 } 5290 5291 /* 5292 * We didn't let makeNewLayout() register to bring the cursor into view, 5293 * so do it here if there is any possibility that it is needed. 5294 */ 5295 if (mMovement != null || 5296 mLayout.getWidth() > unpaddedWidth || 5297 mLayout.getHeight() > unpaddedHeight) { 5298 registerForPreDraw(); 5299 } else { 5300 scrollTo(0, 0); 5301 } 5302 5303 setMeasuredDimension(width, height); 5304 } 5305 5306 private int getDesiredHeight() { 5307 return Math.max( 5308 getDesiredHeight(mLayout, true), 5309 getDesiredHeight(mHintLayout, mEllipsize != null)); 5310 } 5311 5312 private int getDesiredHeight(Layout layout, boolean cap) { 5313 if (layout == null) { 5314 return 0; 5315 } 5316 5317 int linecount = layout.getLineCount(); 5318 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 5319 int desired = layout.getLineTop(linecount); 5320 5321 final Drawables dr = mDrawables; 5322 if (dr != null) { 5323 desired = Math.max(desired, dr.mDrawableHeightLeft); 5324 desired = Math.max(desired, dr.mDrawableHeightRight); 5325 } 5326 5327 desired += pad; 5328 5329 if (mMaxMode == LINES) { 5330 /* 5331 * Don't cap the hint to a certain number of lines. 5332 * (Do cap it, though, if we have a maximum pixel height.) 5333 */ 5334 if (cap) { 5335 if (linecount > mMaximum) { 5336 desired = layout.getLineTop(mMaximum) + 5337 layout.getBottomPadding(); 5338 5339 if (dr != null) { 5340 desired = Math.max(desired, dr.mDrawableHeightLeft); 5341 desired = Math.max(desired, dr.mDrawableHeightRight); 5342 } 5343 5344 desired += pad; 5345 linecount = mMaximum; 5346 } 5347 } 5348 } else { 5349 desired = Math.min(desired, mMaximum); 5350 } 5351 5352 if (mMinMode == LINES) { 5353 if (linecount < mMinimum) { 5354 desired += getLineHeight() * (mMinimum - linecount); 5355 } 5356 } else { 5357 desired = Math.max(desired, mMinimum); 5358 } 5359 5360 // Check against our minimum height 5361 desired = Math.max(desired, getSuggestedMinimumHeight()); 5362 5363 return desired; 5364 } 5365 5366 /** 5367 * Check whether a change to the existing text layout requires a 5368 * new view layout. 5369 */ 5370 private void checkForResize() { 5371 boolean sizeChanged = false; 5372 5373 if (mLayout != null) { 5374 // Check if our width changed 5375 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 5376 sizeChanged = true; 5377 invalidate(); 5378 } 5379 5380 // Check if our height changed 5381 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 5382 int desiredHeight = getDesiredHeight(); 5383 5384 if (desiredHeight != this.getHeight()) { 5385 sizeChanged = true; 5386 } 5387 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 5388 if (mDesiredHeightAtMeasure >= 0) { 5389 int desiredHeight = getDesiredHeight(); 5390 5391 if (desiredHeight != mDesiredHeightAtMeasure) { 5392 sizeChanged = true; 5393 } 5394 } 5395 } 5396 } 5397 5398 if (sizeChanged) { 5399 requestLayout(); 5400 // caller will have already invalidated 5401 } 5402 } 5403 5404 /** 5405 * Check whether entirely new text requires a new view layout 5406 * or merely a new text layout. 5407 */ 5408 private void checkForRelayout() { 5409 // If we have a fixed width, we can just swap in a new text layout 5410 // if the text height stays the same or if the view height is fixed. 5411 5412 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 5413 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 5414 (mHint == null || mHintLayout != null) && 5415 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 5416 // Static width, so try making a new text layout. 5417 5418 int oldht = mLayout.getHeight(); 5419 int want = mLayout.getWidth(); 5420 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 5421 5422 /* 5423 * No need to bring the text into view, since the size is not 5424 * changing (unless we do the requestLayout(), in which case it 5425 * will happen at measure). 5426 */ 5427 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 5428 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 5429 false); 5430 5431 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 5432 // In a fixed-height view, so use our new text layout. 5433 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 5434 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 5435 invalidate(); 5436 return; 5437 } 5438 5439 // Dynamic height, but height has stayed the same, 5440 // so use our new text layout. 5441 if (mLayout.getHeight() == oldht && 5442 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 5443 invalidate(); 5444 return; 5445 } 5446 } 5447 5448 // We lose: the height has changed and we have a dynamic height. 5449 // Request a new view layout using our new text layout. 5450 requestLayout(); 5451 invalidate(); 5452 } else { 5453 // Dynamic width, so we have no choice but to request a new 5454 // view layout with a new text layout. 5455 5456 nullLayouts(); 5457 requestLayout(); 5458 invalidate(); 5459 } 5460 } 5461 5462 /** 5463 * Returns true if anything changed. 5464 */ 5465 private boolean bringTextIntoView() { 5466 int line = 0; 5467 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 5468 line = mLayout.getLineCount() - 1; 5469 } 5470 5471 Layout.Alignment a = mLayout.getParagraphAlignment(line); 5472 int dir = mLayout.getParagraphDirection(line); 5473 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5474 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 5475 int ht = mLayout.getHeight(); 5476 5477 int scrollx, scrolly; 5478 5479 if (a == Layout.Alignment.ALIGN_CENTER) { 5480 /* 5481 * Keep centered if possible, or, if it is too wide to fit, 5482 * keep leading edge in view. 5483 */ 5484 5485 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5486 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5487 5488 if (right - left < hspace) { 5489 scrollx = (right + left) / 2 - hspace / 2; 5490 } else { 5491 if (dir < 0) { 5492 scrollx = right - hspace; 5493 } else { 5494 scrollx = left; 5495 } 5496 } 5497 } else if (a == Layout.Alignment.ALIGN_NORMAL) { 5498 /* 5499 * Keep leading edge in view. 5500 */ 5501 5502 if (dir < 0) { 5503 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5504 scrollx = right - hspace; 5505 } else { 5506 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5507 } 5508 } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ { 5509 /* 5510 * Keep trailing edge in view. 5511 */ 5512 5513 if (dir < 0) { 5514 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5515 } else { 5516 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5517 scrollx = right - hspace; 5518 } 5519 } 5520 5521 if (ht < vspace) { 5522 scrolly = 0; 5523 } else { 5524 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 5525 scrolly = ht - vspace; 5526 } else { 5527 scrolly = 0; 5528 } 5529 } 5530 5531 if (scrollx != mScrollX || scrolly != mScrollY) { 5532 scrollTo(scrollx, scrolly); 5533 return true; 5534 } else { 5535 return false; 5536 } 5537 } 5538 5539 /** 5540 * Move the point, specified by the offset, into the view if it is needed. 5541 * This has to be called after layout. Returns true if anything changed. 5542 */ 5543 public boolean bringPointIntoView(int offset) { 5544 boolean changed = false; 5545 5546 int line = mLayout.getLineForOffset(offset); 5547 5548 // FIXME: Is it okay to truncate this, or should we round? 5549 final int x = (int)mLayout.getPrimaryHorizontal(offset); 5550 final int top = mLayout.getLineTop(line); 5551 final int bottom = mLayout.getLineTop(line + 1); 5552 5553 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 5554 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 5555 int ht = mLayout.getHeight(); 5556 5557 int grav; 5558 5559 switch (mLayout.getParagraphAlignment(line)) { 5560 case ALIGN_NORMAL: 5561 grav = 1; 5562 break; 5563 5564 case ALIGN_OPPOSITE: 5565 grav = -1; 5566 break; 5567 5568 default: 5569 grav = 0; 5570 } 5571 5572 grav *= mLayout.getParagraphDirection(line); 5573 5574 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5575 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 5576 5577 int hslack = (bottom - top) / 2; 5578 int vslack = hslack; 5579 5580 if (vslack > vspace / 4) 5581 vslack = vspace / 4; 5582 if (hslack > hspace / 4) 5583 hslack = hspace / 4; 5584 5585 int hs = mScrollX; 5586 int vs = mScrollY; 5587 5588 if (top - vs < vslack) 5589 vs = top - vslack; 5590 if (bottom - vs > vspace - vslack) 5591 vs = bottom - (vspace - vslack); 5592 if (ht - vs < vspace) 5593 vs = ht - vspace; 5594 if (0 - vs > 0) 5595 vs = 0; 5596 5597 if (grav != 0) { 5598 if (x - hs < hslack) { 5599 hs = x - hslack; 5600 } 5601 if (x - hs > hspace - hslack) { 5602 hs = x - (hspace - hslack); 5603 } 5604 } 5605 5606 if (grav < 0) { 5607 if (left - hs > 0) 5608 hs = left; 5609 if (right - hs < hspace) 5610 hs = right - hspace; 5611 } else if (grav > 0) { 5612 if (right - hs < hspace) 5613 hs = right - hspace; 5614 if (left - hs > 0) 5615 hs = left; 5616 } else /* grav == 0 */ { 5617 if (right - left <= hspace) { 5618 /* 5619 * If the entire text fits, center it exactly. 5620 */ 5621 hs = left - (hspace - (right - left)) / 2; 5622 } else if (x > right - hslack) { 5623 /* 5624 * If we are near the right edge, keep the right edge 5625 * at the edge of the view. 5626 */ 5627 hs = right - hspace; 5628 } else if (x < left + hslack) { 5629 /* 5630 * If we are near the left edge, keep the left edge 5631 * at the edge of the view. 5632 */ 5633 hs = left; 5634 } else if (left > hs) { 5635 /* 5636 * Is there whitespace visible at the left? Fix it if so. 5637 */ 5638 hs = left; 5639 } else if (right < hs + hspace) { 5640 /* 5641 * Is there whitespace visible at the right? Fix it if so. 5642 */ 5643 hs = right - hspace; 5644 } else { 5645 /* 5646 * Otherwise, float as needed. 5647 */ 5648 if (x - hs < hslack) { 5649 hs = x - hslack; 5650 } 5651 if (x - hs > hspace - hslack) { 5652 hs = x - (hspace - hslack); 5653 } 5654 } 5655 } 5656 5657 if (hs != mScrollX || vs != mScrollY) { 5658 if (mScroller == null) { 5659 scrollTo(hs, vs); 5660 } else { 5661 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 5662 int dx = hs - mScrollX; 5663 int dy = vs - mScrollY; 5664 5665 if (duration > ANIMATED_SCROLL_GAP) { 5666 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 5667 awakenScrollBars(mScroller.getDuration()); 5668 invalidate(); 5669 } else { 5670 if (!mScroller.isFinished()) { 5671 mScroller.abortAnimation(); 5672 } 5673 5674 scrollBy(dx, dy); 5675 } 5676 5677 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 5678 } 5679 5680 changed = true; 5681 } 5682 5683 if (isFocused()) { 5684 // This offsets because getInterestingRect() is in terms of 5685 // viewport coordinates, but requestRectangleOnScreen() 5686 // is in terms of content coordinates. 5687 5688 Rect r = new Rect(x, top, x + 1, bottom); 5689 getInterestingRect(r, line); 5690 r.offset(mScrollX, mScrollY); 5691 5692 if (requestRectangleOnScreen(r)) { 5693 changed = true; 5694 } 5695 } 5696 5697 return changed; 5698 } 5699 5700 /** 5701 * Move the cursor, if needed, so that it is at an offset that is visible 5702 * to the user. This will not move the cursor if it represents more than 5703 * one character (a selection range). This will only work if the 5704 * TextView contains spannable text; otherwise it will do nothing. 5705 * 5706 * @return True if the cursor was actually moved, false otherwise. 5707 */ 5708 public boolean moveCursorToVisibleOffset() { 5709 if (!(mText instanceof Spannable)) { 5710 return false; 5711 } 5712 int start = getSelectionStart(); 5713 int end = getSelectionEnd(); 5714 if (start != end) { 5715 return false; 5716 } 5717 5718 // First: make sure the line is visible on screen: 5719 5720 int line = mLayout.getLineForOffset(start); 5721 5722 final int top = mLayout.getLineTop(line); 5723 final int bottom = mLayout.getLineTop(line + 1); 5724 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 5725 int vslack = (bottom - top) / 2; 5726 if (vslack > vspace / 4) 5727 vslack = vspace / 4; 5728 final int vs = mScrollY; 5729 5730 if (top < (vs+vslack)) { 5731 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 5732 } else if (bottom > (vspace+vs-vslack)) { 5733 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 5734 } 5735 5736 // Next: make sure the character is visible on screen: 5737 5738 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5739 final int hs = mScrollX; 5740 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 5741 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 5742 5743 int newStart = start; 5744 if (newStart < leftChar) { 5745 newStart = leftChar; 5746 } else if (newStart > rightChar) { 5747 newStart = rightChar; 5748 } 5749 5750 if (newStart != start) { 5751 Selection.setSelection((Spannable)mText, newStart); 5752 return true; 5753 } 5754 5755 return false; 5756 } 5757 5758 @Override 5759 public void computeScroll() { 5760 if (mScroller != null) { 5761 if (mScroller.computeScrollOffset()) { 5762 mScrollX = mScroller.getCurrX(); 5763 mScrollY = mScroller.getCurrY(); 5764 postInvalidate(); // So we draw again 5765 } 5766 } 5767 } 5768 5769 private void getInterestingRect(Rect r, int line) { 5770 convertFromViewportToContentCoordinates(r); 5771 5772 // Rectangle can can be expanded on first and last line to take 5773 // padding into account. 5774 // TODO Take left/right padding into account too? 5775 if (line == 0) r.top -= getExtendedPaddingTop(); 5776 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 5777 } 5778 5779 private void convertFromViewportToContentCoordinates(Rect r) { 5780 final int horizontalOffset = viewportToContentHorizontalOffset(); 5781 r.left += horizontalOffset; 5782 r.right += horizontalOffset; 5783 5784 final int verticalOffset = viewportToContentVerticalOffset(); 5785 r.top += verticalOffset; 5786 r.bottom += verticalOffset; 5787 } 5788 5789 private int viewportToContentHorizontalOffset() { 5790 return getCompoundPaddingLeft() - mScrollX; 5791 } 5792 5793 private int viewportToContentVerticalOffset() { 5794 int offset = getExtendedPaddingTop() - mScrollY; 5795 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5796 offset += getVerticalOffset(false); 5797 } 5798 return offset; 5799 } 5800 5801 @Override 5802 public void debug(int depth) { 5803 super.debug(depth); 5804 5805 String output = debugIndent(depth); 5806 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 5807 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 5808 + "} "; 5809 5810 if (mText != null) { 5811 5812 output += "mText=\"" + mText + "\" "; 5813 if (mLayout != null) { 5814 output += "mLayout width=" + mLayout.getWidth() 5815 + " height=" + mLayout.getHeight(); 5816 } 5817 } else { 5818 output += "mText=NULL"; 5819 } 5820 Log.d(VIEW_LOG_TAG, output); 5821 } 5822 5823 /** 5824 * Convenience for {@link Selection#getSelectionStart}. 5825 */ 5826 @ViewDebug.ExportedProperty(category = "text") 5827 public int getSelectionStart() { 5828 return Selection.getSelectionStart(getText()); 5829 } 5830 5831 /** 5832 * Convenience for {@link Selection#getSelectionEnd}. 5833 */ 5834 @ViewDebug.ExportedProperty(category = "text") 5835 public int getSelectionEnd() { 5836 return Selection.getSelectionEnd(getText()); 5837 } 5838 5839 /** 5840 * Return true iff there is a selection inside this text view. 5841 */ 5842 public boolean hasSelection() { 5843 final int selectionStart = getSelectionStart(); 5844 final int selectionEnd = getSelectionEnd(); 5845 5846 return selectionStart >= 0 && selectionStart != selectionEnd; 5847 } 5848 5849 /** 5850 * Sets the properties of this field (lines, horizontally scrolling, 5851 * transformation method) to be for a single-line input. 5852 * 5853 * @attr ref android.R.styleable#TextView_singleLine 5854 */ 5855 public void setSingleLine() { 5856 setSingleLine(true); 5857 } 5858 5859 /** 5860 * If true, sets the properties of this field (lines, horizontally 5861 * scrolling, transformation method) to be for a single-line input; 5862 * if false, restores these to the default conditions. 5863 * Note that calling this with false restores default conditions, 5864 * not necessarily those that were in effect prior to calling 5865 * it with true. 5866 * 5867 * @attr ref android.R.styleable#TextView_singleLine 5868 */ 5869 @android.view.RemotableViewMethod 5870 public void setSingleLine(boolean singleLine) { 5871 if ((mInputType&EditorInfo.TYPE_MASK_CLASS) 5872 == EditorInfo.TYPE_CLASS_TEXT) { 5873 if (singleLine) { 5874 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 5875 } else { 5876 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 5877 } 5878 } 5879 applySingleLine(singleLine, true); 5880 } 5881 5882 private void applySingleLine(boolean singleLine, boolean applyTransformation) { 5883 mSingleLine = singleLine; 5884 if (singleLine) { 5885 setLines(1); 5886 setHorizontallyScrolling(true); 5887 if (applyTransformation) { 5888 setTransformationMethod(SingleLineTransformationMethod. 5889 getInstance()); 5890 } 5891 } else { 5892 setMaxLines(Integer.MAX_VALUE); 5893 setHorizontallyScrolling(false); 5894 if (applyTransformation) { 5895 setTransformationMethod(null); 5896 } 5897 } 5898 } 5899 5900 /** 5901 * Causes words in the text that are longer than the view is wide 5902 * to be ellipsized instead of broken in the middle. You may also 5903 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 5904 * to constrain the text to a single line. Use <code>null</code> 5905 * to turn off ellipsizing. 5906 * 5907 * @attr ref android.R.styleable#TextView_ellipsize 5908 */ 5909 public void setEllipsize(TextUtils.TruncateAt where) { 5910 mEllipsize = where; 5911 5912 if (mLayout != null) { 5913 nullLayouts(); 5914 requestLayout(); 5915 invalidate(); 5916 } 5917 } 5918 5919 /** 5920 * Sets how many times to repeat the marquee animation. Only applied if the 5921 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 5922 * 5923 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 5924 */ 5925 public void setMarqueeRepeatLimit(int marqueeLimit) { 5926 mMarqueeRepeatLimit = marqueeLimit; 5927 } 5928 5929 /** 5930 * Returns where, if anywhere, words that are longer than the view 5931 * is wide should be ellipsized. 5932 */ 5933 @ViewDebug.ExportedProperty 5934 public TextUtils.TruncateAt getEllipsize() { 5935 return mEllipsize; 5936 } 5937 5938 /** 5939 * Set the TextView so that when it takes focus, all the text is 5940 * selected. 5941 * 5942 * @attr ref android.R.styleable#TextView_selectAllOnFocus 5943 */ 5944 @android.view.RemotableViewMethod 5945 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 5946 mSelectAllOnFocus = selectAllOnFocus; 5947 5948 if (selectAllOnFocus && !(mText instanceof Spannable)) { 5949 setText(mText, BufferType.SPANNABLE); 5950 } 5951 } 5952 5953 /** 5954 * Set whether the cursor is visible. The default is true. 5955 * 5956 * @attr ref android.R.styleable#TextView_cursorVisible 5957 */ 5958 @android.view.RemotableViewMethod 5959 public void setCursorVisible(boolean visible) { 5960 mCursorVisible = visible; 5961 invalidate(); 5962 5963 if (visible) { 5964 makeBlink(); 5965 } else if (mBlink != null) { 5966 mBlink.removeCallbacks(mBlink); 5967 } 5968 5969 // InsertionPointCursorController depends on mCursorVisible 5970 prepareCursorControllers(); 5971 } 5972 5973 private boolean canMarquee() { 5974 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 5975 return width > 0 && mLayout.getLineWidth(0) > width; 5976 } 5977 5978 private void startMarquee() { 5979 // Do not ellipsize EditText 5980 if (mInput != null) return; 5981 5982 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 5983 return; 5984 } 5985 5986 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 5987 getLineCount() == 1 && canMarquee()) { 5988 5989 if (mMarquee == null) mMarquee = new Marquee(this); 5990 mMarquee.start(mMarqueeRepeatLimit); 5991 } 5992 } 5993 5994 private void stopMarquee() { 5995 if (mMarquee != null && !mMarquee.isStopped()) { 5996 mMarquee.stop(); 5997 } 5998 } 5999 6000 private void startStopMarquee(boolean start) { 6001 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6002 if (start) { 6003 startMarquee(); 6004 } else { 6005 stopMarquee(); 6006 } 6007 } 6008 } 6009 6010 private static final class Marquee extends Handler { 6011 // TODO: Add an option to configure this 6012 private static final float MARQUEE_DELTA_MAX = 0.07f; 6013 private static final int MARQUEE_DELAY = 1200; 6014 private static final int MARQUEE_RESTART_DELAY = 1200; 6015 private static final int MARQUEE_RESOLUTION = 1000 / 30; 6016 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 6017 6018 private static final byte MARQUEE_STOPPED = 0x0; 6019 private static final byte MARQUEE_STARTING = 0x1; 6020 private static final byte MARQUEE_RUNNING = 0x2; 6021 6022 private static final int MESSAGE_START = 0x1; 6023 private static final int MESSAGE_TICK = 0x2; 6024 private static final int MESSAGE_RESTART = 0x3; 6025 6026 private final WeakReference<TextView> mView; 6027 6028 private byte mStatus = MARQUEE_STOPPED; 6029 private final float mScrollUnit; 6030 private float mMaxScroll; 6031 float mMaxFadeScroll; 6032 private float mGhostStart; 6033 private float mGhostOffset; 6034 private float mFadeStop; 6035 private int mRepeatLimit; 6036 6037 float mScroll; 6038 6039 Marquee(TextView v) { 6040 final float density = v.getContext().getResources().getDisplayMetrics().density; 6041 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 6042 mView = new WeakReference<TextView>(v); 6043 } 6044 6045 @Override 6046 public void handleMessage(Message msg) { 6047 switch (msg.what) { 6048 case MESSAGE_START: 6049 mStatus = MARQUEE_RUNNING; 6050 tick(); 6051 break; 6052 case MESSAGE_TICK: 6053 tick(); 6054 break; 6055 case MESSAGE_RESTART: 6056 if (mStatus == MARQUEE_RUNNING) { 6057 if (mRepeatLimit >= 0) { 6058 mRepeatLimit--; 6059 } 6060 start(mRepeatLimit); 6061 } 6062 break; 6063 } 6064 } 6065 6066 void tick() { 6067 if (mStatus != MARQUEE_RUNNING) { 6068 return; 6069 } 6070 6071 removeMessages(MESSAGE_TICK); 6072 6073 final TextView textView = mView.get(); 6074 if (textView != null && (textView.isFocused() || textView.isSelected())) { 6075 mScroll += mScrollUnit; 6076 if (mScroll > mMaxScroll) { 6077 mScroll = mMaxScroll; 6078 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 6079 } else { 6080 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 6081 } 6082 textView.invalidate(); 6083 } 6084 } 6085 6086 void stop() { 6087 mStatus = MARQUEE_STOPPED; 6088 removeMessages(MESSAGE_START); 6089 removeMessages(MESSAGE_RESTART); 6090 removeMessages(MESSAGE_TICK); 6091 resetScroll(); 6092 } 6093 6094 private void resetScroll() { 6095 mScroll = 0.0f; 6096 final TextView textView = mView.get(); 6097 if (textView != null) textView.invalidate(); 6098 } 6099 6100 void start(int repeatLimit) { 6101 if (repeatLimit == 0) { 6102 stop(); 6103 return; 6104 } 6105 mRepeatLimit = repeatLimit; 6106 final TextView textView = mView.get(); 6107 if (textView != null && textView.mLayout != null) { 6108 mStatus = MARQUEE_STARTING; 6109 mScroll = 0.0f; 6110 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 6111 textView.getCompoundPaddingRight(); 6112 final float lineWidth = textView.mLayout.getLineWidth(0); 6113 final float gap = textWidth / 3.0f; 6114 mGhostStart = lineWidth - textWidth + gap; 6115 mMaxScroll = mGhostStart + textWidth; 6116 mGhostOffset = lineWidth + gap; 6117 mFadeStop = lineWidth + textWidth / 6.0f; 6118 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 6119 6120 textView.invalidate(); 6121 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 6122 } 6123 } 6124 6125 float getGhostOffset() { 6126 return mGhostOffset; 6127 } 6128 6129 boolean shouldDrawLeftFade() { 6130 return mScroll <= mFadeStop; 6131 } 6132 6133 boolean shouldDrawGhost() { 6134 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 6135 } 6136 6137 boolean isRunning() { 6138 return mStatus == MARQUEE_RUNNING; 6139 } 6140 6141 boolean isStopped() { 6142 return mStatus == MARQUEE_STOPPED; 6143 } 6144 } 6145 6146 /** 6147 * This method is called when the text is changed, in case any 6148 * subclasses would like to know. 6149 * 6150 * @param text The text the TextView is displaying. 6151 * @param start The offset of the start of the range of the text 6152 * that was modified. 6153 * @param before The offset of the former end of the range of the 6154 * text that was modified. If text was simply inserted, 6155 * this will be the same as <code>start</code>. 6156 * If text was replaced with new text or deleted, the 6157 * length of the old text was <code>before-start</code>. 6158 * @param after The offset of the end of the range of the text 6159 * that was modified. If text was simply deleted, 6160 * this will be the same as <code>start</code>. 6161 * If text was replaced with new text or inserted, 6162 * the length of the new text is <code>after-start</code>. 6163 */ 6164 protected void onTextChanged(CharSequence text, 6165 int start, int before, int after) { 6166 } 6167 6168 /** 6169 * This method is called when the selection has changed, in case any 6170 * subclasses would like to know. 6171 * 6172 * @param selStart The new selection start location. 6173 * @param selEnd The new selection end location. 6174 */ 6175 protected void onSelectionChanged(int selStart, int selEnd) { 6176 } 6177 6178 /** 6179 * Adds a TextWatcher to the list of those whose methods are called 6180 * whenever this TextView's text changes. 6181 * <p> 6182 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 6183 * not called after {@link #setText} calls. Now, doing {@link #setText} 6184 * if there are any text changed listeners forces the buffer type to 6185 * Editable if it would not otherwise be and does call this method. 6186 */ 6187 public void addTextChangedListener(TextWatcher watcher) { 6188 if (mListeners == null) { 6189 mListeners = new ArrayList<TextWatcher>(); 6190 } 6191 6192 mListeners.add(watcher); 6193 } 6194 6195 /** 6196 * Removes the specified TextWatcher from the list of those whose 6197 * methods are called 6198 * whenever this TextView's text changes. 6199 */ 6200 public void removeTextChangedListener(TextWatcher watcher) { 6201 if (mListeners != null) { 6202 int i = mListeners.indexOf(watcher); 6203 6204 if (i >= 0) { 6205 mListeners.remove(i); 6206 } 6207 } 6208 } 6209 6210 private void sendBeforeTextChanged(CharSequence text, int start, int before, 6211 int after) { 6212 if (mListeners != null) { 6213 final ArrayList<TextWatcher> list = mListeners; 6214 final int count = list.size(); 6215 for (int i = 0; i < count; i++) { 6216 list.get(i).beforeTextChanged(text, start, before, after); 6217 } 6218 } 6219 } 6220 6221 /** 6222 * Not private so it can be called from an inner class without going 6223 * through a thunk. 6224 */ 6225 void sendOnTextChanged(CharSequence text, int start, int before, 6226 int after) { 6227 if (mListeners != null) { 6228 final ArrayList<TextWatcher> list = mListeners; 6229 final int count = list.size(); 6230 for (int i = 0; i < count; i++) { 6231 list.get(i).onTextChanged(text, start, before, after); 6232 } 6233 } 6234 } 6235 6236 /** 6237 * Not private so it can be called from an inner class without going 6238 * through a thunk. 6239 */ 6240 void sendAfterTextChanged(Editable text) { 6241 if (mListeners != null) { 6242 final ArrayList<TextWatcher> list = mListeners; 6243 final int count = list.size(); 6244 for (int i = 0; i < count; i++) { 6245 list.get(i).afterTextChanged(text); 6246 } 6247 } 6248 } 6249 6250 /** 6251 * Not private so it can be called from an inner class without going 6252 * through a thunk. 6253 */ 6254 void handleTextChanged(CharSequence buffer, int start, 6255 int before, int after) { 6256 final InputMethodState ims = mInputMethodState; 6257 if (ims == null || ims.mBatchEditNesting == 0) { 6258 updateAfterEdit(); 6259 } 6260 if (ims != null) { 6261 ims.mContentChanged = true; 6262 if (ims.mChangedStart < 0) { 6263 ims.mChangedStart = start; 6264 ims.mChangedEnd = start+before; 6265 } else { 6266 ims.mChangedStart = Math.min(ims.mChangedStart, start); 6267 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 6268 } 6269 ims.mChangedDelta += after-before; 6270 } 6271 6272 sendOnTextChanged(buffer, start, before, after); 6273 onTextChanged(buffer, start, before, after); 6274 hideControllers(); 6275 } 6276 6277 /** 6278 * Not private so it can be called from an inner class without going 6279 * through a thunk. 6280 */ 6281 void spanChange(Spanned buf, Object what, int oldStart, int newStart, 6282 int oldEnd, int newEnd) { 6283 // XXX Make the start and end move together if this ends up 6284 // spending too much time invalidating. 6285 6286 boolean selChanged = false; 6287 int newSelStart=-1, newSelEnd=-1; 6288 6289 final InputMethodState ims = mInputMethodState; 6290 6291 if (what == Selection.SELECTION_END) { 6292 mHighlightPathBogus = true; 6293 selChanged = true; 6294 newSelEnd = newStart; 6295 6296 if (!isFocused()) { 6297 mSelectionMoved = true; 6298 } 6299 6300 if (oldStart >= 0 || newStart >= 0) { 6301 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 6302 registerForPreDraw(); 6303 6304 if (isFocused()) { 6305 mShowCursor = SystemClock.uptimeMillis(); 6306 makeBlink(); 6307 } 6308 } 6309 } 6310 6311 if (what == Selection.SELECTION_START) { 6312 mHighlightPathBogus = true; 6313 selChanged = true; 6314 newSelStart = newStart; 6315 6316 if (!isFocused()) { 6317 mSelectionMoved = true; 6318 } 6319 6320 if (oldStart >= 0 || newStart >= 0) { 6321 int end = Selection.getSelectionEnd(buf); 6322 invalidateCursor(end, oldStart, newStart); 6323 } 6324 } 6325 6326 if (selChanged) { 6327 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 6328 if (newSelStart < 0) { 6329 newSelStart = Selection.getSelectionStart(buf); 6330 } 6331 if (newSelEnd < 0) { 6332 newSelEnd = Selection.getSelectionEnd(buf); 6333 } 6334 onSelectionChanged(newSelStart, newSelEnd); 6335 } 6336 } 6337 6338 if (what instanceof UpdateAppearance || 6339 what instanceof ParagraphStyle) { 6340 if (ims == null || ims.mBatchEditNesting == 0) { 6341 invalidate(); 6342 mHighlightPathBogus = true; 6343 checkForResize(); 6344 } else { 6345 ims.mContentChanged = true; 6346 } 6347 } 6348 6349 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 6350 mHighlightPathBogus = true; 6351 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 6352 ims.mSelectionModeChanged = true; 6353 } 6354 6355 if (Selection.getSelectionStart(buf) >= 0) { 6356 if (ims == null || ims.mBatchEditNesting == 0) { 6357 invalidateCursor(); 6358 } else { 6359 ims.mCursorChanged = true; 6360 } 6361 } 6362 } 6363 6364 if (what instanceof ParcelableSpan) { 6365 // If this is a span that can be sent to a remote process, 6366 // the current extract editor would be interested in it. 6367 if (ims != null && ims.mExtracting != null) { 6368 if (ims.mBatchEditNesting != 0) { 6369 if (oldStart >= 0) { 6370 if (ims.mChangedStart > oldStart) { 6371 ims.mChangedStart = oldStart; 6372 } 6373 if (ims.mChangedStart > oldEnd) { 6374 ims.mChangedStart = oldEnd; 6375 } 6376 } 6377 if (newStart >= 0) { 6378 if (ims.mChangedStart > newStart) { 6379 ims.mChangedStart = newStart; 6380 } 6381 if (ims.mChangedStart > newEnd) { 6382 ims.mChangedStart = newEnd; 6383 } 6384 } 6385 } else { 6386 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 6387 + oldStart + "-" + oldEnd + "," 6388 + newStart + "-" + newEnd + what); 6389 ims.mContentChanged = true; 6390 } 6391 } 6392 } 6393 } 6394 6395 private class ChangeWatcher 6396 implements TextWatcher, SpanWatcher { 6397 6398 private CharSequence mBeforeText; 6399 6400 public void beforeTextChanged(CharSequence buffer, int start, 6401 int before, int after) { 6402 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 6403 + " before=" + before + " after=" + after + ": " + buffer); 6404 6405 if (AccessibilityManager.getInstance(mContext).isEnabled() 6406 && !isPasswordInputType(mInputType)) { 6407 mBeforeText = buffer.toString(); 6408 } 6409 6410 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 6411 } 6412 6413 public void onTextChanged(CharSequence buffer, int start, 6414 int before, int after) { 6415 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 6416 + " before=" + before + " after=" + after + ": " + buffer); 6417 TextView.this.handleTextChanged(buffer, start, before, after); 6418 6419 if (AccessibilityManager.getInstance(mContext).isEnabled() && 6420 (isFocused() || isSelected() && 6421 isShown())) { 6422 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 6423 mBeforeText = null; 6424 } 6425 } 6426 6427 public void afterTextChanged(Editable buffer) { 6428 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 6429 TextView.this.sendAfterTextChanged(buffer); 6430 6431 if (MetaKeyKeyListener.getMetaState(buffer, 6432 MetaKeyKeyListener.META_SELECTING) != 0) { 6433 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 6434 } 6435 } 6436 6437 public void onSpanChanged(Spannable buf, 6438 Object what, int s, int e, int st, int en) { 6439 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 6440 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 6441 TextView.this.spanChange(buf, what, s, st, e, en); 6442 } 6443 6444 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 6445 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 6446 + " what=" + what + ": " + buf); 6447 TextView.this.spanChange(buf, what, -1, s, -1, e); 6448 } 6449 6450 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 6451 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 6452 + " what=" + what + ": " + buf); 6453 TextView.this.spanChange(buf, what, s, -1, e, -1); 6454 } 6455 } 6456 6457 private void makeBlink() { 6458 if (!mCursorVisible) { 6459 if (mBlink != null) { 6460 mBlink.removeCallbacks(mBlink); 6461 } 6462 6463 return; 6464 } 6465 6466 if (mBlink == null) 6467 mBlink = new Blink(this); 6468 6469 mBlink.removeCallbacks(mBlink); 6470 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 6471 } 6472 6473 /** 6474 * @hide 6475 */ 6476 @Override 6477 public void dispatchFinishTemporaryDetach() { 6478 mDispatchTemporaryDetach = true; 6479 super.dispatchFinishTemporaryDetach(); 6480 mDispatchTemporaryDetach = false; 6481 } 6482 6483 @Override 6484 public void onStartTemporaryDetach() { 6485 super.onStartTemporaryDetach(); 6486 // Only track when onStartTemporaryDetach() is called directly, 6487 // usually because this instance is an editable field in a list 6488 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 6489 } 6490 6491 @Override 6492 public void onFinishTemporaryDetach() { 6493 super.onFinishTemporaryDetach(); 6494 // Only track when onStartTemporaryDetach() is called directly, 6495 // usually because this instance is an editable field in a list 6496 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 6497 } 6498 6499 @Override 6500 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 6501 if (mTemporaryDetach) { 6502 // If we are temporarily in the detach state, then do nothing. 6503 super.onFocusChanged(focused, direction, previouslyFocusedRect); 6504 return; 6505 } 6506 6507 mShowCursor = SystemClock.uptimeMillis(); 6508 6509 ensureEndedBatchEdit(); 6510 6511 if (focused) { 6512 int selStart = getSelectionStart(); 6513 int selEnd = getSelectionEnd(); 6514 6515 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 6516 // Has to be done before onTakeFocus, which can be overloaded. 6517 if (mLastTouchOffset >= 0) { 6518 // Can happen when a TextView is displayed after its content has been deleted. 6519 mLastTouchOffset = Math.min(mLastTouchOffset, mText.length()); 6520 Selection.setSelection((Spannable) mText, mLastTouchOffset); 6521 } 6522 6523 if (mMovement != null) { 6524 mMovement.onTakeFocus(this, (Spannable) mText, direction); 6525 } 6526 6527 if (mSelectAllOnFocus) { 6528 Selection.setSelection((Spannable) mText, 0, mText.length()); 6529 } 6530 6531 // The DecorView does not have focus when the 'Done' ExtractEditText button is 6532 // pressed. Since it is the ViewRoot's mView, it requests focus before 6533 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 6534 // This special case ensure that we keep current selection in that case. 6535 // It would be better to know why the DecorView does not have focus at that time. 6536 if (((this instanceof ExtractEditText) || mSelectionMoved) && 6537 selStart >= 0 && selEnd >= 0) { 6538 /* 6539 * Someone intentionally set the selection, so let them 6540 * do whatever it is that they wanted to do instead of 6541 * the default on-focus behavior. We reset the selection 6542 * here instead of just skipping the onTakeFocus() call 6543 * because some movement methods do something other than 6544 * just setting the selection in theirs and we still 6545 * need to go through that path. 6546 */ 6547 Selection.setSelection((Spannable) mText, selStart, selEnd); 6548 } 6549 mTouchFocusSelected = true; 6550 } 6551 6552 mFrozenWithFocus = false; 6553 mSelectionMoved = false; 6554 6555 if (mText instanceof Spannable) { 6556 Spannable sp = (Spannable) mText; 6557 MetaKeyKeyListener.resetMetaState(sp); 6558 } 6559 6560 makeBlink(); 6561 6562 if (mError != null) { 6563 showError(); 6564 } 6565 } else { 6566 if (mError != null) { 6567 hideError(); 6568 } 6569 // Don't leave us in the middle of a batch edit. 6570 onEndBatchEdit(); 6571 6572 hideInsertionPointCursorController(); 6573 if (this instanceof ExtractEditText) { 6574 // terminateTextSelectionMode would remove selection, which we want to keep when 6575 // ExtractEditText goes out of focus. 6576 mIsInTextSelectionMode = false; 6577 } else { 6578 terminateTextSelectionMode(); 6579 } 6580 } 6581 6582 startStopMarquee(focused); 6583 6584 if (mTransformation != null) { 6585 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 6586 } 6587 6588 super.onFocusChanged(focused, direction, previouslyFocusedRect); 6589 } 6590 6591 @Override 6592 public void onWindowFocusChanged(boolean hasWindowFocus) { 6593 super.onWindowFocusChanged(hasWindowFocus); 6594 6595 if (hasWindowFocus) { 6596 if (mBlink != null) { 6597 mBlink.uncancel(); 6598 6599 if (isFocused()) { 6600 mShowCursor = SystemClock.uptimeMillis(); 6601 makeBlink(); 6602 } 6603 } 6604 } else { 6605 if (mBlink != null) { 6606 mBlink.cancel(); 6607 } 6608 // Don't leave us in the middle of a batch edit. 6609 onEndBatchEdit(); 6610 if (mInputContentType != null) { 6611 mInputContentType.enterDown = false; 6612 } 6613 } 6614 6615 startStopMarquee(hasWindowFocus); 6616 } 6617 6618 /** 6619 * Use {@link BaseInputConnection#removeComposingSpans 6620 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 6621 * state from this text view. 6622 */ 6623 public void clearComposingText() { 6624 if (mText instanceof Spannable) { 6625 BaseInputConnection.removeComposingSpans((Spannable)mText); 6626 } 6627 } 6628 6629 @Override 6630 public void setSelected(boolean selected) { 6631 boolean wasSelected = isSelected(); 6632 6633 super.setSelected(selected); 6634 6635 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6636 if (selected) { 6637 startMarquee(); 6638 } else { 6639 stopMarquee(); 6640 } 6641 } 6642 } 6643 6644 private void onTapUpEvent(int prevStart, int prevEnd) { 6645 final int start = getSelectionStart(); 6646 final int end = getSelectionEnd(); 6647 6648 if (start == end) { 6649 if (start >= prevStart && start < prevEnd) { 6650 // Restore previous selection 6651 Selection.setSelection((Spannable)mText, prevStart, prevEnd); 6652 // Tapping inside the selection displays the cut/copy/paste context menu. 6653 showContextMenu(); 6654 return; 6655 } else { 6656 // Tapping outside stops selection mode, if any 6657 stopTextSelectionMode(); 6658 6659 if (mInsertionPointCursorController != null) { 6660 mInsertionPointCursorController.show(); 6661 } 6662 } 6663 } 6664 } 6665 6666 class CommitSelectionReceiver extends ResultReceiver { 6667 private final int mPrevStart, mPrevEnd; 6668 6669 public CommitSelectionReceiver(int prevStart, int prevEnd) { 6670 super(getHandler()); 6671 mPrevStart = prevStart; 6672 mPrevEnd = prevEnd; 6673 } 6674 6675 @Override 6676 protected void onReceiveResult(int resultCode, Bundle resultData) { 6677 // If this tap was actually used to show the IMM, leave cursor or selection unchanged 6678 // by restoring its previous position. 6679 if (resultCode == InputMethodManager.RESULT_SHOWN) { 6680 final int len = mText.length(); 6681 int start = Math.min(len, mPrevStart); 6682 int end = Math.min(len, mPrevEnd); 6683 Selection.setSelection((Spannable)mText, start, end); 6684 6685 if (hasSelection()) { 6686 startTextSelectionMode(); 6687 } else if (mInsertionPointCursorController != null) { 6688 mInsertionPointCursorController.show(); 6689 } 6690 } 6691 } 6692 } 6693 6694 @Override 6695 public boolean onTouchEvent(MotionEvent event) { 6696 final int action = event.getActionMasked(); 6697 if (action == MotionEvent.ACTION_DOWN) { 6698 if (mInsertionPointCursorController != null) { 6699 mInsertionPointCursorController.onTouchEvent(event); 6700 } 6701 if (mSelectionModifierCursorController != null) { 6702 mSelectionModifierCursorController.onTouchEvent(event); 6703 } 6704 6705 // Reset this state; it will be re-set if super.onTouchEvent 6706 // causes focus to move to the view. 6707 mTouchFocusSelected = false; 6708 mScrolled = false; 6709 } 6710 6711 final boolean superResult = super.onTouchEvent(event); 6712 6713 /* 6714 * Don't handle the release after a long press, because it will 6715 * move the selection away from whatever the menu action was 6716 * trying to affect. 6717 */ 6718 if (mEatTouchRelease && action == MotionEvent.ACTION_UP) { 6719 mEatTouchRelease = false; 6720 return superResult; 6721 } 6722 6723 if ((mMovement != null || onCheckIsTextEditor()) && mText instanceof Spannable && mLayout != null) { 6724 if (mInsertionPointCursorController != null) { 6725 mInsertionPointCursorController.onTouchEvent(event); 6726 } 6727 if (mSelectionModifierCursorController != null) { 6728 mSelectionModifierCursorController.onTouchEvent(event); 6729 } 6730 6731 boolean handled = false; 6732 6733 // Save previous selection, in case this event is used to show the IME. 6734 int oldSelStart = getSelectionStart(); 6735 int oldSelEnd = getSelectionEnd(); 6736 6737 final int oldScrollX = mScrollX; 6738 final int oldScrollY = mScrollY; 6739 6740 if (mMovement != null) { 6741 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 6742 } 6743 6744 if (isTextEditable()) { 6745 if (mScrollX != oldScrollX || mScrollY != oldScrollY) { 6746 // Hide insertion anchor while scrolling. Leave selection. 6747 hideInsertionPointCursorController(); 6748 if (mSelectionModifierCursorController != null && 6749 mSelectionModifierCursorController.isShowing()) { 6750 mSelectionModifierCursorController.updatePosition(); 6751 } 6752 } 6753 if (action == MotionEvent.ACTION_UP && isFocused() && !mScrolled) { 6754 InputMethodManager imm = (InputMethodManager) 6755 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 6756 6757 CommitSelectionReceiver csr = null; 6758 if (getSelectionStart() != oldSelStart || getSelectionEnd() != oldSelEnd || 6759 didTouchFocusSelect()) { 6760 csr = new CommitSelectionReceiver(oldSelStart, oldSelEnd); 6761 } 6762 6763 handled |= imm.showSoftInput(this, 0, csr) && (csr != null); 6764 6765 // Cannot be done by CommitSelectionReceiver, which might not always be called, 6766 // for instance when dealing with an ExtractEditText. 6767 onTapUpEvent(oldSelStart, oldSelEnd); 6768 } 6769 } 6770 6771 if (handled) { 6772 return true; 6773 } 6774 } 6775 6776 return superResult; 6777 } 6778 6779 private void prepareCursorControllers() { 6780 // TODO Add an extra android:cursorController flag to disable the controller? 6781 if (mCursorVisible && mLayout != null) { 6782 if (mInsertionPointCursorController == null) { 6783 mInsertionPointCursorController = new InsertionPointCursorController(); 6784 } 6785 } else { 6786 mInsertionPointCursorController = null; 6787 } 6788 6789 if (canSelectText() && mLayout != null) { 6790 if (mSelectionModifierCursorController == null) { 6791 mSelectionModifierCursorController = new SelectionModifierCursorController(); 6792 } 6793 } else { 6794 // Stop selection mode if the controller becomes unavailable. 6795 stopTextSelectionMode(); 6796 mSelectionModifierCursorController = null; 6797 } 6798 } 6799 6800 /** 6801 * @return True iff this TextView contains a text that can be edited. 6802 */ 6803 private boolean isTextEditable() { 6804 return mText instanceof Editable && onCheckIsTextEditor(); 6805 } 6806 6807 /** 6808 * Returns true, only while processing a touch gesture, if the initial 6809 * touch down event caused focus to move to the text view and as a result 6810 * its selection changed. Only valid while processing the touch gesture 6811 * of interest. 6812 */ 6813 public boolean didTouchFocusSelect() { 6814 return mTouchFocusSelected; 6815 } 6816 6817 @Override 6818 public void cancelLongPress() { 6819 super.cancelLongPress(); 6820 mScrolled = true; 6821 } 6822 6823 @Override 6824 public boolean onTrackballEvent(MotionEvent event) { 6825 if (mMovement != null && mText instanceof Spannable && 6826 mLayout != null) { 6827 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 6828 return true; 6829 } 6830 } 6831 6832 return super.onTrackballEvent(event); 6833 } 6834 6835 public void setScroller(Scroller s) { 6836 mScroller = s; 6837 } 6838 6839 private static class Blink extends Handler implements Runnable { 6840 private final WeakReference<TextView> mView; 6841 private boolean mCancelled; 6842 6843 public Blink(TextView v) { 6844 mView = new WeakReference<TextView>(v); 6845 } 6846 6847 public void run() { 6848 if (mCancelled) { 6849 return; 6850 } 6851 6852 removeCallbacks(Blink.this); 6853 6854 TextView tv = mView.get(); 6855 6856 if (tv != null && tv.isFocused()) { 6857 int st = tv.getSelectionStart(); 6858 int en = tv.getSelectionEnd(); 6859 6860 if (st == en && st >= 0 && en >= 0) { 6861 if (tv.mLayout != null) { 6862 tv.invalidateCursorPath(); 6863 } 6864 6865 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 6866 } 6867 } 6868 } 6869 6870 void cancel() { 6871 if (!mCancelled) { 6872 removeCallbacks(Blink.this); 6873 mCancelled = true; 6874 } 6875 } 6876 6877 void uncancel() { 6878 mCancelled = false; 6879 } 6880 } 6881 6882 @Override 6883 protected float getLeftFadingEdgeStrength() { 6884 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6885 if (mMarquee != null && !mMarquee.isStopped()) { 6886 final Marquee marquee = mMarquee; 6887 if (marquee.shouldDrawLeftFade()) { 6888 return marquee.mScroll / getHorizontalFadingEdgeLength(); 6889 } else { 6890 return 0.0f; 6891 } 6892 } else if (getLineCount() == 1) { 6893 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 6894 case Gravity.LEFT: 6895 return 0.0f; 6896 case Gravity.RIGHT: 6897 return (mLayout.getLineRight(0) - (mRight - mLeft) - 6898 getCompoundPaddingLeft() - getCompoundPaddingRight() - 6899 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 6900 case Gravity.CENTER_HORIZONTAL: 6901 return 0.0f; 6902 } 6903 } 6904 } 6905 return super.getLeftFadingEdgeStrength(); 6906 } 6907 6908 @Override 6909 protected float getRightFadingEdgeStrength() { 6910 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6911 if (mMarquee != null && !mMarquee.isStopped()) { 6912 final Marquee marquee = mMarquee; 6913 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 6914 } else if (getLineCount() == 1) { 6915 switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 6916 case Gravity.LEFT: 6917 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 6918 getCompoundPaddingRight(); 6919 final float lineWidth = mLayout.getLineWidth(0); 6920 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 6921 case Gravity.RIGHT: 6922 return 0.0f; 6923 case Gravity.CENTER_HORIZONTAL: 6924 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 6925 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 6926 getHorizontalFadingEdgeLength(); 6927 } 6928 } 6929 } 6930 return super.getRightFadingEdgeStrength(); 6931 } 6932 6933 @Override 6934 protected int computeHorizontalScrollRange() { 6935 if (mLayout != null) 6936 return mLayout.getWidth(); 6937 6938 return super.computeHorizontalScrollRange(); 6939 } 6940 6941 @Override 6942 protected int computeVerticalScrollRange() { 6943 if (mLayout != null) 6944 return mLayout.getHeight(); 6945 6946 return super.computeVerticalScrollRange(); 6947 } 6948 6949 @Override 6950 protected int computeVerticalScrollExtent() { 6951 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 6952 } 6953 6954 public enum BufferType { 6955 NORMAL, SPANNABLE, EDITABLE, 6956 } 6957 6958 /** 6959 * Returns the TextView_textColor attribute from the 6960 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 6961 * from the TextView_textAppearance attribute, if TextView_textColor 6962 * was not set directly. 6963 */ 6964 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 6965 ColorStateList colors; 6966 colors = attrs.getColorStateList(com.android.internal.R.styleable. 6967 TextView_textColor); 6968 6969 if (colors == null) { 6970 int ap = attrs.getResourceId(com.android.internal.R.styleable. 6971 TextView_textAppearance, -1); 6972 if (ap != -1) { 6973 TypedArray appearance; 6974 appearance = context.obtainStyledAttributes(ap, 6975 com.android.internal.R.styleable.TextAppearance); 6976 colors = appearance.getColorStateList(com.android.internal.R.styleable. 6977 TextAppearance_textColor); 6978 appearance.recycle(); 6979 } 6980 } 6981 6982 return colors; 6983 } 6984 6985 /** 6986 * Returns the default color from the TextView_textColor attribute 6987 * from the AttributeSet, if set, or the default color from the 6988 * TextAppearance_textColor from the TextView_textAppearance attribute, 6989 * if TextView_textColor was not set directly. 6990 */ 6991 public static int getTextColor(Context context, 6992 TypedArray attrs, 6993 int def) { 6994 ColorStateList colors = getTextColors(context, attrs); 6995 6996 if (colors == null) { 6997 return def; 6998 } else { 6999 return colors.getDefaultColor(); 7000 } 7001 } 7002 7003 @Override 7004 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7005 switch (keyCode) { 7006 case KeyEvent.KEYCODE_A: 7007 if (canSelectAll()) { 7008 return onTextContextMenuItem(ID_SELECT_ALL); 7009 } 7010 7011 break; 7012 7013 case KeyEvent.KEYCODE_X: 7014 if (canCut()) { 7015 return onTextContextMenuItem(ID_CUT); 7016 } 7017 7018 break; 7019 7020 case KeyEvent.KEYCODE_C: 7021 if (canCopy()) { 7022 return onTextContextMenuItem(ID_COPY); 7023 } 7024 7025 break; 7026 7027 case KeyEvent.KEYCODE_V: 7028 if (canPaste()) { 7029 return onTextContextMenuItem(ID_PASTE); 7030 } 7031 7032 break; 7033 } 7034 7035 return super.onKeyShortcut(keyCode, event); 7036 } 7037 7038 private boolean canSelectAll() { 7039 return canSelectText() && mText.length() != 0; 7040 } 7041 7042 private boolean canSelectText() { 7043 // prepareCursorController() relies on this method. 7044 // If you change this condition, make sure prepareCursorController is called anywhere 7045 // the value of this condition might be changed. 7046 return (mText instanceof Spannable && 7047 mMovement != null && 7048 mMovement.canSelectArbitrarily()); 7049 } 7050 7051 private boolean canCut() { 7052 if (mTransformation instanceof PasswordTransformationMethod) { 7053 return false; 7054 } 7055 7056 if (mText.length() > 0 && hasSelection()) { 7057 if (mText instanceof Editable && mInput != null) { 7058 return true; 7059 } 7060 } 7061 7062 return false; 7063 } 7064 7065 private boolean canCopy() { 7066 if (mTransformation instanceof PasswordTransformationMethod) { 7067 return false; 7068 } 7069 7070 if (mText.length() > 0 && hasSelection()) { 7071 return true; 7072 } 7073 7074 return false; 7075 } 7076 7077 private boolean canPaste() { 7078 return (mText instanceof Editable && 7079 mInput != null && 7080 getSelectionStart() >= 0 && 7081 getSelectionEnd() >= 0 && 7082 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 7083 hasText()); 7084 } 7085 7086 /** 7087 * Returns the offsets delimiting the 'word' located at position offset. 7088 * 7089 * @param offset An offset in the text. 7090 * @return The offsets for the start and end of the word located at <code>offset</code>. 7091 * The two ints offsets are packed in a long, with the starting offset shifted by 32 bits. 7092 * Returns a negative value if no valid word was found. 7093 */ 7094 private long getWordLimitsAt(int offset) { 7095 /* 7096 * Quick return if the input type is one where adding words 7097 * to the dictionary doesn't make any sense. 7098 */ 7099 int klass = mInputType & InputType.TYPE_MASK_CLASS; 7100 if (klass == InputType.TYPE_CLASS_NUMBER || 7101 klass == InputType.TYPE_CLASS_PHONE || 7102 klass == InputType.TYPE_CLASS_DATETIME) { 7103 return -1; 7104 } 7105 7106 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 7107 if (variation == InputType.TYPE_TEXT_VARIATION_URI || 7108 variation == InputType.TYPE_TEXT_VARIATION_PASSWORD || 7109 variation == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD || 7110 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 7111 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 7112 return -1; 7113 } 7114 7115 int len = mText.length(); 7116 int end = Math.min(offset, len); 7117 7118 if (end < 0) { 7119 return -1; 7120 } 7121 7122 int start = end; 7123 7124 for (; start > 0; start--) { 7125 char c = mTransformed.charAt(start - 1); 7126 int type = Character.getType(c); 7127 7128 if (c != '\'' && 7129 type != Character.UPPERCASE_LETTER && 7130 type != Character.LOWERCASE_LETTER && 7131 type != Character.TITLECASE_LETTER && 7132 type != Character.MODIFIER_LETTER && 7133 type != Character.DECIMAL_DIGIT_NUMBER) { 7134 break; 7135 } 7136 } 7137 7138 for (; end < len; end++) { 7139 char c = mTransformed.charAt(end); 7140 int type = Character.getType(c); 7141 7142 if (c != '\'' && 7143 type != Character.UPPERCASE_LETTER && 7144 type != Character.LOWERCASE_LETTER && 7145 type != Character.TITLECASE_LETTER && 7146 type != Character.MODIFIER_LETTER && 7147 type != Character.DECIMAL_DIGIT_NUMBER) { 7148 break; 7149 } 7150 } 7151 7152 if (start == end) { 7153 return -1; 7154 } 7155 7156 if (end - start > 48) { 7157 return -1; 7158 } 7159 7160 boolean hasLetter = false; 7161 for (int i = start; i < end; i++) { 7162 if (Character.isLetter(mTransformed.charAt(i))) { 7163 hasLetter = true; 7164 break; 7165 } 7166 } 7167 7168 if (!hasLetter) { 7169 return -1; 7170 } 7171 7172 // Two ints packed in a long 7173 return (((long) start) << 32) | end; 7174 } 7175 7176 private void selectCurrentWord() { 7177 // In case selection mode is started after an orientation change or after a select all, 7178 // use the current selection instead of creating one 7179 if (hasSelection()) { 7180 return; 7181 } 7182 7183 int selectionStart, selectionEnd; 7184 7185 // selectionModifierCursorController is not null at that point 7186 SelectionModifierCursorController selectionModifierCursorController = 7187 ((SelectionModifierCursorController) mSelectionModifierCursorController); 7188 int minOffset = selectionModifierCursorController.getMinTouchOffset(); 7189 int maxOffset = selectionModifierCursorController.getMaxTouchOffset(); 7190 7191 if (minOffset == maxOffset) { 7192 int offset = Math.max(0, Math.min(minOffset, mTransformed.length())); 7193 7194 // Tolerance, number of charaters around tapped position 7195 final int range = 1; 7196 final int max = mTransformed.length() - 1; 7197 7198 // 'Smart' word selection: detect position between words 7199 for (int i = -range; i <= range; i++) { 7200 int index = offset + i; 7201 if (index >= 0 && index <= max) { 7202 if (Character.isSpaceChar(mTransformed.charAt(index))) { 7203 // Select current space 7204 selectionStart = index; 7205 selectionEnd = selectionStart + 1; 7206 7207 // Extend selection to maximum space range 7208 while (selectionStart > 0 && 7209 Character.isSpaceChar(mTransformed.charAt(selectionStart - 1))) { 7210 selectionStart--; 7211 } 7212 while (selectionEnd < max && 7213 Character.isSpaceChar(mTransformed.charAt(selectionEnd))) { 7214 selectionEnd++; 7215 } 7216 7217 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 7218 return; 7219 } 7220 } 7221 } 7222 7223 // 'Smart' word selection: detect position at beginning or end of text. 7224 if (offset <= range) { 7225 Selection.setSelection((Spannable) mText, 0, 0); 7226 return; 7227 } 7228 if (offset >= (max - range)) { 7229 Selection.setSelection((Spannable) mText, max + 1, max + 1); 7230 return; 7231 } 7232 } 7233 7234 long wordLimits = getWordLimitsAt(minOffset); 7235 if (wordLimits >= 0) { 7236 selectionStart = (int) (wordLimits >>> 32); 7237 } else { 7238 selectionStart = Math.max(minOffset - 5, 0); 7239 } 7240 7241 wordLimits = getWordLimitsAt(maxOffset); 7242 if (wordLimits >= 0) { 7243 selectionEnd = (int) (wordLimits & 0x00000000FFFFFFFFL); 7244 } else { 7245 selectionEnd = Math.min(maxOffset + 5, mText.length()); 7246 } 7247 7248 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 7249 } 7250 7251 private String getWordForDictionary() { 7252 if (mLastTouchOffset < 0) { 7253 return null; 7254 } 7255 7256 long wordLimits = getWordLimitsAt(mLastTouchOffset); 7257 if (wordLimits >= 0) { 7258 int start = (int) (wordLimits >>> 32); 7259 int end = (int) (wordLimits & 0x00000000FFFFFFFFL); 7260 return mTransformed.subSequence(start, end).toString(); 7261 } else { 7262 return null; 7263 } 7264 } 7265 7266 @Override 7267 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 7268 if (!isShown()) { 7269 return false; 7270 } 7271 7272 final boolean isPassword = isPasswordInputType(mInputType); 7273 7274 if (!isPassword) { 7275 CharSequence text = getText(); 7276 if (TextUtils.isEmpty(text)) { 7277 text = getHint(); 7278 } 7279 if (!TextUtils.isEmpty(text)) { 7280 if (text.length() > AccessibilityEvent.MAX_TEXT_LENGTH) { 7281 text = text.subSequence(0, AccessibilityEvent.MAX_TEXT_LENGTH + 1); 7282 } 7283 event.getText().add(text); 7284 } 7285 } else { 7286 event.setPassword(isPassword); 7287 } 7288 return false; 7289 } 7290 7291 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 7292 int fromIndex, int removedCount, int addedCount) { 7293 AccessibilityEvent event = 7294 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 7295 event.setFromIndex(fromIndex); 7296 event.setRemovedCount(removedCount); 7297 event.setAddedCount(addedCount); 7298 event.setBeforeText(beforeText); 7299 sendAccessibilityEventUnchecked(event); 7300 } 7301 7302 @Override 7303 protected void onCreateContextMenu(ContextMenu menu) { 7304 super.onCreateContextMenu(menu); 7305 boolean added = false; 7306 7307 if (mIsInTextSelectionMode) { 7308 MenuHandler handler = new MenuHandler(); 7309 7310 if (canCut()) { 7311 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 7312 setOnMenuItemClickListener(handler). 7313 setAlphabeticShortcut('x'); 7314 added = true; 7315 } 7316 7317 if (canCopy()) { 7318 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 7319 setOnMenuItemClickListener(handler). 7320 setAlphabeticShortcut('c'); 7321 added = true; 7322 } 7323 7324 if (canPaste()) { 7325 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 7326 setOnMenuItemClickListener(handler). 7327 setAlphabeticShortcut('v'); 7328 added = true; 7329 } 7330 } else { 7331 /* 7332 if (!isFocused()) { 7333 if (isFocusable() && mInput != null) { 7334 if (canCopy()) { 7335 MenuHandler handler = new MenuHandler(); 7336 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 7337 setOnMenuItemClickListener(handler). 7338 setAlphabeticShortcut('c'); 7339 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 7340 } 7341 } 7342 7343 //return; 7344 } 7345 */ 7346 MenuHandler handler = new MenuHandler(); 7347 7348 if (canSelectText()) { 7349 menu.add(0, ID_START_SELECTING_TEXT, 0, com.android.internal.R.string.selectText). 7350 setOnMenuItemClickListener(handler); 7351 added = true; 7352 } 7353 7354 if (canSelectAll()) { 7355 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 7356 setOnMenuItemClickListener(handler). 7357 setAlphabeticShortcut('a'); 7358 added = true; 7359 } 7360 7361 if (mText instanceof Spanned) { 7362 int selStart = getSelectionStart(); 7363 int selEnd = getSelectionEnd(); 7364 7365 int min = Math.min(selStart, selEnd); 7366 int max = Math.max(selStart, selEnd); 7367 7368 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, 7369 URLSpan.class); 7370 if (urls.length == 1) { 7371 menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl). 7372 setOnMenuItemClickListener(handler); 7373 added = true; 7374 } 7375 } 7376 7377 // Paste location is too imprecise. Only allow on empty text fields. 7378 if (canPaste() && textIsOnlySpaces()) { 7379 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 7380 setOnMenuItemClickListener(handler). 7381 setAlphabeticShortcut('v'); 7382 added = true; 7383 } 7384 7385 if (isInputMethodTarget()) { 7386 menu.add(1, ID_SWITCH_INPUT_METHOD, 0, com.android.internal.R.string.inputMethod). 7387 setOnMenuItemClickListener(handler); 7388 added = true; 7389 } 7390 7391 String word = getWordForDictionary(); 7392 if (word != null) { 7393 menu.add(1, ID_ADD_TO_DICTIONARY, 0, 7394 getContext().getString(com.android.internal.R.string.addToDictionary, word)). 7395 setOnMenuItemClickListener(handler); 7396 added = true; 7397 7398 } 7399 } 7400 7401 if (added) { 7402 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 7403 } 7404 } 7405 7406 private boolean textIsOnlySpaces() { 7407 final int length = mTransformed.length(); 7408 for (int i = 0; i < length; i++) { 7409 if (!Character.isSpaceChar(mTransformed.charAt(i))) { 7410 return false; 7411 } 7412 } 7413 return true; 7414 } 7415 7416 /** 7417 * Returns whether this text view is a current input method target. The 7418 * default implementation just checks with {@link InputMethodManager}. 7419 */ 7420 public boolean isInputMethodTarget() { 7421 InputMethodManager imm = InputMethodManager.peekInstance(); 7422 return imm != null && imm.isActive(this); 7423 } 7424 7425 // Context menu entries 7426 private static final int ID_SELECT_ALL = android.R.id.selectAll; 7427 private static final int ID_START_SELECTING_TEXT = android.R.id.startSelectingText; 7428 private static final int ID_CUT = android.R.id.cut; 7429 private static final int ID_COPY = android.R.id.copy; 7430 private static final int ID_PASTE = android.R.id.paste; 7431 private static final int ID_COPY_URL = android.R.id.copyUrl; 7432 private static final int ID_SWITCH_INPUT_METHOD = android.R.id.switchInputMethod; 7433 private static final int ID_ADD_TO_DICTIONARY = android.R.id.addToDictionary; 7434 7435 private class MenuHandler implements MenuItem.OnMenuItemClickListener { 7436 public boolean onMenuItemClick(MenuItem item) { 7437 return onTextContextMenuItem(item.getItemId()); 7438 } 7439 } 7440 7441 /** 7442 * Called when a context menu option for the text view is selected. Currently 7443 * this will be one of: {@link android.R.id#selectAll}, 7444 * {@link android.R.id#startSelectingText}, 7445 * {@link android.R.id#cut}, {@link android.R.id#copy}, 7446 * {@link android.R.id#paste}, {@link android.R.id#copyUrl}, 7447 * or {@link android.R.id#switchInputMethod}. 7448 */ 7449 public boolean onTextContextMenuItem(int id) { 7450 int min = 0; 7451 int max = mText.length(); 7452 7453 if (isFocused()) { 7454 final int selStart = getSelectionStart(); 7455 final int selEnd = getSelectionEnd(); 7456 7457 min = Math.max(0, Math.min(selStart, selEnd)); 7458 max = Math.max(0, Math.max(selStart, selEnd)); 7459 } 7460 7461 ClipboardManager clip = (ClipboardManager)getContext() 7462 .getSystemService(Context.CLIPBOARD_SERVICE); 7463 7464 switch (id) { 7465 case ID_SELECT_ALL: 7466 Selection.setSelection((Spannable) mText, 0, mText.length()); 7467 startTextSelectionMode(); 7468 return true; 7469 7470 case ID_START_SELECTING_TEXT: 7471 startTextSelectionMode(); 7472 return true; 7473 7474 case ID_CUT: 7475 clip.setText(mTransformed.subSequence(min, max)); 7476 ((Editable) mText).delete(min, max); 7477 stopTextSelectionMode(); 7478 return true; 7479 7480 case ID_COPY: 7481 clip.setText(mTransformed.subSequence(min, max)); 7482 stopTextSelectionMode(); 7483 return true; 7484 7485 case ID_PASTE: 7486 CharSequence paste = clip.getText(); 7487 7488 if (paste != null && paste.length() > 0) { 7489 // Paste adds/removes spaces before or after insertion as needed. 7490 7491 if (Character.isSpaceChar(paste.charAt(0))) { 7492 if (min > 0 && Character.isSpaceChar(mTransformed.charAt(min - 1))) { 7493 // Two spaces at beginning of paste: remove one 7494 ((Editable) mText).replace(min - 1, min, ""); 7495 min = min - 1; 7496 max = max - 1; 7497 } 7498 } else { 7499 if (min > 0 && !Character.isSpaceChar(mTransformed.charAt(min - 1))) { 7500 // No space at beginning of paste: add one 7501 ((Editable) mText).replace(min, min, " "); 7502 min = min + 1; 7503 max = max + 1; 7504 } 7505 } 7506 7507 if (Character.isSpaceChar(paste.charAt(paste.length() - 1))) { 7508 if (max < mText.length() && Character.isSpaceChar(mTransformed.charAt(max))) { 7509 // Two spaces at end of paste: remove one 7510 ((Editable) mText).replace(max, max + 1, ""); 7511 } 7512 } else { 7513 if (max < mText.length() && !Character.isSpaceChar(mTransformed.charAt(max))) { 7514 // No space at end of paste: add one 7515 ((Editable) mText).replace(max, max, " "); 7516 } 7517 } 7518 7519 Selection.setSelection((Spannable) mText, max); 7520 ((Editable) mText).replace(min, max, paste); 7521 stopTextSelectionMode(); 7522 } 7523 return true; 7524 7525 case ID_COPY_URL: 7526 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class); 7527 if (urls.length == 1) { 7528 clip.setText(urls[0].getURL()); 7529 } 7530 return true; 7531 7532 case ID_SWITCH_INPUT_METHOD: 7533 InputMethodManager imm = InputMethodManager.peekInstance(); 7534 if (imm != null) { 7535 imm.showInputMethodPicker(); 7536 } 7537 return true; 7538 7539 case ID_ADD_TO_DICTIONARY: 7540 String word = getWordForDictionary(); 7541 7542 if (word != null) { 7543 Intent i = new Intent("com.android.settings.USER_DICTIONARY_INSERT"); 7544 i.putExtra("word", word); 7545 i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 7546 getContext().startActivity(i); 7547 } 7548 return true; 7549 } 7550 7551 return false; 7552 } 7553 7554 @Override 7555 public boolean performLongClick() { 7556 if (super.performLongClick()) { 7557 mEatTouchRelease = true; 7558 return true; 7559 } 7560 7561 return false; 7562 } 7563 7564 private void startTextSelectionMode() { 7565 if (!mIsInTextSelectionMode) { 7566 if (mSelectionModifierCursorController == null) { 7567 Log.w(LOG_TAG, "TextView has no selection controller. Action mode cancelled."); 7568 return; 7569 } 7570 7571 if (!requestFocus()) { 7572 return; 7573 } 7574 7575 selectCurrentWord(); 7576 mSelectionModifierCursorController.show(); 7577 mIsInTextSelectionMode = true; 7578 } 7579 } 7580 7581 /** 7582 * Same as {@link #stopTextSelectionMode()}, except that there is no cursor controller 7583 * fade out animation. Needed since the drawable and their alpha values are shared by all 7584 * TextViews. Switching from one TextView to another would fade the cursor controllers in the 7585 * new one otherwise. 7586 */ 7587 private void terminateTextSelectionMode() { 7588 stopTextSelectionMode(); 7589 if (mSelectionModifierCursorController != null) { 7590 SelectionModifierCursorController selectionModifierCursorController = 7591 (SelectionModifierCursorController) mSelectionModifierCursorController; 7592 selectionModifierCursorController.cancelFadeOutAnimation(); 7593 } 7594 } 7595 7596 private void stopTextSelectionMode() { 7597 if (mIsInTextSelectionMode) { 7598 Selection.setSelection((Spannable) mText, getSelectionEnd()); 7599 if (mSelectionModifierCursorController != null) { 7600 mSelectionModifierCursorController.hide(); 7601 } 7602 7603 mIsInTextSelectionMode = false; 7604 } 7605 } 7606 7607 /** 7608 * A CursorController instance can be used to control a cursor in the text. 7609 * 7610 * It can be passed to an {@link ArrowKeyMovementMethod} which can intercepts events 7611 * and send them to this object instead of the cursor. 7612 * 7613 * @hide 7614 */ 7615 public interface CursorController { 7616 /* Cursor fade-out animation duration, in milliseconds. */ 7617 static final int FADE_OUT_DURATION = 400; 7618 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(int x, int y); 7640 7641 public void updatePosition(); 7642 7643 /** 7644 * The controller and the cursor's positions can be link by a fixed offset, 7645 * computed when the controller is touched, and then maintained as it moves 7646 * @return Horizontal offset between the controller and the cursor. 7647 */ 7648 public float getOffsetX(); 7649 7650 /** 7651 * @return Vertical offset between the controller and the cursor. 7652 */ 7653 public float getOffsetY(); 7654 7655 /** 7656 * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller 7657 * a chance to become active and/or visible. 7658 * @param event The touch event 7659 */ 7660 public boolean onTouchEvent(MotionEvent event); 7661 } 7662 7663 private class HandleView extends View { 7664 private boolean mPositionOnTop = false; 7665 private Drawable mDrawable; 7666 private PopupWindow mContainer; 7667 private int mPositionX; 7668 private int mPositionY; 7669 private CursorController mController; 7670 private boolean mIsDragging; 7671 7672 public HandleView(CursorController controller, Drawable handle) { 7673 super(TextView.this.mContext); 7674 mController = controller; 7675 mDrawable = handle; 7676 mContainer = new PopupWindow(TextView.this.mContext, null, 7677 com.android.internal.R.attr.textSelectHandleWindowStyle); 7678 } 7679 7680 @Override 7681 public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 7682 setMeasuredDimension(mDrawable.getIntrinsicWidth(), 7683 mDrawable.getIntrinsicHeight()); 7684 } 7685 7686 public void show() { 7687 if (!isPositionInBounds()) { 7688 hide(); 7689 return; 7690 } 7691 mContainer.setContentView(this); 7692 final int[] coords = mTempCoords; 7693 TextView.this.getLocationOnScreen(coords); 7694 coords[0] += mPositionX; 7695 coords[1] += mPositionY; 7696 mContainer.showAtLocation(TextView.this, 0, coords[0], coords[1]); 7697 } 7698 7699 public void hide() { 7700 mIsDragging = false; 7701 mContainer.dismiss(); 7702 } 7703 7704 public boolean isShowing() { 7705 return mContainer.isShowing(); 7706 } 7707 7708 private boolean isPositionInBounds() { 7709 final int extendedPaddingTop = getExtendedPaddingTop(); 7710 final int extendedPaddingBottom = getExtendedPaddingBottom(); 7711 final int compoundPaddingLeft = getCompoundPaddingLeft(); 7712 final int compoundPaddingRight = getCompoundPaddingRight(); 7713 7714 final TextView hostView = TextView.this; 7715 final int right = hostView.mRight; 7716 final int left = hostView.mLeft; 7717 final int bottom = hostView.mBottom; 7718 final int top = hostView.mTop; 7719 7720 final int clipLeft = left + compoundPaddingLeft; 7721 final int clipTop = top + extendedPaddingTop; 7722 final int clipRight = right - compoundPaddingRight; 7723 final int clipBottom = bottom - extendedPaddingBottom; 7724 7725 final int handleWidth = mDrawable.getIntrinsicWidth(); 7726 return mPositionX >= clipLeft - handleWidth * 0.75f && 7727 mPositionX <= clipRight + handleWidth * 0.25f && 7728 mPositionY >= clipTop && mPositionY <= clipBottom; 7729 } 7730 7731 private void moveTo(int x, int y) { 7732 mPositionX = x - TextView.this.mScrollX; 7733 mPositionY = y - TextView.this.mScrollY; 7734 if (isPositionInBounds()) { 7735 if (mContainer.isShowing()){ 7736 final int[] coords = mTempCoords; 7737 TextView.this.getLocationOnScreen(coords); 7738 coords[0] += mPositionX; 7739 coords[1] += mPositionY; 7740 mContainer.update(coords[0], coords[1], mRight - mLeft, mBottom - mTop); 7741 } else { 7742 show(); 7743 } 7744 } else { 7745 hide(); 7746 } 7747 } 7748 7749 @Override 7750 public void onDraw(Canvas c) { 7751 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 7752 if (mPositionOnTop) { 7753 c.save(); 7754 c.rotate(180, (mRight - mLeft) / 2, (mBottom - mTop) / 2); 7755 mDrawable.draw(c); 7756 c.restore(); 7757 } else { 7758 mDrawable.draw(c); 7759 } 7760 } 7761 7762 @Override 7763 public boolean onTouchEvent(MotionEvent ev) { 7764 switch (ev.getActionMasked()) { 7765 case MotionEvent.ACTION_DOWN: 7766 mIsDragging = true; 7767 break; 7768 7769 case MotionEvent.ACTION_MOVE: 7770 final float rawX = ev.getRawX(); 7771 final float rawY = ev.getRawY(); 7772 final int[] coords = mTempCoords; 7773 TextView.this.getLocationOnScreen(coords); 7774 final int x = (int) (rawX - coords[0] + 0.5f); 7775 final int y = (int) (rawY - coords[1] + 0.5f); 7776 mController.updatePosition(x, y); 7777 break; 7778 7779 case MotionEvent.ACTION_UP: 7780 case MotionEvent.ACTION_CANCEL: 7781 mIsDragging = false; 7782 } 7783 return true; 7784 } 7785 7786 public boolean isDragging() { 7787 return mIsDragging; 7788 } 7789 7790 void positionAtCursor(final int offset, boolean bottom) { 7791 final int width = mDrawable.getIntrinsicWidth(); 7792 final int height = mDrawable.getIntrinsicHeight(); 7793 final int line = mLayout.getLineForOffset(offset); 7794 final int lineTop = mLayout.getLineTop(line); 7795 final int lineBottom = mLayout.getLineBottom(line); 7796 7797 final Rect bounds = sCursorControllerTempRect; 7798 bounds.left = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0) 7799 + TextView.this.mScrollX; 7800 bounds.top = (bottom ? lineBottom : lineTop) + TextView.this.mScrollY; 7801 7802 bounds.right = bounds.left + width; 7803 bounds.bottom = bounds.top + height; 7804 7805 convertFromViewportToContentCoordinates(bounds); 7806 moveTo(bounds.left, bounds.top); 7807 } 7808 } 7809 7810 class InsertionPointCursorController implements CursorController { 7811 private static final int DELAY_BEFORE_FADE_OUT = 4100; 7812 7813 // The cursor controller image 7814 private final HandleView mHandle; 7815 // Offset between finger hot point on cursor controller and actual cursor 7816 private float mOffsetX, mOffsetY; 7817 7818 private final Runnable mHider = new Runnable() { 7819 public void run() { 7820 hide(); 7821 } 7822 }; 7823 7824 InsertionPointCursorController() { 7825 Resources res = mContext.getResources(); 7826 mHandle = new HandleView(this, res.getDrawable(mTextSelectHandleRes)); 7827 } 7828 7829 public void show() { 7830 updatePosition(); 7831 mHandle.show(); 7832 hideDelayed(DELAY_BEFORE_FADE_OUT); 7833 } 7834 7835 public void hide() { 7836 mHandle.hide(); 7837 TextView.this.removeCallbacks(mHider); 7838 } 7839 7840 private void hideDelayed(int msec) { 7841 TextView.this.removeCallbacks(mHider); 7842 TextView.this.postDelayed(mHider, msec); 7843 } 7844 7845 public boolean isShowing() { 7846 return mHandle.isShowing(); 7847 } 7848 7849 public void updatePosition(int x, int y) { 7850 final int previousOffset = getSelectionStart(); 7851 int offset = getHysteresisOffset(x, y, previousOffset); 7852 7853 if (offset != previousOffset) { 7854 Selection.setSelection((Spannable) mText, offset); 7855 updatePosition(); 7856 } 7857 hideDelayed(DELAY_BEFORE_FADE_OUT); 7858 } 7859 7860 public void updatePosition() { 7861 final int offset = getSelectionStart(); 7862 7863 if (offset < 0) { 7864 // Should never happen, safety check. 7865 Log.w(LOG_TAG, "Update cursor controller position called with no cursor"); 7866 hide(); 7867 return; 7868 } 7869 7870 mHandle.positionAtCursor(offset, true); 7871 } 7872 7873 public float getOffsetX() { 7874 return mOffsetX; 7875 } 7876 7877 public float getOffsetY() { 7878 return mOffsetY; 7879 } 7880 7881 public boolean onTouchEvent(MotionEvent ev) { 7882 return false; 7883 } 7884 } 7885 7886 class SelectionModifierCursorController implements CursorController { 7887 // The cursor controller images 7888 private HandleView mStartHandle, mEndHandle; 7889 // Offset between finger hot point on active cursor controller and actual cursor 7890 private float mOffsetX, mOffsetY; 7891 // The offsets of that last touch down event. Remembered to start selection there. 7892 private int mMinTouchOffset, mMaxTouchOffset; 7893 // Whether selection anchors are active 7894 private boolean mIsShowing; 7895 7896 SelectionModifierCursorController() { 7897 Resources res = mContext.getResources(); 7898 mStartHandle = new HandleView(this, res.getDrawable(mTextSelectHandleLeftRes)); 7899 mEndHandle = new HandleView(this, res.getDrawable(mTextSelectHandleRightRes)); 7900 } 7901 7902 public void show() { 7903 mIsShowing = true; 7904 updatePosition(); 7905 mStartHandle.show(); 7906 mEndHandle.show(); 7907 hideInsertionPointCursorController(); 7908 } 7909 7910 public void hide() { 7911 mStartHandle.hide(); 7912 mEndHandle.hide(); 7913 mIsShowing = false; 7914 } 7915 7916 public boolean isShowing() { 7917 return mIsShowing; 7918 } 7919 7920 public void cancelFadeOutAnimation() { 7921 hide(); 7922 } 7923 7924 public void updatePosition(int x, int y) { 7925 int selectionStart = getSelectionStart(); 7926 int selectionEnd = getSelectionEnd(); 7927 7928 final int previousOffset = mStartHandle.isDragging() ? selectionStart : selectionEnd; 7929 int offset = getHysteresisOffset(x, y, previousOffset); 7930 7931 // Handle the case where start and end are swapped, making sure start <= end 7932 if (mStartHandle.isDragging()) { 7933 if (offset <= selectionEnd) { 7934 if (selectionStart == offset) { 7935 return; // no change, no need to redraw; 7936 } 7937 selectionStart = offset; 7938 } else { 7939 selectionStart = selectionEnd; 7940 selectionEnd = offset; 7941 HandleView temp = mStartHandle; 7942 mStartHandle = mEndHandle; 7943 mEndHandle = temp; 7944 } 7945 } else { 7946 if (offset >= selectionStart) { 7947 if (selectionEnd == offset) { 7948 return; // no change, no need to redraw; 7949 } 7950 selectionEnd = offset; 7951 } else { 7952 selectionEnd = selectionStart; 7953 selectionStart = offset; 7954 HandleView temp = mStartHandle; 7955 mStartHandle = mEndHandle; 7956 mEndHandle = temp; 7957 } 7958 } 7959 7960 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 7961 updatePosition(); 7962 } 7963 7964 public void updatePosition() { 7965 final int selectionStart = getSelectionStart(); 7966 final int selectionEnd = getSelectionEnd(); 7967 7968 if ((selectionStart < 0) || (selectionEnd < 0)) { 7969 // Should never happen, safety check. 7970 Log.w(LOG_TAG, "Update selection controller position called with no cursor"); 7971 hide(); 7972 return; 7973 } 7974 7975 boolean oneLineSelection = mLayout.getLineForOffset(selectionStart) == 7976 mLayout.getLineForOffset(selectionEnd); 7977 mStartHandle.positionAtCursor(selectionStart, oneLineSelection); 7978 mEndHandle.positionAtCursor(selectionEnd, true); 7979 } 7980 7981 public boolean onTouchEvent(MotionEvent event) { 7982 if (isFocused() && isTextEditable()) { 7983 switch (event.getActionMasked()) { 7984 case MotionEvent.ACTION_DOWN: 7985 final int x = (int) event.getX(); 7986 final int y = (int) event.getY(); 7987 7988 // Remember finger down position, to be able to start selection from there 7989 mMinTouchOffset = mMaxTouchOffset = mLastTouchOffset = getOffset(x, y); 7990 7991 break; 7992 7993 case MotionEvent.ACTION_POINTER_DOWN: 7994 case MotionEvent.ACTION_POINTER_UP: 7995 // Handle multi-point gestures. Keep min and max offset positions. 7996 // Only activated for devices that correctly handle multi-touch. 7997 if (mContext.getPackageManager().hasSystemFeature( 7998 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 7999 updateMinAndMaxOffsets(event); 8000 } 8001 break; 8002 } 8003 } 8004 return false; 8005 } 8006 8007 /** 8008 * @param event 8009 */ 8010 private void updateMinAndMaxOffsets(MotionEvent event) { 8011 int pointerCount = event.getPointerCount(); 8012 for (int index = 0; index < pointerCount; index++) { 8013 final int x = (int) event.getX(index); 8014 final int y = (int) event.getY(index); 8015 int offset = getOffset(x, y); 8016 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 8017 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 8018 } 8019 } 8020 8021 public int getMinTouchOffset() { 8022 return mMinTouchOffset; 8023 } 8024 8025 public int getMaxTouchOffset() { 8026 return mMaxTouchOffset; 8027 } 8028 8029 public float getOffsetX() { 8030 return mOffsetX; 8031 } 8032 8033 public float getOffsetY() { 8034 return mOffsetY; 8035 } 8036 8037 /** 8038 * @return true iff this controller is currently used to move the selection start. 8039 */ 8040 public boolean isSelectionStartDragged() { 8041 return mStartHandle.isDragging(); 8042 } 8043 } 8044 8045 private void hideInsertionPointCursorController() { 8046 if (mInsertionPointCursorController != null) { 8047 mInsertionPointCursorController.hide(); 8048 } 8049 } 8050 8051 private void hideControllers() { 8052 hideInsertionPointCursorController(); 8053 stopTextSelectionMode(); 8054 } 8055 8056 private int getOffsetForHorizontal(int line, int x) { 8057 x -= getTotalPaddingLeft(); 8058 // Clamp the position to inside of the view. 8059 x = Math.max(0, x); 8060 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 8061 x += getScrollX(); 8062 return getLayout().getOffsetForHorizontal(line, x); 8063 } 8064 8065 /** 8066 * Get the offset character closest to the specified absolute position. 8067 * 8068 * @param x The horizontal absolute position of a point on screen 8069 * @param y The vertical absolute position of a point on screen 8070 * @return the character offset for the character whose position is closest to the specified 8071 * position. Returns -1 if there is no layout. 8072 * 8073 * @hide 8074 */ 8075 public int getOffset(int x, int y) { 8076 if (getLayout() == null) return -1; 8077 8078 y -= getTotalPaddingTop(); 8079 // Clamp the position to inside of the view. 8080 y = Math.max(0, y); 8081 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 8082 y += getScrollY(); 8083 8084 final int line = getLayout().getLineForVertical(y); 8085 final int offset = getOffsetForHorizontal(line, x); 8086 return offset; 8087 } 8088 8089 int getHysteresisOffset(int x, int y, int previousOffset) { 8090 final Layout layout = getLayout(); 8091 if (layout == null) return -1; 8092 8093 y -= getTotalPaddingTop(); 8094 // Clamp the position to inside of the view. 8095 y = Math.max(0, y); 8096 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 8097 y += getScrollY(); 8098 8099 int line = getLayout().getLineForVertical(y); 8100 8101 final int previousLine = layout.getLineForOffset(previousOffset); 8102 final int previousLineTop = layout.getLineTop(previousLine); 8103 final int previousLineBottom = layout.getLineBottom(previousLine); 8104 final int hysteresisThreshold = (previousLineBottom - previousLineTop) / 2; 8105 8106 // If new line is just before or after previous line and y position is less than 8107 // hysteresisThreshold away from previous line, keep cursor on previous line. 8108 if (((line == previousLine + 1) && ((y - previousLineBottom) < hysteresisThreshold)) || 8109 ((line == previousLine - 1) && ((previousLineTop - y) < hysteresisThreshold))) { 8110 line = previousLine; 8111 } 8112 8113 return getOffsetForHorizontal(line, x); 8114 } 8115 8116 @ViewDebug.ExportedProperty 8117 private CharSequence mText; 8118 private CharSequence mTransformed; 8119 private BufferType mBufferType = BufferType.NORMAL; 8120 8121 private int mInputType = EditorInfo.TYPE_NULL; 8122 private CharSequence mHint; 8123 private Layout mHintLayout; 8124 8125 private KeyListener mInput; 8126 8127 private MovementMethod mMovement; 8128 private TransformationMethod mTransformation; 8129 private ChangeWatcher mChangeWatcher; 8130 8131 private ArrayList<TextWatcher> mListeners = null; 8132 8133 // display attributes 8134 private final TextPaint mTextPaint; 8135 private boolean mUserSetTextScaleX; 8136 private final Paint mHighlightPaint; 8137 private int mHighlightColor = 0xCC475925; 8138 private Layout mLayout; 8139 8140 private long mShowCursor; 8141 private Blink mBlink; 8142 private boolean mCursorVisible = true; 8143 8144 // Cursor Controllers. Null when disabled. 8145 private CursorController mInsertionPointCursorController; 8146 private CursorController mSelectionModifierCursorController; 8147 private boolean mIsInTextSelectionMode = false; 8148 private int mLastTouchOffset = -1; 8149 // Created once and shared by different CursorController helper methods. 8150 // Only one cursor controller is active at any time which prevent race conditions. 8151 private static Rect sCursorControllerTempRect = new Rect(); 8152 8153 private boolean mSelectAllOnFocus = false; 8154 8155 private int mGravity = Gravity.TOP | Gravity.LEFT; 8156 private boolean mHorizontallyScrolling; 8157 8158 private int mAutoLinkMask; 8159 private boolean mLinksClickable = true; 8160 8161 private float mSpacingMult = 1; 8162 private float mSpacingAdd = 0; 8163 8164 private static final int LINES = 1; 8165 private static final int EMS = LINES; 8166 private static final int PIXELS = 2; 8167 8168 private int mMaximum = Integer.MAX_VALUE; 8169 private int mMaxMode = LINES; 8170 private int mMinimum = 0; 8171 private int mMinMode = LINES; 8172 8173 private int mMaxWidth = Integer.MAX_VALUE; 8174 private int mMaxWidthMode = PIXELS; 8175 private int mMinWidth = 0; 8176 private int mMinWidthMode = PIXELS; 8177 8178 private boolean mSingleLine; 8179 private int mDesiredHeightAtMeasure = -1; 8180 private boolean mIncludePad = true; 8181 8182 // tmp primitives, so we don't alloc them on each draw 8183 private Path mHighlightPath; 8184 private boolean mHighlightPathBogus = true; 8185 private static final RectF sTempRect = new RectF(); 8186 8187 // XXX should be much larger 8188 private static final int VERY_WIDE = 16384; 8189 8190 private static final int BLINK = 500; 8191 8192 private static final int ANIMATED_SCROLL_GAP = 250; 8193 private long mLastScroll; 8194 private Scroller mScroller = null; 8195 8196 private BoringLayout.Metrics mBoring; 8197 private BoringLayout.Metrics mHintBoring; 8198 8199 private BoringLayout mSavedLayout, mSavedHintLayout; 8200 8201 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 8202 private InputFilter[] mFilters = NO_FILTERS; 8203 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 8204} 8205