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