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