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