TextView.java revision 83955ef12fb324fb3d407c5ea08769f267af7074
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 android.R; 20import android.content.ClipData; 21import android.content.ClipData.Item; 22import android.content.ClipboardManager; 23import android.content.Context; 24import android.content.pm.PackageManager; 25import android.content.res.ColorStateList; 26import android.content.res.Resources; 27import android.content.res.TypedArray; 28import android.content.res.XmlResourceParser; 29import android.graphics.Canvas; 30import android.graphics.Color; 31import android.graphics.Paint; 32import android.graphics.Path; 33import android.graphics.Rect; 34import android.graphics.RectF; 35import android.graphics.Typeface; 36import android.graphics.drawable.Drawable; 37import android.inputmethodservice.ExtractEditText; 38import android.net.Uri; 39import android.os.Bundle; 40import android.os.Handler; 41import android.os.Message; 42import android.os.Parcel; 43import android.os.Parcelable; 44import android.os.SystemClock; 45import android.text.BoringLayout; 46import android.text.DynamicLayout; 47import android.text.Editable; 48import android.text.GetChars; 49import android.text.GraphicsOperations; 50import android.text.InputFilter; 51import android.text.InputType; 52import android.text.Layout; 53import android.text.ParcelableSpan; 54import android.text.Selection; 55import android.text.SpanWatcher; 56import android.text.Spannable; 57import android.text.SpannableString; 58import android.text.SpannableStringBuilder; 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.method.WordIterator; 80import android.text.style.ClickableSpan; 81import android.text.style.ParagraphStyle; 82import android.text.style.SuggestionSpan; 83import android.text.style.TextAppearanceSpan; 84import android.text.style.URLSpan; 85import android.text.style.UnderlineSpan; 86import android.text.style.UpdateAppearance; 87import android.text.util.Linkify; 88import android.util.AttributeSet; 89import android.util.DisplayMetrics; 90import android.util.FloatMath; 91import android.util.Log; 92import android.util.TypedValue; 93import android.view.ActionMode; 94import android.view.ActionMode.Callback; 95import android.view.ContextMenu; 96import android.view.DragEvent; 97import android.view.Gravity; 98import android.view.HapticFeedbackConstants; 99import android.view.KeyCharacterMap; 100import android.view.KeyEvent; 101import android.view.LayoutInflater; 102import android.view.Menu; 103import android.view.MenuItem; 104import android.view.MotionEvent; 105import android.view.View; 106import android.view.ViewAncestor; 107import android.view.ViewConfiguration; 108import android.view.ViewDebug; 109import android.view.ViewGroup; 110import android.view.ViewGroup.LayoutParams; 111import android.view.ViewParent; 112import android.view.ViewTreeObserver; 113import android.view.WindowManager; 114import android.view.accessibility.AccessibilityEvent; 115import android.view.accessibility.AccessibilityManager; 116import android.view.accessibility.AccessibilityNodeInfo; 117import android.view.animation.AnimationUtils; 118import android.view.inputmethod.BaseInputConnection; 119import android.view.inputmethod.CompletionInfo; 120import android.view.inputmethod.CorrectionInfo; 121import android.view.inputmethod.EditorInfo; 122import android.view.inputmethod.ExtractedText; 123import android.view.inputmethod.ExtractedTextRequest; 124import android.view.inputmethod.InputConnection; 125import android.view.inputmethod.InputMethodManager; 126import android.widget.RemoteViews.RemoteView; 127 128import com.android.internal.util.FastMath; 129import com.android.internal.widget.EditableInputConnection; 130 131import org.xmlpull.v1.XmlPullParserException; 132 133import java.io.IOException; 134import java.lang.ref.WeakReference; 135import java.text.BreakIterator; 136import java.util.ArrayList; 137 138/** 139 * Displays text to the user and optionally allows them to edit it. A TextView 140 * is a complete text editor, however the basic class is configured to not 141 * allow editing; see {@link EditText} for a subclass that configures the text 142 * view for editing. 143 * 144 * <p> 145 * <b>XML attributes</b> 146 * <p> 147 * See {@link android.R.styleable#TextView TextView Attributes}, 148 * {@link android.R.styleable#View View Attributes} 149 * 150 * @attr ref android.R.styleable#TextView_text 151 * @attr ref android.R.styleable#TextView_bufferType 152 * @attr ref android.R.styleable#TextView_hint 153 * @attr ref android.R.styleable#TextView_textColor 154 * @attr ref android.R.styleable#TextView_textColorHighlight 155 * @attr ref android.R.styleable#TextView_textColorHint 156 * @attr ref android.R.styleable#TextView_textAppearance 157 * @attr ref android.R.styleable#TextView_textColorLink 158 * @attr ref android.R.styleable#TextView_textSize 159 * @attr ref android.R.styleable#TextView_textScaleX 160 * @attr ref android.R.styleable#TextView_typeface 161 * @attr ref android.R.styleable#TextView_textStyle 162 * @attr ref android.R.styleable#TextView_cursorVisible 163 * @attr ref android.R.styleable#TextView_maxLines 164 * @attr ref android.R.styleable#TextView_maxHeight 165 * @attr ref android.R.styleable#TextView_lines 166 * @attr ref android.R.styleable#TextView_height 167 * @attr ref android.R.styleable#TextView_minLines 168 * @attr ref android.R.styleable#TextView_minHeight 169 * @attr ref android.R.styleable#TextView_maxEms 170 * @attr ref android.R.styleable#TextView_maxWidth 171 * @attr ref android.R.styleable#TextView_ems 172 * @attr ref android.R.styleable#TextView_width 173 * @attr ref android.R.styleable#TextView_minEms 174 * @attr ref android.R.styleable#TextView_minWidth 175 * @attr ref android.R.styleable#TextView_gravity 176 * @attr ref android.R.styleable#TextView_scrollHorizontally 177 * @attr ref android.R.styleable#TextView_password 178 * @attr ref android.R.styleable#TextView_singleLine 179 * @attr ref android.R.styleable#TextView_selectAllOnFocus 180 * @attr ref android.R.styleable#TextView_includeFontPadding 181 * @attr ref android.R.styleable#TextView_maxLength 182 * @attr ref android.R.styleable#TextView_shadowColor 183 * @attr ref android.R.styleable#TextView_shadowDx 184 * @attr ref android.R.styleable#TextView_shadowDy 185 * @attr ref android.R.styleable#TextView_shadowRadius 186 * @attr ref android.R.styleable#TextView_autoLink 187 * @attr ref android.R.styleable#TextView_linksClickable 188 * @attr ref android.R.styleable#TextView_numeric 189 * @attr ref android.R.styleable#TextView_digits 190 * @attr ref android.R.styleable#TextView_phoneNumber 191 * @attr ref android.R.styleable#TextView_inputMethod 192 * @attr ref android.R.styleable#TextView_capitalize 193 * @attr ref android.R.styleable#TextView_autoText 194 * @attr ref android.R.styleable#TextView_editable 195 * @attr ref android.R.styleable#TextView_freezesText 196 * @attr ref android.R.styleable#TextView_ellipsize 197 * @attr ref android.R.styleable#TextView_drawableTop 198 * @attr ref android.R.styleable#TextView_drawableBottom 199 * @attr ref android.R.styleable#TextView_drawableRight 200 * @attr ref android.R.styleable#TextView_drawableLeft 201 * @attr ref android.R.styleable#TextView_drawablePadding 202 * @attr ref android.R.styleable#TextView_lineSpacingExtra 203 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 204 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 205 * @attr ref android.R.styleable#TextView_inputType 206 * @attr ref android.R.styleable#TextView_imeOptions 207 * @attr ref android.R.styleable#TextView_privateImeOptions 208 * @attr ref android.R.styleable#TextView_imeActionLabel 209 * @attr ref android.R.styleable#TextView_imeActionId 210 * @attr ref android.R.styleable#TextView_editorExtras 211 */ 212@RemoteView 213public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { 214 static final String LOG_TAG = "TextView"; 215 static final boolean DEBUG_EXTRACT = false; 216 217 private static final int PRIORITY = 100; 218 private int mCurrentAlpha = 255; 219 220 final int[] mTempCoords = new int[2]; 221 Rect mTempRect; 222 223 private ColorStateList mTextColor; 224 private int mCurTextColor; 225 private ColorStateList mHintTextColor; 226 private ColorStateList mLinkTextColor; 227 private int mCurHintTextColor; 228 private boolean mFreezesText; 229 private boolean mFrozenWithFocus; 230 private boolean mTemporaryDetach; 231 private boolean mDispatchTemporaryDetach; 232 233 private boolean mDiscardNextActionUp = false; 234 private boolean mIgnoreActionUpEvent = false; 235 236 private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); 237 private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); 238 239 private float mShadowRadius, mShadowDx, mShadowDy; 240 241 private static final int PREDRAW_NOT_REGISTERED = 0; 242 private static final int PREDRAW_PENDING = 1; 243 private static final int PREDRAW_DONE = 2; 244 private int mPreDrawState = PREDRAW_NOT_REGISTERED; 245 246 private TextUtils.TruncateAt mEllipsize = null; 247 248 // Enum for the "typeface" XML parameter. 249 // TODO: How can we get this from the XML instead of hardcoding it here? 250 private static final int SANS = 1; 251 private static final int SERIF = 2; 252 private static final int MONOSPACE = 3; 253 254 // Bitfield for the "numeric" XML parameter. 255 // TODO: How can we get this from the XML instead of hardcoding it here? 256 private static final int SIGNED = 2; 257 private static final int DECIMAL = 4; 258 259 class Drawables { 260 final Rect mCompoundRect = new Rect(); 261 Drawable mDrawableTop, mDrawableBottom, mDrawableLeft, mDrawableRight; 262 int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight; 263 int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight; 264 int mDrawablePadding; 265 } 266 private Drawables mDrawables; 267 268 private CharSequence mError; 269 private boolean mErrorWasChanged; 270 private ErrorPopup mPopup; 271 /** 272 * This flag is set if the TextView tries to display an error before it 273 * is attached to the window (so its position is still unknown). 274 * It causes the error to be shown later, when onAttachedToWindow() 275 * is called. 276 */ 277 private boolean mShowErrorAfterAttach; 278 279 private CharWrapper mCharWrapper = null; 280 281 private boolean mSelectionMoved = false; 282 private boolean mTouchFocusSelected = false; 283 284 private Marquee mMarquee; 285 private boolean mRestartMarquee; 286 287 private int mMarqueeRepeatLimit = 3; 288 289 class InputContentType { 290 int imeOptions = EditorInfo.IME_NULL; 291 String privateImeOptions; 292 CharSequence imeActionLabel; 293 int imeActionId; 294 Bundle extras; 295 OnEditorActionListener onEditorActionListener; 296 boolean enterDown; 297 } 298 InputContentType mInputContentType; 299 300 class InputMethodState { 301 Rect mCursorRectInWindow = new Rect(); 302 RectF mTmpRectF = new RectF(); 303 float[] mTmpOffset = new float[2]; 304 ExtractedTextRequest mExtracting; 305 final ExtractedText mTmpExtracted = new ExtractedText(); 306 int mBatchEditNesting; 307 boolean mCursorChanged; 308 boolean mSelectionModeChanged; 309 boolean mContentChanged; 310 int mChangedStart, mChangedEnd, mChangedDelta; 311 } 312 InputMethodState mInputMethodState; 313 314 private int mTextSelectHandleLeftRes; 315 private int mTextSelectHandleRightRes; 316 private int mTextSelectHandleRes; 317 private int mTextEditPasteWindowLayout, mTextEditSidePasteWindowLayout; 318 private int mTextEditNoPasteWindowLayout, mTextEditSideNoPasteWindowLayout; 319 320 private int mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout; 321 private int mTextEditSuggestionItemLayout; 322 private SuggestionsPopupWindow mSuggestionsPopupWindow; 323 private SuggestionRangeSpan mSuggestionRangeSpan; 324 private boolean mSuggestionsEnabled = true; 325 326 private int mCursorDrawableRes; 327 private final Drawable[] mCursorDrawable = new Drawable[2]; 328 private int mCursorCount; // Actual current number of used mCursorDrawable: 0, 1 or 2 329 330 private Drawable mSelectHandleLeft; 331 private Drawable mSelectHandleRight; 332 private Drawable mSelectHandleCenter; 333 334 private float mLastDownPositionX, mLastDownPositionY; 335 private Callback mCustomSelectionActionModeCallback; 336 337 private final int mSquaredTouchSlopDistance; 338 // Set when this TextView gained focus with some text selected. Will start selection mode. 339 private boolean mCreatedWithASelection = false; 340 341 private WordIterator mWordIterator; 342 343 /* 344 * Kick-start the font cache for the zygote process (to pay the cost of 345 * initializing freetype for our default font only once). 346 */ 347 static { 348 Paint p = new Paint(); 349 p.setAntiAlias(true); 350 // We don't care about the result, just the side-effect of measuring. 351 p.measureText("H"); 352 } 353 354 /** 355 * Interface definition for a callback to be invoked when an action is 356 * performed on the editor. 357 */ 358 public interface OnEditorActionListener { 359 /** 360 * Called when an action is being performed. 361 * 362 * @param v The view that was clicked. 363 * @param actionId Identifier of the action. This will be either the 364 * identifier you supplied, or {@link EditorInfo#IME_NULL 365 * EditorInfo.IME_NULL} if being called due to the enter key 366 * being pressed. 367 * @param event If triggered by an enter key, this is the event; 368 * otherwise, this is null. 369 * @return Return true if you have consumed the action, else false. 370 */ 371 boolean onEditorAction(TextView v, int actionId, KeyEvent event); 372 } 373 374 public TextView(Context context) { 375 this(context, null); 376 } 377 378 public TextView(Context context, 379 AttributeSet attrs) { 380 this(context, attrs, com.android.internal.R.attr.textViewStyle); 381 } 382 383 @SuppressWarnings("deprecation") 384 public TextView(Context context, 385 AttributeSet attrs, 386 int defStyle) { 387 super(context, attrs, defStyle); 388 mText = ""; 389 390 mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); 391 mTextPaint.density = getResources().getDisplayMetrics().density; 392 mTextPaint.setCompatibilityScaling( 393 getResources().getCompatibilityInfo().applicationScale); 394 395 // If we get the paint from the skin, we should set it to left, since 396 // the layout always wants it to be left. 397 // mTextPaint.setTextAlign(Paint.Align.LEFT); 398 399 mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 400 mHighlightPaint.setCompatibilityScaling( 401 getResources().getCompatibilityInfo().applicationScale); 402 403 mMovement = getDefaultMovementMethod(); 404 mTransformation = null; 405 406 TypedArray a = 407 context.obtainStyledAttributes( 408 attrs, com.android.internal.R.styleable.TextView, defStyle, 0); 409 410 int textColorHighlight = 0; 411 ColorStateList textColor = null; 412 ColorStateList textColorHint = null; 413 ColorStateList textColorLink = null; 414 int textSize = 15; 415 int typefaceIndex = -1; 416 int styleIndex = -1; 417 418 /* 419 * Look the appearance up without checking first if it exists because 420 * almost every TextView has one and it greatly simplifies the logic 421 * to be able to parse the appearance first and then let specific tags 422 * for this View override it. 423 */ 424 TypedArray appearance = null; 425 int ap = a.getResourceId(com.android.internal.R.styleable.TextView_textAppearance, -1); 426 if (ap != -1) { 427 appearance = context.obtainStyledAttributes(ap, 428 com.android.internal.R.styleable. 429 TextAppearance); 430 } 431 if (appearance != null) { 432 int n = appearance.getIndexCount(); 433 for (int i = 0; i < n; i++) { 434 int attr = appearance.getIndex(i); 435 436 switch (attr) { 437 case com.android.internal.R.styleable.TextAppearance_textColorHighlight: 438 textColorHighlight = appearance.getColor(attr, textColorHighlight); 439 break; 440 441 case com.android.internal.R.styleable.TextAppearance_textColor: 442 textColor = appearance.getColorStateList(attr); 443 break; 444 445 case com.android.internal.R.styleable.TextAppearance_textColorHint: 446 textColorHint = appearance.getColorStateList(attr); 447 break; 448 449 case com.android.internal.R.styleable.TextAppearance_textColorLink: 450 textColorLink = appearance.getColorStateList(attr); 451 break; 452 453 case com.android.internal.R.styleable.TextAppearance_textSize: 454 textSize = appearance.getDimensionPixelSize(attr, textSize); 455 break; 456 457 case com.android.internal.R.styleable.TextAppearance_typeface: 458 typefaceIndex = appearance.getInt(attr, -1); 459 break; 460 461 case com.android.internal.R.styleable.TextAppearance_textStyle: 462 styleIndex = appearance.getInt(attr, -1); 463 break; 464 } 465 } 466 467 appearance.recycle(); 468 } 469 470 boolean editable = getDefaultEditable(); 471 CharSequence inputMethod = null; 472 int numeric = 0; 473 CharSequence digits = null; 474 boolean phone = false; 475 boolean autotext = false; 476 int autocap = -1; 477 int buffertype = 0; 478 boolean selectallonfocus = false; 479 Drawable drawableLeft = null, drawableTop = null, drawableRight = null, 480 drawableBottom = null; 481 int drawablePadding = 0; 482 int ellipsize = -1; 483 boolean singleLine = false; 484 int maxlength = -1; 485 CharSequence text = ""; 486 CharSequence hint = null; 487 int shadowcolor = 0; 488 float dx = 0, dy = 0, r = 0; 489 boolean password = false; 490 int inputType = EditorInfo.TYPE_NULL; 491 492 int n = a.getIndexCount(); 493 for (int i = 0; i < n; i++) { 494 int attr = a.getIndex(i); 495 496 switch (attr) { 497 case com.android.internal.R.styleable.TextView_editable: 498 editable = a.getBoolean(attr, editable); 499 break; 500 501 case com.android.internal.R.styleable.TextView_inputMethod: 502 inputMethod = a.getText(attr); 503 break; 504 505 case com.android.internal.R.styleable.TextView_numeric: 506 numeric = a.getInt(attr, numeric); 507 break; 508 509 case com.android.internal.R.styleable.TextView_digits: 510 digits = a.getText(attr); 511 break; 512 513 case com.android.internal.R.styleable.TextView_phoneNumber: 514 phone = a.getBoolean(attr, phone); 515 break; 516 517 case com.android.internal.R.styleable.TextView_autoText: 518 autotext = a.getBoolean(attr, autotext); 519 break; 520 521 case com.android.internal.R.styleable.TextView_capitalize: 522 autocap = a.getInt(attr, autocap); 523 break; 524 525 case com.android.internal.R.styleable.TextView_bufferType: 526 buffertype = a.getInt(attr, buffertype); 527 break; 528 529 case com.android.internal.R.styleable.TextView_selectAllOnFocus: 530 selectallonfocus = a.getBoolean(attr, selectallonfocus); 531 break; 532 533 case com.android.internal.R.styleable.TextView_autoLink: 534 mAutoLinkMask = a.getInt(attr, 0); 535 break; 536 537 case com.android.internal.R.styleable.TextView_linksClickable: 538 mLinksClickable = a.getBoolean(attr, true); 539 break; 540 541 case com.android.internal.R.styleable.TextView_drawableLeft: 542 drawableLeft = a.getDrawable(attr); 543 break; 544 545 case com.android.internal.R.styleable.TextView_drawableTop: 546 drawableTop = a.getDrawable(attr); 547 break; 548 549 case com.android.internal.R.styleable.TextView_drawableRight: 550 drawableRight = a.getDrawable(attr); 551 break; 552 553 case com.android.internal.R.styleable.TextView_drawableBottom: 554 drawableBottom = a.getDrawable(attr); 555 break; 556 557 case com.android.internal.R.styleable.TextView_drawablePadding: 558 drawablePadding = a.getDimensionPixelSize(attr, drawablePadding); 559 break; 560 561 case com.android.internal.R.styleable.TextView_maxLines: 562 setMaxLines(a.getInt(attr, -1)); 563 break; 564 565 case com.android.internal.R.styleable.TextView_maxHeight: 566 setMaxHeight(a.getDimensionPixelSize(attr, -1)); 567 break; 568 569 case com.android.internal.R.styleable.TextView_lines: 570 setLines(a.getInt(attr, -1)); 571 break; 572 573 case com.android.internal.R.styleable.TextView_height: 574 setHeight(a.getDimensionPixelSize(attr, -1)); 575 break; 576 577 case com.android.internal.R.styleable.TextView_minLines: 578 setMinLines(a.getInt(attr, -1)); 579 break; 580 581 case com.android.internal.R.styleable.TextView_minHeight: 582 setMinHeight(a.getDimensionPixelSize(attr, -1)); 583 break; 584 585 case com.android.internal.R.styleable.TextView_maxEms: 586 setMaxEms(a.getInt(attr, -1)); 587 break; 588 589 case com.android.internal.R.styleable.TextView_maxWidth: 590 setMaxWidth(a.getDimensionPixelSize(attr, -1)); 591 break; 592 593 case com.android.internal.R.styleable.TextView_ems: 594 setEms(a.getInt(attr, -1)); 595 break; 596 597 case com.android.internal.R.styleable.TextView_width: 598 setWidth(a.getDimensionPixelSize(attr, -1)); 599 break; 600 601 case com.android.internal.R.styleable.TextView_minEms: 602 setMinEms(a.getInt(attr, -1)); 603 break; 604 605 case com.android.internal.R.styleable.TextView_minWidth: 606 setMinWidth(a.getDimensionPixelSize(attr, -1)); 607 break; 608 609 case com.android.internal.R.styleable.TextView_gravity: 610 setGravity(a.getInt(attr, -1)); 611 break; 612 613 case com.android.internal.R.styleable.TextView_hint: 614 hint = a.getText(attr); 615 break; 616 617 case com.android.internal.R.styleable.TextView_text: 618 text = a.getText(attr); 619 break; 620 621 case com.android.internal.R.styleable.TextView_scrollHorizontally: 622 if (a.getBoolean(attr, false)) { 623 setHorizontallyScrolling(true); 624 } 625 break; 626 627 case com.android.internal.R.styleable.TextView_singleLine: 628 singleLine = a.getBoolean(attr, singleLine); 629 break; 630 631 case com.android.internal.R.styleable.TextView_ellipsize: 632 ellipsize = a.getInt(attr, ellipsize); 633 break; 634 635 case com.android.internal.R.styleable.TextView_marqueeRepeatLimit: 636 setMarqueeRepeatLimit(a.getInt(attr, mMarqueeRepeatLimit)); 637 break; 638 639 case com.android.internal.R.styleable.TextView_includeFontPadding: 640 if (!a.getBoolean(attr, true)) { 641 setIncludeFontPadding(false); 642 } 643 break; 644 645 case com.android.internal.R.styleable.TextView_cursorVisible: 646 if (!a.getBoolean(attr, true)) { 647 setCursorVisible(false); 648 } 649 break; 650 651 case com.android.internal.R.styleable.TextView_maxLength: 652 maxlength = a.getInt(attr, -1); 653 break; 654 655 case com.android.internal.R.styleable.TextView_textScaleX: 656 setTextScaleX(a.getFloat(attr, 1.0f)); 657 break; 658 659 case com.android.internal.R.styleable.TextView_freezesText: 660 mFreezesText = a.getBoolean(attr, false); 661 break; 662 663 case com.android.internal.R.styleable.TextView_shadowColor: 664 shadowcolor = a.getInt(attr, 0); 665 break; 666 667 case com.android.internal.R.styleable.TextView_shadowDx: 668 dx = a.getFloat(attr, 0); 669 break; 670 671 case com.android.internal.R.styleable.TextView_shadowDy: 672 dy = a.getFloat(attr, 0); 673 break; 674 675 case com.android.internal.R.styleable.TextView_shadowRadius: 676 r = a.getFloat(attr, 0); 677 break; 678 679 case com.android.internal.R.styleable.TextView_enabled: 680 setEnabled(a.getBoolean(attr, isEnabled())); 681 break; 682 683 case com.android.internal.R.styleable.TextView_textColorHighlight: 684 textColorHighlight = a.getColor(attr, textColorHighlight); 685 break; 686 687 case com.android.internal.R.styleable.TextView_textColor: 688 textColor = a.getColorStateList(attr); 689 break; 690 691 case com.android.internal.R.styleable.TextView_textColorHint: 692 textColorHint = a.getColorStateList(attr); 693 break; 694 695 case com.android.internal.R.styleable.TextView_textColorLink: 696 textColorLink = a.getColorStateList(attr); 697 break; 698 699 case com.android.internal.R.styleable.TextView_textSize: 700 textSize = a.getDimensionPixelSize(attr, textSize); 701 break; 702 703 case com.android.internal.R.styleable.TextView_typeface: 704 typefaceIndex = a.getInt(attr, typefaceIndex); 705 break; 706 707 case com.android.internal.R.styleable.TextView_textStyle: 708 styleIndex = a.getInt(attr, styleIndex); 709 break; 710 711 case com.android.internal.R.styleable.TextView_password: 712 password = a.getBoolean(attr, password); 713 break; 714 715 case com.android.internal.R.styleable.TextView_lineSpacingExtra: 716 mSpacingAdd = a.getDimensionPixelSize(attr, (int) mSpacingAdd); 717 break; 718 719 case com.android.internal.R.styleable.TextView_lineSpacingMultiplier: 720 mSpacingMult = a.getFloat(attr, mSpacingMult); 721 break; 722 723 case com.android.internal.R.styleable.TextView_inputType: 724 inputType = a.getInt(attr, mInputType); 725 break; 726 727 case com.android.internal.R.styleable.TextView_imeOptions: 728 if (mInputContentType == null) { 729 mInputContentType = new InputContentType(); 730 } 731 mInputContentType.imeOptions = a.getInt(attr, 732 mInputContentType.imeOptions); 733 break; 734 735 case com.android.internal.R.styleable.TextView_imeActionLabel: 736 if (mInputContentType == null) { 737 mInputContentType = new InputContentType(); 738 } 739 mInputContentType.imeActionLabel = a.getText(attr); 740 break; 741 742 case com.android.internal.R.styleable.TextView_imeActionId: 743 if (mInputContentType == null) { 744 mInputContentType = new InputContentType(); 745 } 746 mInputContentType.imeActionId = a.getInt(attr, 747 mInputContentType.imeActionId); 748 break; 749 750 case com.android.internal.R.styleable.TextView_privateImeOptions: 751 setPrivateImeOptions(a.getString(attr)); 752 break; 753 754 case com.android.internal.R.styleable.TextView_editorExtras: 755 try { 756 setInputExtras(a.getResourceId(attr, 0)); 757 } catch (XmlPullParserException e) { 758 Log.w(LOG_TAG, "Failure reading input extras", e); 759 } catch (IOException e) { 760 Log.w(LOG_TAG, "Failure reading input extras", e); 761 } 762 break; 763 764 case com.android.internal.R.styleable.TextView_textCursorDrawable: 765 mCursorDrawableRes = a.getResourceId(attr, 0); 766 break; 767 768 case com.android.internal.R.styleable.TextView_textSelectHandleLeft: 769 mTextSelectHandleLeftRes = a.getResourceId(attr, 0); 770 break; 771 772 case com.android.internal.R.styleable.TextView_textSelectHandleRight: 773 mTextSelectHandleRightRes = a.getResourceId(attr, 0); 774 break; 775 776 case com.android.internal.R.styleable.TextView_textSelectHandle: 777 mTextSelectHandleRes = a.getResourceId(attr, 0); 778 break; 779 780 case com.android.internal.R.styleable.TextView_textEditPasteWindowLayout: 781 mTextEditPasteWindowLayout = a.getResourceId(attr, 0); 782 break; 783 784 case com.android.internal.R.styleable.TextView_textEditNoPasteWindowLayout: 785 mTextEditNoPasteWindowLayout = a.getResourceId(attr, 0); 786 break; 787 788 case com.android.internal.R.styleable.TextView_textEditSidePasteWindowLayout: 789 mTextEditSidePasteWindowLayout = a.getResourceId(attr, 0); 790 break; 791 792 case com.android.internal.R.styleable.TextView_textEditSideNoPasteWindowLayout: 793 mTextEditSideNoPasteWindowLayout = a.getResourceId(attr, 0); 794 break; 795 796 case com.android.internal.R.styleable.TextView_textEditSuggestionsBottomWindowLayout: 797 mTextEditSuggestionsBottomWindowLayout = a.getResourceId(attr, 0); 798 break; 799 800 case com.android.internal.R.styleable.TextView_textEditSuggestionsTopWindowLayout: 801 mTextEditSuggestionsTopWindowLayout = a.getResourceId(attr, 0); 802 break; 803 804 case com.android.internal.R.styleable.TextView_textEditSuggestionItemLayout: 805 mTextEditSuggestionItemLayout = a.getResourceId(attr, 0); 806 break; 807 808 case com.android.internal.R.styleable.TextView_textIsSelectable: 809 mTextIsSelectable = a.getBoolean(attr, false); 810 break; 811 812 case com.android.internal.R.styleable.TextView_suggestionsEnabled: 813 mSuggestionsEnabled = a.getBoolean(attr, true); 814 break; 815 } 816 } 817 a.recycle(); 818 819 BufferType bufferType = BufferType.EDITABLE; 820 821 final int variation = 822 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 823 final boolean passwordInputType = variation 824 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); 825 final boolean webPasswordInputType = variation 826 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD); 827 final boolean numberPasswordInputType = variation 828 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 829 830 if (inputMethod != null) { 831 Class<?> c; 832 833 try { 834 c = Class.forName(inputMethod.toString()); 835 } catch (ClassNotFoundException ex) { 836 throw new RuntimeException(ex); 837 } 838 839 try { 840 mInput = (KeyListener) c.newInstance(); 841 } catch (InstantiationException ex) { 842 throw new RuntimeException(ex); 843 } catch (IllegalAccessException ex) { 844 throw new RuntimeException(ex); 845 } 846 try { 847 mInputType = inputType != EditorInfo.TYPE_NULL 848 ? inputType 849 : mInput.getInputType(); 850 } catch (IncompatibleClassChangeError e) { 851 mInputType = EditorInfo.TYPE_CLASS_TEXT; 852 } 853 } else if (digits != null) { 854 mInput = DigitsKeyListener.getInstance(digits.toString()); 855 // If no input type was specified, we will default to generic 856 // text, since we can't tell the IME about the set of digits 857 // that was selected. 858 mInputType = inputType != EditorInfo.TYPE_NULL 859 ? inputType : EditorInfo.TYPE_CLASS_TEXT; 860 } else if (inputType != EditorInfo.TYPE_NULL) { 861 setInputType(inputType, true); 862 // If set, the input type overrides what was set using the deprecated singleLine flag. 863 singleLine = !isMultilineInputType(inputType); 864 } else if (phone) { 865 mInput = DialerKeyListener.getInstance(); 866 mInputType = inputType = EditorInfo.TYPE_CLASS_PHONE; 867 } else if (numeric != 0) { 868 mInput = DigitsKeyListener.getInstance((numeric & SIGNED) != 0, 869 (numeric & DECIMAL) != 0); 870 inputType = EditorInfo.TYPE_CLASS_NUMBER; 871 if ((numeric & SIGNED) != 0) { 872 inputType |= EditorInfo.TYPE_NUMBER_FLAG_SIGNED; 873 } 874 if ((numeric & DECIMAL) != 0) { 875 inputType |= EditorInfo.TYPE_NUMBER_FLAG_DECIMAL; 876 } 877 mInputType = inputType; 878 } else if (autotext || autocap != -1) { 879 TextKeyListener.Capitalize cap; 880 881 inputType = EditorInfo.TYPE_CLASS_TEXT; 882 883 switch (autocap) { 884 case 1: 885 cap = TextKeyListener.Capitalize.SENTENCES; 886 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES; 887 break; 888 889 case 2: 890 cap = TextKeyListener.Capitalize.WORDS; 891 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS; 892 break; 893 894 case 3: 895 cap = TextKeyListener.Capitalize.CHARACTERS; 896 inputType |= EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS; 897 break; 898 899 default: 900 cap = TextKeyListener.Capitalize.NONE; 901 break; 902 } 903 904 mInput = TextKeyListener.getInstance(autotext, cap); 905 mInputType = inputType; 906 } else if (mTextIsSelectable) { 907 // Prevent text changes from keyboard. 908 mInputType = EditorInfo.TYPE_NULL; 909 mInput = null; 910 bufferType = BufferType.SPANNABLE; 911 // Required to request focus while in touch mode. 912 setFocusableInTouchMode(true); 913 // So that selection can be changed using arrow keys and touch is handled. 914 setMovementMethod(ArrowKeyMovementMethod.getInstance()); 915 } else if (editable) { 916 mInput = TextKeyListener.getInstance(); 917 mInputType = EditorInfo.TYPE_CLASS_TEXT; 918 } else { 919 mInput = null; 920 921 switch (buffertype) { 922 case 0: 923 bufferType = BufferType.NORMAL; 924 break; 925 case 1: 926 bufferType = BufferType.SPANNABLE; 927 break; 928 case 2: 929 bufferType = BufferType.EDITABLE; 930 break; 931 } 932 } 933 934 // mInputType has been set from inputType, possibly modified by mInputMethod. 935 // Specialize mInputType to [web]password if we have a text class and the original input 936 // type was a password. 937 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 938 if (password || passwordInputType) { 939 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 940 | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD; 941 } 942 if (webPasswordInputType) { 943 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 944 | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD; 945 } 946 } else if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_NUMBER) { 947 if (numberPasswordInputType) { 948 mInputType = (mInputType & ~(EditorInfo.TYPE_MASK_VARIATION)) 949 | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD; 950 } 951 } 952 953 if (selectallonfocus) { 954 mSelectAllOnFocus = true; 955 956 if (bufferType == BufferType.NORMAL) 957 bufferType = BufferType.SPANNABLE; 958 } 959 960 setCompoundDrawablesWithIntrinsicBounds( 961 drawableLeft, drawableTop, drawableRight, drawableBottom); 962 setCompoundDrawablePadding(drawablePadding); 963 964 // Same as setSingleLine(), but make sure the transformation method and the maximum number 965 // of lines of height are unchanged for multi-line TextViews. 966 setInputTypeSingleLine(singleLine); 967 applySingleLine(singleLine, singleLine, singleLine); 968 969 if (singleLine && mInput == null && ellipsize < 0) { 970 ellipsize = 3; // END 971 } 972 973 switch (ellipsize) { 974 case 1: 975 setEllipsize(TextUtils.TruncateAt.START); 976 break; 977 case 2: 978 setEllipsize(TextUtils.TruncateAt.MIDDLE); 979 break; 980 case 3: 981 setEllipsize(TextUtils.TruncateAt.END); 982 break; 983 case 4: 984 setHorizontalFadingEdgeEnabled(true); 985 setEllipsize(TextUtils.TruncateAt.MARQUEE); 986 break; 987 } 988 989 setTextColor(textColor != null ? textColor : ColorStateList.valueOf(0xFF000000)); 990 setHintTextColor(textColorHint); 991 setLinkTextColor(textColorLink); 992 if (textColorHighlight != 0) { 993 setHighlightColor(textColorHighlight); 994 } 995 setRawTextSize(textSize); 996 997 if (password || passwordInputType || webPasswordInputType || numberPasswordInputType) { 998 setTransformationMethod(PasswordTransformationMethod.getInstance()); 999 typefaceIndex = MONOSPACE; 1000 } else if ((mInputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION)) 1001 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { 1002 typefaceIndex = MONOSPACE; 1003 } 1004 1005 setTypefaceByIndex(typefaceIndex, styleIndex); 1006 1007 if (shadowcolor != 0) { 1008 setShadowLayer(r, dx, dy, shadowcolor); 1009 } 1010 1011 if (maxlength >= 0) { 1012 setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) }); 1013 } else { 1014 setFilters(NO_FILTERS); 1015 } 1016 1017 setText(text, bufferType); 1018 if (hint != null) setHint(hint); 1019 1020 /* 1021 * Views are not normally focusable unless specified to be. 1022 * However, TextViews that have input or movement methods *are* 1023 * focusable by default. 1024 */ 1025 a = context.obtainStyledAttributes(attrs, 1026 com.android.internal.R.styleable.View, 1027 defStyle, 0); 1028 1029 boolean focusable = mMovement != null || mInput != null; 1030 boolean clickable = focusable; 1031 boolean longClickable = focusable; 1032 1033 n = a.getIndexCount(); 1034 for (int i = 0; i < n; i++) { 1035 int attr = a.getIndex(i); 1036 1037 switch (attr) { 1038 case com.android.internal.R.styleable.View_focusable: 1039 focusable = a.getBoolean(attr, focusable); 1040 break; 1041 1042 case com.android.internal.R.styleable.View_clickable: 1043 clickable = a.getBoolean(attr, clickable); 1044 break; 1045 1046 case com.android.internal.R.styleable.View_longClickable: 1047 longClickable = a.getBoolean(attr, longClickable); 1048 break; 1049 } 1050 } 1051 a.recycle(); 1052 1053 setFocusable(focusable); 1054 setClickable(clickable); 1055 setLongClickable(longClickable); 1056 1057 prepareCursorControllers(); 1058 1059 final ViewConfiguration viewConfiguration = ViewConfiguration.get(context); 1060 final int touchSlop = viewConfiguration.getScaledTouchSlop(); 1061 mSquaredTouchSlopDistance = touchSlop * touchSlop; 1062 } 1063 1064 private void setTypefaceByIndex(int typefaceIndex, int styleIndex) { 1065 Typeface tf = null; 1066 switch (typefaceIndex) { 1067 case SANS: 1068 tf = Typeface.SANS_SERIF; 1069 break; 1070 1071 case SERIF: 1072 tf = Typeface.SERIF; 1073 break; 1074 1075 case MONOSPACE: 1076 tf = Typeface.MONOSPACE; 1077 break; 1078 } 1079 1080 setTypeface(tf, styleIndex); 1081 } 1082 1083 @Override 1084 public void setEnabled(boolean enabled) { 1085 if (enabled == isEnabled()) { 1086 return; 1087 } 1088 1089 if (!enabled) { 1090 // Hide the soft input if the currently active TextView is disabled 1091 InputMethodManager imm = InputMethodManager.peekInstance(); 1092 if (imm != null && imm.isActive(this)) { 1093 imm.hideSoftInputFromWindow(getWindowToken(), 0); 1094 } 1095 } 1096 super.setEnabled(enabled); 1097 } 1098 1099 /** 1100 * Sets the typeface and style in which the text should be displayed, 1101 * and turns on the fake bold and italic bits in the Paint if the 1102 * Typeface that you provided does not have all the bits in the 1103 * style that you specified. 1104 * 1105 * @attr ref android.R.styleable#TextView_typeface 1106 * @attr ref android.R.styleable#TextView_textStyle 1107 */ 1108 public void setTypeface(Typeface tf, int style) { 1109 if (style > 0) { 1110 if (tf == null) { 1111 tf = Typeface.defaultFromStyle(style); 1112 } else { 1113 tf = Typeface.create(tf, style); 1114 } 1115 1116 setTypeface(tf); 1117 // now compute what (if any) algorithmic styling is needed 1118 int typefaceStyle = tf != null ? tf.getStyle() : 0; 1119 int need = style & ~typefaceStyle; 1120 mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); 1121 mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); 1122 } else { 1123 mTextPaint.setFakeBoldText(false); 1124 mTextPaint.setTextSkewX(0); 1125 setTypeface(tf); 1126 } 1127 } 1128 1129 /** 1130 * Subclasses override this to specify that they have a KeyListener 1131 * by default even if not specifically called for in the XML options. 1132 */ 1133 protected boolean getDefaultEditable() { 1134 return false; 1135 } 1136 1137 /** 1138 * Subclasses override this to specify a default movement method. 1139 */ 1140 protected MovementMethod getDefaultMovementMethod() { 1141 return null; 1142 } 1143 1144 /** 1145 * Return the text the TextView is displaying. If setText() was called with 1146 * an argument of BufferType.SPANNABLE or BufferType.EDITABLE, you can cast 1147 * the return value from this method to Spannable or Editable, respectively. 1148 * 1149 * Note: The content of the return value should not be modified. If you want 1150 * a modifiable one, you should make your own copy first. 1151 */ 1152 @ViewDebug.CapturedViewProperty 1153 public CharSequence getText() { 1154 return mText; 1155 } 1156 1157 /** 1158 * Returns the length, in characters, of the text managed by this TextView 1159 */ 1160 public int length() { 1161 return mText.length(); 1162 } 1163 1164 /** 1165 * Return the text the TextView is displaying as an Editable object. If 1166 * the text is not editable, null is returned. 1167 * 1168 * @see #getText 1169 */ 1170 public Editable getEditableText() { 1171 return (mText instanceof Editable) ? (Editable)mText : null; 1172 } 1173 1174 /** 1175 * @return the height of one standard line in pixels. Note that markup 1176 * within the text can cause individual lines to be taller or shorter 1177 * than this height, and the layout may contain additional first- 1178 * or last-line padding. 1179 */ 1180 public int getLineHeight() { 1181 return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd); 1182 } 1183 1184 /** 1185 * @return the Layout that is currently being used to display the text. 1186 * This can be null if the text or width has recently changes. 1187 */ 1188 public final Layout getLayout() { 1189 return mLayout; 1190 } 1191 1192 /** 1193 * @return the current key listener for this TextView. 1194 * This will frequently be null for non-EditText TextViews. 1195 */ 1196 public final KeyListener getKeyListener() { 1197 return mInput; 1198 } 1199 1200 /** 1201 * Sets the key listener to be used with this TextView. This can be null 1202 * to disallow user input. Note that this method has significant and 1203 * subtle interactions with soft keyboards and other input method: 1204 * see {@link KeyListener#getInputType() KeyListener.getContentType()} 1205 * for important details. Calling this method will replace the current 1206 * content type of the text view with the content type returned by the 1207 * key listener. 1208 * <p> 1209 * Be warned that if you want a TextView with a key listener or movement 1210 * method not to be focusable, or if you want a TextView without a 1211 * key listener or movement method to be focusable, you must call 1212 * {@link #setFocusable} again after calling this to get the focusability 1213 * back the way you want it. 1214 * 1215 * @attr ref android.R.styleable#TextView_numeric 1216 * @attr ref android.R.styleable#TextView_digits 1217 * @attr ref android.R.styleable#TextView_phoneNumber 1218 * @attr ref android.R.styleable#TextView_inputMethod 1219 * @attr ref android.R.styleable#TextView_capitalize 1220 * @attr ref android.R.styleable#TextView_autoText 1221 */ 1222 public void setKeyListener(KeyListener input) { 1223 setKeyListenerOnly(input); 1224 fixFocusableAndClickableSettings(); 1225 1226 if (input != null) { 1227 try { 1228 mInputType = mInput.getInputType(); 1229 } catch (IncompatibleClassChangeError e) { 1230 mInputType = EditorInfo.TYPE_CLASS_TEXT; 1231 } 1232 // Change inputType, without affecting transformation. 1233 // No need to applySingleLine since mSingleLine is unchanged. 1234 setInputTypeSingleLine(mSingleLine); 1235 } else { 1236 mInputType = EditorInfo.TYPE_NULL; 1237 } 1238 1239 InputMethodManager imm = InputMethodManager.peekInstance(); 1240 if (imm != null) imm.restartInput(this); 1241 } 1242 1243 private void setKeyListenerOnly(KeyListener input) { 1244 mInput = input; 1245 if (mInput != null && !(mText instanceof Editable)) 1246 setText(mText); 1247 1248 setFilters((Editable) mText, mFilters); 1249 } 1250 1251 /** 1252 * @return the movement method being used for this TextView. 1253 * This will frequently be null for non-EditText TextViews. 1254 */ 1255 public final MovementMethod getMovementMethod() { 1256 return mMovement; 1257 } 1258 1259 /** 1260 * Sets the movement method (arrow key handler) to be used for 1261 * this TextView. This can be null to disallow using the arrow keys 1262 * to move the cursor or scroll the view. 1263 * <p> 1264 * Be warned that if you want a TextView with a key listener or movement 1265 * method not to be focusable, or if you want a TextView without a 1266 * key listener or movement method to be focusable, you must call 1267 * {@link #setFocusable} again after calling this to get the focusability 1268 * back the way you want it. 1269 */ 1270 public final void setMovementMethod(MovementMethod movement) { 1271 mMovement = movement; 1272 1273 if (mMovement != null && !(mText instanceof Spannable)) 1274 setText(mText); 1275 1276 fixFocusableAndClickableSettings(); 1277 1278 // SelectionModifierCursorController depends on textCanBeSelected, which depends on mMovement 1279 prepareCursorControllers(); 1280 } 1281 1282 private void fixFocusableAndClickableSettings() { 1283 if ((mMovement != null) || mInput != null) { 1284 setFocusable(true); 1285 setClickable(true); 1286 setLongClickable(true); 1287 } else { 1288 setFocusable(false); 1289 setClickable(false); 1290 setLongClickable(false); 1291 } 1292 } 1293 1294 /** 1295 * @return the current transformation method for this TextView. 1296 * This will frequently be null except for single-line and password 1297 * fields. 1298 */ 1299 public final TransformationMethod getTransformationMethod() { 1300 return mTransformation; 1301 } 1302 1303 /** 1304 * Sets the transformation that is applied to the text that this 1305 * TextView is displaying. 1306 * 1307 * @attr ref android.R.styleable#TextView_password 1308 * @attr ref android.R.styleable#TextView_singleLine 1309 */ 1310 public final void setTransformationMethod(TransformationMethod method) { 1311 if (method == mTransformation) { 1312 // Avoid the setText() below if the transformation is 1313 // the same. 1314 return; 1315 } 1316 if (mTransformation != null) { 1317 if (mText instanceof Spannable) { 1318 ((Spannable) mText).removeSpan(mTransformation); 1319 } 1320 } 1321 1322 mTransformation = method; 1323 1324 setText(mText); 1325 } 1326 1327 /** 1328 * Returns the top padding of the view, plus space for the top 1329 * Drawable if any. 1330 */ 1331 public int getCompoundPaddingTop() { 1332 final Drawables dr = mDrawables; 1333 if (dr == null || dr.mDrawableTop == null) { 1334 return mPaddingTop; 1335 } else { 1336 return mPaddingTop + dr.mDrawablePadding + dr.mDrawableSizeTop; 1337 } 1338 } 1339 1340 /** 1341 * Returns the bottom padding of the view, plus space for the bottom 1342 * Drawable if any. 1343 */ 1344 public int getCompoundPaddingBottom() { 1345 final Drawables dr = mDrawables; 1346 if (dr == null || dr.mDrawableBottom == null) { 1347 return mPaddingBottom; 1348 } else { 1349 return mPaddingBottom + dr.mDrawablePadding + dr.mDrawableSizeBottom; 1350 } 1351 } 1352 1353 /** 1354 * Returns the left padding of the view, plus space for the left 1355 * Drawable if any. 1356 */ 1357 public int getCompoundPaddingLeft() { 1358 final Drawables dr = mDrawables; 1359 if (dr == null || dr.mDrawableLeft == null) { 1360 return mPaddingLeft; 1361 } else { 1362 return mPaddingLeft + dr.mDrawablePadding + dr.mDrawableSizeLeft; 1363 } 1364 } 1365 1366 /** 1367 * Returns the right padding of the view, plus space for the right 1368 * Drawable if any. 1369 */ 1370 public int getCompoundPaddingRight() { 1371 final Drawables dr = mDrawables; 1372 if (dr == null || dr.mDrawableRight == null) { 1373 return mPaddingRight; 1374 } else { 1375 return mPaddingRight + dr.mDrawablePadding + dr.mDrawableSizeRight; 1376 } 1377 } 1378 1379 /** 1380 * Returns the extended top padding of the view, including both the 1381 * top Drawable if any and any extra space to keep more than maxLines 1382 * of text from showing. It is only valid to call this after measuring. 1383 */ 1384 public int getExtendedPaddingTop() { 1385 if (mMaxMode != LINES) { 1386 return getCompoundPaddingTop(); 1387 } 1388 1389 if (mLayout.getLineCount() <= mMaximum) { 1390 return getCompoundPaddingTop(); 1391 } 1392 1393 int top = getCompoundPaddingTop(); 1394 int bottom = getCompoundPaddingBottom(); 1395 int viewht = getHeight() - top - bottom; 1396 int layoutht = mLayout.getLineTop(mMaximum); 1397 1398 if (layoutht >= viewht) { 1399 return top; 1400 } 1401 1402 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1403 if (gravity == Gravity.TOP) { 1404 return top; 1405 } else if (gravity == Gravity.BOTTOM) { 1406 return top + viewht - layoutht; 1407 } else { // (gravity == Gravity.CENTER_VERTICAL) 1408 return top + (viewht - layoutht) / 2; 1409 } 1410 } 1411 1412 /** 1413 * Returns the extended bottom padding of the view, including both the 1414 * bottom Drawable if any and any extra space to keep more than maxLines 1415 * of text from showing. It is only valid to call this after measuring. 1416 */ 1417 public int getExtendedPaddingBottom() { 1418 if (mMaxMode != LINES) { 1419 return getCompoundPaddingBottom(); 1420 } 1421 1422 if (mLayout.getLineCount() <= mMaximum) { 1423 return getCompoundPaddingBottom(); 1424 } 1425 1426 int top = getCompoundPaddingTop(); 1427 int bottom = getCompoundPaddingBottom(); 1428 int viewht = getHeight() - top - bottom; 1429 int layoutht = mLayout.getLineTop(mMaximum); 1430 1431 if (layoutht >= viewht) { 1432 return bottom; 1433 } 1434 1435 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 1436 if (gravity == Gravity.TOP) { 1437 return bottom + viewht - layoutht; 1438 } else if (gravity == Gravity.BOTTOM) { 1439 return bottom; 1440 } else { // (gravity == Gravity.CENTER_VERTICAL) 1441 return bottom + (viewht - layoutht) / 2; 1442 } 1443 } 1444 1445 /** 1446 * Returns the total left padding of the view, including the left 1447 * Drawable if any. 1448 */ 1449 public int getTotalPaddingLeft() { 1450 return getCompoundPaddingLeft(); 1451 } 1452 1453 /** 1454 * Returns the total right padding of the view, including the right 1455 * Drawable if any. 1456 */ 1457 public int getTotalPaddingRight() { 1458 return getCompoundPaddingRight(); 1459 } 1460 1461 /** 1462 * Returns the total top padding of the view, including the top 1463 * Drawable if any, the extra space to keep more than maxLines 1464 * from showing, and the vertical offset for gravity, if any. 1465 */ 1466 public int getTotalPaddingTop() { 1467 return getExtendedPaddingTop() + getVerticalOffset(true); 1468 } 1469 1470 /** 1471 * Returns the total bottom padding of the view, including the bottom 1472 * Drawable if any, the extra space to keep more than maxLines 1473 * from showing, and the vertical offset for gravity, if any. 1474 */ 1475 public int getTotalPaddingBottom() { 1476 return getExtendedPaddingBottom() + getBottomVerticalOffset(true); 1477 } 1478 1479 /** 1480 * Sets the Drawables (if any) to appear to the left of, above, 1481 * to the right of, and below the text. Use null if you do not 1482 * want a Drawable there. The Drawables must already have had 1483 * {@link Drawable#setBounds} called. 1484 * 1485 * @attr ref android.R.styleable#TextView_drawableLeft 1486 * @attr ref android.R.styleable#TextView_drawableTop 1487 * @attr ref android.R.styleable#TextView_drawableRight 1488 * @attr ref android.R.styleable#TextView_drawableBottom 1489 */ 1490 public void setCompoundDrawables(Drawable left, Drawable top, 1491 Drawable right, Drawable bottom) { 1492 Drawables dr = mDrawables; 1493 1494 final boolean drawables = left != null || top != null 1495 || right != null || bottom != null; 1496 1497 if (!drawables) { 1498 // Clearing drawables... can we free the data structure? 1499 if (dr != null) { 1500 if (dr.mDrawablePadding == 0) { 1501 mDrawables = null; 1502 } else { 1503 // We need to retain the last set padding, so just clear 1504 // out all of the fields in the existing structure. 1505 if (dr.mDrawableLeft != null) dr.mDrawableLeft.setCallback(null); 1506 dr.mDrawableLeft = null; 1507 if (dr.mDrawableTop != null) dr.mDrawableTop.setCallback(null); 1508 dr.mDrawableTop = null; 1509 if (dr.mDrawableRight != null) dr.mDrawableRight.setCallback(null); 1510 dr.mDrawableRight = null; 1511 if (dr.mDrawableBottom != null) dr.mDrawableBottom.setCallback(null); 1512 dr.mDrawableBottom = null; 1513 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 1514 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 1515 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1516 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1517 } 1518 } 1519 } else { 1520 if (dr == null) { 1521 mDrawables = dr = new Drawables(); 1522 } 1523 1524 if (dr.mDrawableLeft != left && dr.mDrawableLeft != null) { 1525 dr.mDrawableLeft.setCallback(null); 1526 } 1527 dr.mDrawableLeft = left; 1528 1529 if (dr.mDrawableTop != top && dr.mDrawableTop != null) { 1530 dr.mDrawableTop.setCallback(null); 1531 } 1532 dr.mDrawableTop = top; 1533 1534 if (dr.mDrawableRight != right && dr.mDrawableRight != null) { 1535 dr.mDrawableRight.setCallback(null); 1536 } 1537 dr.mDrawableRight = right; 1538 1539 if (dr.mDrawableBottom != bottom && dr.mDrawableBottom != null) { 1540 dr.mDrawableBottom.setCallback(null); 1541 } 1542 dr.mDrawableBottom = bottom; 1543 1544 final Rect compoundRect = dr.mCompoundRect; 1545 int[] state; 1546 1547 state = getDrawableState(); 1548 1549 if (left != null) { 1550 left.setState(state); 1551 left.copyBounds(compoundRect); 1552 left.setCallback(this); 1553 dr.mDrawableSizeLeft = compoundRect.width(); 1554 dr.mDrawableHeightLeft = compoundRect.height(); 1555 } else { 1556 dr.mDrawableSizeLeft = dr.mDrawableHeightLeft = 0; 1557 } 1558 1559 if (right != null) { 1560 right.setState(state); 1561 right.copyBounds(compoundRect); 1562 right.setCallback(this); 1563 dr.mDrawableSizeRight = compoundRect.width(); 1564 dr.mDrawableHeightRight = compoundRect.height(); 1565 } else { 1566 dr.mDrawableSizeRight = dr.mDrawableHeightRight = 0; 1567 } 1568 1569 if (top != null) { 1570 top.setState(state); 1571 top.copyBounds(compoundRect); 1572 top.setCallback(this); 1573 dr.mDrawableSizeTop = compoundRect.height(); 1574 dr.mDrawableWidthTop = compoundRect.width(); 1575 } else { 1576 dr.mDrawableSizeTop = dr.mDrawableWidthTop = 0; 1577 } 1578 1579 if (bottom != null) { 1580 bottom.setState(state); 1581 bottom.copyBounds(compoundRect); 1582 bottom.setCallback(this); 1583 dr.mDrawableSizeBottom = compoundRect.height(); 1584 dr.mDrawableWidthBottom = compoundRect.width(); 1585 } else { 1586 dr.mDrawableSizeBottom = dr.mDrawableWidthBottom = 0; 1587 } 1588 } 1589 1590 invalidate(); 1591 requestLayout(); 1592 } 1593 1594 /** 1595 * Sets the Drawables (if any) to appear to the left of, above, 1596 * to the right of, and below the text. Use 0 if you do not 1597 * want a Drawable there. The Drawables' bounds will be set to 1598 * their intrinsic bounds. 1599 * 1600 * @param left Resource identifier of the left Drawable. 1601 * @param top Resource identifier of the top Drawable. 1602 * @param right Resource identifier of the right Drawable. 1603 * @param bottom Resource identifier of the bottom Drawable. 1604 * 1605 * @attr ref android.R.styleable#TextView_drawableLeft 1606 * @attr ref android.R.styleable#TextView_drawableTop 1607 * @attr ref android.R.styleable#TextView_drawableRight 1608 * @attr ref android.R.styleable#TextView_drawableBottom 1609 */ 1610 public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) { 1611 final Resources resources = getContext().getResources(); 1612 setCompoundDrawablesWithIntrinsicBounds(left != 0 ? resources.getDrawable(left) : null, 1613 top != 0 ? resources.getDrawable(top) : null, 1614 right != 0 ? resources.getDrawable(right) : null, 1615 bottom != 0 ? resources.getDrawable(bottom) : null); 1616 } 1617 1618 /** 1619 * Sets the Drawables (if any) to appear to the left of, above, 1620 * to the right of, and below the text. Use null if you do not 1621 * want a Drawable there. The Drawables' bounds will be set to 1622 * their intrinsic bounds. 1623 * 1624 * @attr ref android.R.styleable#TextView_drawableLeft 1625 * @attr ref android.R.styleable#TextView_drawableTop 1626 * @attr ref android.R.styleable#TextView_drawableRight 1627 * @attr ref android.R.styleable#TextView_drawableBottom 1628 */ 1629 public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top, 1630 Drawable right, Drawable bottom) { 1631 1632 if (left != null) { 1633 left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight()); 1634 } 1635 if (right != null) { 1636 right.setBounds(0, 0, right.getIntrinsicWidth(), right.getIntrinsicHeight()); 1637 } 1638 if (top != null) { 1639 top.setBounds(0, 0, top.getIntrinsicWidth(), top.getIntrinsicHeight()); 1640 } 1641 if (bottom != null) { 1642 bottom.setBounds(0, 0, bottom.getIntrinsicWidth(), bottom.getIntrinsicHeight()); 1643 } 1644 setCompoundDrawables(left, top, right, bottom); 1645 } 1646 1647 /** 1648 * Returns drawables for the left, top, right, and bottom borders. 1649 */ 1650 public Drawable[] getCompoundDrawables() { 1651 final Drawables dr = mDrawables; 1652 if (dr != null) { 1653 return new Drawable[] { 1654 dr.mDrawableLeft, dr.mDrawableTop, dr.mDrawableRight, dr.mDrawableBottom 1655 }; 1656 } else { 1657 return new Drawable[] { null, null, null, null }; 1658 } 1659 } 1660 1661 /** 1662 * Sets the size of the padding between the compound drawables and 1663 * the text. 1664 * 1665 * @attr ref android.R.styleable#TextView_drawablePadding 1666 */ 1667 public void setCompoundDrawablePadding(int pad) { 1668 Drawables dr = mDrawables; 1669 if (pad == 0) { 1670 if (dr != null) { 1671 dr.mDrawablePadding = pad; 1672 } 1673 } else { 1674 if (dr == null) { 1675 mDrawables = dr = new Drawables(); 1676 } 1677 dr.mDrawablePadding = pad; 1678 } 1679 1680 invalidate(); 1681 requestLayout(); 1682 } 1683 1684 /** 1685 * Returns the padding between the compound drawables and the text. 1686 */ 1687 public int getCompoundDrawablePadding() { 1688 final Drawables dr = mDrawables; 1689 return dr != null ? dr.mDrawablePadding : 0; 1690 } 1691 1692 @Override 1693 public void setPadding(int left, int top, int right, int bottom) { 1694 if (left != mPaddingLeft || 1695 right != mPaddingRight || 1696 top != mPaddingTop || 1697 bottom != mPaddingBottom) { 1698 nullLayouts(); 1699 } 1700 1701 // the super call will requestLayout() 1702 super.setPadding(left, top, right, bottom); 1703 invalidate(); 1704 } 1705 1706 /** 1707 * Gets the autolink mask of the text. See {@link 1708 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 1709 * possible values. 1710 * 1711 * @attr ref android.R.styleable#TextView_autoLink 1712 */ 1713 public final int getAutoLinkMask() { 1714 return mAutoLinkMask; 1715 } 1716 1717 /** 1718 * Sets the text color, size, style, hint color, and highlight color 1719 * from the specified TextAppearance resource. 1720 */ 1721 public void setTextAppearance(Context context, int resid) { 1722 TypedArray appearance = 1723 context.obtainStyledAttributes(resid, 1724 com.android.internal.R.styleable.TextAppearance); 1725 1726 int color; 1727 ColorStateList colors; 1728 int ts; 1729 1730 color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0); 1731 if (color != 0) { 1732 setHighlightColor(color); 1733 } 1734 1735 colors = appearance.getColorStateList(com.android.internal.R.styleable. 1736 TextAppearance_textColor); 1737 if (colors != null) { 1738 setTextColor(colors); 1739 } 1740 1741 ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable. 1742 TextAppearance_textSize, 0); 1743 if (ts != 0) { 1744 setRawTextSize(ts); 1745 } 1746 1747 colors = appearance.getColorStateList(com.android.internal.R.styleable. 1748 TextAppearance_textColorHint); 1749 if (colors != null) { 1750 setHintTextColor(colors); 1751 } 1752 1753 colors = appearance.getColorStateList(com.android.internal.R.styleable. 1754 TextAppearance_textColorLink); 1755 if (colors != null) { 1756 setLinkTextColor(colors); 1757 } 1758 1759 int typefaceIndex, styleIndex; 1760 1761 typefaceIndex = appearance.getInt(com.android.internal.R.styleable. 1762 TextAppearance_typeface, -1); 1763 styleIndex = appearance.getInt(com.android.internal.R.styleable. 1764 TextAppearance_textStyle, -1); 1765 1766 setTypefaceByIndex(typefaceIndex, styleIndex); 1767 1768 appearance.recycle(); 1769 } 1770 1771 /** 1772 * @return the size (in pixels) of the default text size in this TextView. 1773 */ 1774 public float getTextSize() { 1775 return mTextPaint.getTextSize(); 1776 } 1777 1778 /** 1779 * Set the default text size to the given value, interpreted as "scaled 1780 * pixel" units. This size is adjusted based on the current density and 1781 * user font size preference. 1782 * 1783 * @param size The scaled pixel size. 1784 * 1785 * @attr ref android.R.styleable#TextView_textSize 1786 */ 1787 @android.view.RemotableViewMethod 1788 public void setTextSize(float size) { 1789 setTextSize(TypedValue.COMPLEX_UNIT_SP, size); 1790 } 1791 1792 /** 1793 * Set the default text size to a given unit and value. See {@link 1794 * TypedValue} for the possible dimension units. 1795 * 1796 * @param unit The desired dimension unit. 1797 * @param size The desired size in the given units. 1798 * 1799 * @attr ref android.R.styleable#TextView_textSize 1800 */ 1801 public void setTextSize(int unit, float size) { 1802 Context c = getContext(); 1803 Resources r; 1804 1805 if (c == null) 1806 r = Resources.getSystem(); 1807 else 1808 r = c.getResources(); 1809 1810 setRawTextSize(TypedValue.applyDimension( 1811 unit, size, r.getDisplayMetrics())); 1812 } 1813 1814 private void setRawTextSize(float size) { 1815 if (size != mTextPaint.getTextSize()) { 1816 mTextPaint.setTextSize(size); 1817 1818 if (mLayout != null) { 1819 nullLayouts(); 1820 requestLayout(); 1821 invalidate(); 1822 } 1823 } 1824 } 1825 1826 /** 1827 * @return the extent by which text is currently being stretched 1828 * horizontally. This will usually be 1. 1829 */ 1830 public float getTextScaleX() { 1831 return mTextPaint.getTextScaleX(); 1832 } 1833 1834 /** 1835 * Sets the extent by which text should be stretched horizontally. 1836 * 1837 * @attr ref android.R.styleable#TextView_textScaleX 1838 */ 1839 @android.view.RemotableViewMethod 1840 public void setTextScaleX(float size) { 1841 if (size != mTextPaint.getTextScaleX()) { 1842 mUserSetTextScaleX = true; 1843 mTextPaint.setTextScaleX(size); 1844 1845 if (mLayout != null) { 1846 nullLayouts(); 1847 requestLayout(); 1848 invalidate(); 1849 } 1850 } 1851 } 1852 1853 /** 1854 * Sets the typeface and style in which the text should be displayed. 1855 * Note that not all Typeface families actually have bold and italic 1856 * variants, so you may need to use 1857 * {@link #setTypeface(Typeface, int)} to get the appearance 1858 * that you actually want. 1859 * 1860 * @attr ref android.R.styleable#TextView_typeface 1861 * @attr ref android.R.styleable#TextView_textStyle 1862 */ 1863 public void setTypeface(Typeface tf) { 1864 if (mTextPaint.getTypeface() != tf) { 1865 mTextPaint.setTypeface(tf); 1866 1867 if (mLayout != null) { 1868 nullLayouts(); 1869 requestLayout(); 1870 invalidate(); 1871 } 1872 } 1873 } 1874 1875 /** 1876 * @return the current typeface and style in which the text is being 1877 * displayed. 1878 */ 1879 public Typeface getTypeface() { 1880 return mTextPaint.getTypeface(); 1881 } 1882 1883 /** 1884 * Sets the text color for all the states (normal, selected, 1885 * focused) to be this color. 1886 * 1887 * @attr ref android.R.styleable#TextView_textColor 1888 */ 1889 @android.view.RemotableViewMethod 1890 public void setTextColor(int color) { 1891 mTextColor = ColorStateList.valueOf(color); 1892 updateTextColors(); 1893 } 1894 1895 /** 1896 * Sets the text color. 1897 * 1898 * @attr ref android.R.styleable#TextView_textColor 1899 */ 1900 public void setTextColor(ColorStateList colors) { 1901 if (colors == null) { 1902 throw new NullPointerException(); 1903 } 1904 1905 mTextColor = colors; 1906 updateTextColors(); 1907 } 1908 1909 /** 1910 * Return the set of text colors. 1911 * 1912 * @return Returns the set of text colors. 1913 */ 1914 public final ColorStateList getTextColors() { 1915 return mTextColor; 1916 } 1917 1918 /** 1919 * <p>Return the current color selected for normal text.</p> 1920 * 1921 * @return Returns the current text color. 1922 */ 1923 public final int getCurrentTextColor() { 1924 return mCurTextColor; 1925 } 1926 1927 /** 1928 * Sets the color used to display the selection highlight. 1929 * 1930 * @attr ref android.R.styleable#TextView_textColorHighlight 1931 */ 1932 @android.view.RemotableViewMethod 1933 public void setHighlightColor(int color) { 1934 if (mHighlightColor != color) { 1935 mHighlightColor = color; 1936 invalidate(); 1937 } 1938 } 1939 1940 /** 1941 * Gives the text a shadow of the specified radius and color, the specified 1942 * distance from its normal position. 1943 * 1944 * @attr ref android.R.styleable#TextView_shadowColor 1945 * @attr ref android.R.styleable#TextView_shadowDx 1946 * @attr ref android.R.styleable#TextView_shadowDy 1947 * @attr ref android.R.styleable#TextView_shadowRadius 1948 */ 1949 public void setShadowLayer(float radius, float dx, float dy, int color) { 1950 mTextPaint.setShadowLayer(radius, dx, dy, color); 1951 1952 mShadowRadius = radius; 1953 mShadowDx = dx; 1954 mShadowDy = dy; 1955 1956 invalidate(); 1957 } 1958 1959 /** 1960 * @return the base paint used for the text. Please use this only to 1961 * consult the Paint's properties and not to change them. 1962 */ 1963 public TextPaint getPaint() { 1964 return mTextPaint; 1965 } 1966 1967 /** 1968 * Sets the autolink mask of the text. See {@link 1969 * android.text.util.Linkify#ALL Linkify.ALL} and peers for 1970 * possible values. 1971 * 1972 * @attr ref android.R.styleable#TextView_autoLink 1973 */ 1974 @android.view.RemotableViewMethod 1975 public final void setAutoLinkMask(int mask) { 1976 mAutoLinkMask = mask; 1977 } 1978 1979 /** 1980 * Sets whether the movement method will automatically be set to 1981 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 1982 * set to nonzero and links are detected in {@link #setText}. 1983 * The default is true. 1984 * 1985 * @attr ref android.R.styleable#TextView_linksClickable 1986 */ 1987 @android.view.RemotableViewMethod 1988 public final void setLinksClickable(boolean whether) { 1989 mLinksClickable = whether; 1990 } 1991 1992 /** 1993 * Returns whether the movement method will automatically be set to 1994 * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been 1995 * set to nonzero and links are detected in {@link #setText}. 1996 * The default is true. 1997 * 1998 * @attr ref android.R.styleable#TextView_linksClickable 1999 */ 2000 public final boolean getLinksClickable() { 2001 return mLinksClickable; 2002 } 2003 2004 /** 2005 * Returns the list of URLSpans attached to the text 2006 * (by {@link Linkify} or otherwise) if any. You can call 2007 * {@link URLSpan#getURL} on them to find where they link to 2008 * or use {@link Spanned#getSpanStart} and {@link Spanned#getSpanEnd} 2009 * to find the region of the text they are attached to. 2010 */ 2011 public URLSpan[] getUrls() { 2012 if (mText instanceof Spanned) { 2013 return ((Spanned) mText).getSpans(0, mText.length(), URLSpan.class); 2014 } else { 2015 return new URLSpan[0]; 2016 } 2017 } 2018 2019 /** 2020 * Sets the color of the hint text. 2021 * 2022 * @attr ref android.R.styleable#TextView_textColorHint 2023 */ 2024 @android.view.RemotableViewMethod 2025 public final void setHintTextColor(int color) { 2026 mHintTextColor = ColorStateList.valueOf(color); 2027 updateTextColors(); 2028 } 2029 2030 /** 2031 * Sets the color of the hint text. 2032 * 2033 * @attr ref android.R.styleable#TextView_textColorHint 2034 */ 2035 public final void setHintTextColor(ColorStateList colors) { 2036 mHintTextColor = colors; 2037 updateTextColors(); 2038 } 2039 2040 /** 2041 * <p>Return the color used to paint the hint text.</p> 2042 * 2043 * @return Returns the list of hint text colors. 2044 */ 2045 public final ColorStateList getHintTextColors() { 2046 return mHintTextColor; 2047 } 2048 2049 /** 2050 * <p>Return the current color selected to paint the hint text.</p> 2051 * 2052 * @return Returns the current hint text color. 2053 */ 2054 public final int getCurrentHintTextColor() { 2055 return mHintTextColor != null ? mCurHintTextColor : mCurTextColor; 2056 } 2057 2058 /** 2059 * Sets the color of links in the text. 2060 * 2061 * @attr ref android.R.styleable#TextView_textColorLink 2062 */ 2063 @android.view.RemotableViewMethod 2064 public final void setLinkTextColor(int color) { 2065 mLinkTextColor = ColorStateList.valueOf(color); 2066 updateTextColors(); 2067 } 2068 2069 /** 2070 * Sets the color of links in the text. 2071 * 2072 * @attr ref android.R.styleable#TextView_textColorLink 2073 */ 2074 public final void setLinkTextColor(ColorStateList colors) { 2075 mLinkTextColor = colors; 2076 updateTextColors(); 2077 } 2078 2079 /** 2080 * <p>Returns the color used to paint links in the text.</p> 2081 * 2082 * @return Returns the list of link text colors. 2083 */ 2084 public final ColorStateList getLinkTextColors() { 2085 return mLinkTextColor; 2086 } 2087 2088 /** 2089 * Sets the horizontal alignment of the text and the 2090 * vertical gravity that will be used when there is extra space 2091 * in the TextView beyond what is required for the text itself. 2092 * 2093 * @see android.view.Gravity 2094 * @attr ref android.R.styleable#TextView_gravity 2095 */ 2096 public void setGravity(int gravity) { 2097 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) == 0) { 2098 gravity |= Gravity.START; 2099 } 2100 if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == 0) { 2101 gravity |= Gravity.TOP; 2102 } 2103 2104 boolean newLayout = false; 2105 2106 if ((gravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) != 2107 (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK)) { 2108 newLayout = true; 2109 } 2110 2111 if (gravity != mGravity) { 2112 invalidate(); 2113 } 2114 2115 mGravity = gravity; 2116 2117 if (mLayout != null && newLayout) { 2118 // XXX this is heavy-handed because no actual content changes. 2119 int want = mLayout.getWidth(); 2120 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 2121 2122 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 2123 mRight - mLeft - getCompoundPaddingLeft() - 2124 getCompoundPaddingRight(), true); 2125 } 2126 } 2127 2128 /** 2129 * Returns the horizontal and vertical alignment of this TextView. 2130 * 2131 * @see android.view.Gravity 2132 * @attr ref android.R.styleable#TextView_gravity 2133 */ 2134 public int getGravity() { 2135 return mGravity; 2136 } 2137 2138 /** 2139 * @return the flags on the Paint being used to display the text. 2140 * @see Paint#getFlags 2141 */ 2142 public int getPaintFlags() { 2143 return mTextPaint.getFlags(); 2144 } 2145 2146 /** 2147 * Sets flags on the Paint being used to display the text and 2148 * reflows the text if they are different from the old flags. 2149 * @see Paint#setFlags 2150 */ 2151 @android.view.RemotableViewMethod 2152 public void setPaintFlags(int flags) { 2153 if (mTextPaint.getFlags() != flags) { 2154 mTextPaint.setFlags(flags); 2155 2156 if (mLayout != null) { 2157 nullLayouts(); 2158 requestLayout(); 2159 invalidate(); 2160 } 2161 } 2162 } 2163 2164 /** 2165 * Sets whether the text should be allowed to be wider than the 2166 * View is. If false, it will be wrapped to the width of the View. 2167 * 2168 * @attr ref android.R.styleable#TextView_scrollHorizontally 2169 */ 2170 public void setHorizontallyScrolling(boolean whether) { 2171 mHorizontallyScrolling = whether; 2172 2173 if (mLayout != null) { 2174 nullLayouts(); 2175 requestLayout(); 2176 invalidate(); 2177 } 2178 } 2179 2180 /** 2181 * Makes the TextView at least this many lines tall. 2182 * 2183 * Setting this value overrides any other (minimum) height setting. A single line TextView will 2184 * set this value to 1. 2185 * 2186 * @attr ref android.R.styleable#TextView_minLines 2187 */ 2188 @android.view.RemotableViewMethod 2189 public void setMinLines(int minlines) { 2190 mMinimum = minlines; 2191 mMinMode = LINES; 2192 2193 requestLayout(); 2194 invalidate(); 2195 } 2196 2197 /** 2198 * Makes the TextView at least this many pixels tall. 2199 * 2200 * Setting this value overrides any other (minimum) number of lines setting. 2201 * 2202 * @attr ref android.R.styleable#TextView_minHeight 2203 */ 2204 @android.view.RemotableViewMethod 2205 public void setMinHeight(int minHeight) { 2206 mMinimum = minHeight; 2207 mMinMode = PIXELS; 2208 2209 requestLayout(); 2210 invalidate(); 2211 } 2212 2213 /** 2214 * Makes the TextView at most this many lines tall. 2215 * 2216 * Setting this value overrides any other (maximum) height setting. 2217 * 2218 * @attr ref android.R.styleable#TextView_maxLines 2219 */ 2220 @android.view.RemotableViewMethod 2221 public void setMaxLines(int maxlines) { 2222 mMaximum = maxlines; 2223 mMaxMode = LINES; 2224 2225 requestLayout(); 2226 invalidate(); 2227 } 2228 2229 /** 2230 * Makes the TextView at most this many pixels tall. This option is mutually exclusive with the 2231 * {@link #setMaxLines(int)} method. 2232 * 2233 * Setting this value overrides any other (maximum) number of lines setting. 2234 * 2235 * @attr ref android.R.styleable#TextView_maxHeight 2236 */ 2237 @android.view.RemotableViewMethod 2238 public void setMaxHeight(int maxHeight) { 2239 mMaximum = maxHeight; 2240 mMaxMode = PIXELS; 2241 2242 requestLayout(); 2243 invalidate(); 2244 } 2245 2246 /** 2247 * Makes the TextView exactly this many lines tall. 2248 * 2249 * Note that setting this value overrides any other (minimum / maximum) number of lines or 2250 * height setting. A single line TextView will set this value to 1. 2251 * 2252 * @attr ref android.R.styleable#TextView_lines 2253 */ 2254 @android.view.RemotableViewMethod 2255 public void setLines(int lines) { 2256 mMaximum = mMinimum = lines; 2257 mMaxMode = mMinMode = LINES; 2258 2259 requestLayout(); 2260 invalidate(); 2261 } 2262 2263 /** 2264 * Makes the TextView exactly this many pixels tall. 2265 * You could do the same thing by specifying this number in the 2266 * LayoutParams. 2267 * 2268 * Note that setting this value overrides any other (minimum / maximum) number of lines or 2269 * height setting. 2270 * 2271 * @attr ref android.R.styleable#TextView_height 2272 */ 2273 @android.view.RemotableViewMethod 2274 public void setHeight(int pixels) { 2275 mMaximum = mMinimum = pixels; 2276 mMaxMode = mMinMode = PIXELS; 2277 2278 requestLayout(); 2279 invalidate(); 2280 } 2281 2282 /** 2283 * Makes the TextView at least this many ems wide 2284 * 2285 * @attr ref android.R.styleable#TextView_minEms 2286 */ 2287 @android.view.RemotableViewMethod 2288 public void setMinEms(int minems) { 2289 mMinWidth = minems; 2290 mMinWidthMode = EMS; 2291 2292 requestLayout(); 2293 invalidate(); 2294 } 2295 2296 /** 2297 * Makes the TextView at least this many pixels wide 2298 * 2299 * @attr ref android.R.styleable#TextView_minWidth 2300 */ 2301 @android.view.RemotableViewMethod 2302 public void setMinWidth(int minpixels) { 2303 mMinWidth = minpixels; 2304 mMinWidthMode = PIXELS; 2305 2306 requestLayout(); 2307 invalidate(); 2308 } 2309 2310 /** 2311 * Makes the TextView at most this many ems wide 2312 * 2313 * @attr ref android.R.styleable#TextView_maxEms 2314 */ 2315 @android.view.RemotableViewMethod 2316 public void setMaxEms(int maxems) { 2317 mMaxWidth = maxems; 2318 mMaxWidthMode = EMS; 2319 2320 requestLayout(); 2321 invalidate(); 2322 } 2323 2324 /** 2325 * Makes the TextView at most this many pixels wide 2326 * 2327 * @attr ref android.R.styleable#TextView_maxWidth 2328 */ 2329 @android.view.RemotableViewMethod 2330 public void setMaxWidth(int maxpixels) { 2331 mMaxWidth = maxpixels; 2332 mMaxWidthMode = PIXELS; 2333 2334 requestLayout(); 2335 invalidate(); 2336 } 2337 2338 /** 2339 * Makes the TextView exactly this many ems wide 2340 * 2341 * @attr ref android.R.styleable#TextView_ems 2342 */ 2343 @android.view.RemotableViewMethod 2344 public void setEms(int ems) { 2345 mMaxWidth = mMinWidth = ems; 2346 mMaxWidthMode = mMinWidthMode = EMS; 2347 2348 requestLayout(); 2349 invalidate(); 2350 } 2351 2352 /** 2353 * Makes the TextView exactly this many pixels wide. 2354 * You could do the same thing by specifying this number in the 2355 * LayoutParams. 2356 * 2357 * @attr ref android.R.styleable#TextView_width 2358 */ 2359 @android.view.RemotableViewMethod 2360 public void setWidth(int pixels) { 2361 mMaxWidth = mMinWidth = pixels; 2362 mMaxWidthMode = mMinWidthMode = PIXELS; 2363 2364 requestLayout(); 2365 invalidate(); 2366 } 2367 2368 2369 /** 2370 * Sets line spacing for this TextView. Each line will have its height 2371 * multiplied by <code>mult</code> and have <code>add</code> added to it. 2372 * 2373 * @attr ref android.R.styleable#TextView_lineSpacingExtra 2374 * @attr ref android.R.styleable#TextView_lineSpacingMultiplier 2375 */ 2376 public void setLineSpacing(float add, float mult) { 2377 mSpacingMult = mult; 2378 mSpacingAdd = add; 2379 2380 if (mLayout != null) { 2381 nullLayouts(); 2382 requestLayout(); 2383 invalidate(); 2384 } 2385 } 2386 2387 /** 2388 * Convenience method: Append the specified text to the TextView's 2389 * display buffer, upgrading it to BufferType.EDITABLE if it was 2390 * not already editable. 2391 */ 2392 public final void append(CharSequence text) { 2393 append(text, 0, text.length()); 2394 } 2395 2396 /** 2397 * Convenience method: Append the specified text slice to the TextView's 2398 * display buffer, upgrading it to BufferType.EDITABLE if it was 2399 * not already editable. 2400 */ 2401 public void append(CharSequence text, int start, int end) { 2402 if (!(mText instanceof Editable)) { 2403 setText(mText, BufferType.EDITABLE); 2404 } 2405 2406 ((Editable) mText).append(text, start, end); 2407 } 2408 2409 private void updateTextColors() { 2410 boolean inval = false; 2411 int color = mTextColor.getColorForState(getDrawableState(), 0); 2412 if (color != mCurTextColor) { 2413 mCurTextColor = color; 2414 inval = true; 2415 } 2416 if (mLinkTextColor != null) { 2417 color = mLinkTextColor.getColorForState(getDrawableState(), 0); 2418 if (color != mTextPaint.linkColor) { 2419 mTextPaint.linkColor = color; 2420 inval = true; 2421 } 2422 } 2423 if (mHintTextColor != null) { 2424 color = mHintTextColor.getColorForState(getDrawableState(), 0); 2425 if (color != mCurHintTextColor && mText.length() == 0) { 2426 mCurHintTextColor = color; 2427 inval = true; 2428 } 2429 } 2430 if (inval) { 2431 invalidate(); 2432 } 2433 } 2434 2435 @Override 2436 protected void drawableStateChanged() { 2437 super.drawableStateChanged(); 2438 if (mTextColor != null && mTextColor.isStateful() 2439 || (mHintTextColor != null && mHintTextColor.isStateful()) 2440 || (mLinkTextColor != null && mLinkTextColor.isStateful())) { 2441 updateTextColors(); 2442 } 2443 2444 final Drawables dr = mDrawables; 2445 if (dr != null) { 2446 int[] state = getDrawableState(); 2447 if (dr.mDrawableTop != null && dr.mDrawableTop.isStateful()) { 2448 dr.mDrawableTop.setState(state); 2449 } 2450 if (dr.mDrawableBottom != null && dr.mDrawableBottom.isStateful()) { 2451 dr.mDrawableBottom.setState(state); 2452 } 2453 if (dr.mDrawableLeft != null && dr.mDrawableLeft.isStateful()) { 2454 dr.mDrawableLeft.setState(state); 2455 } 2456 if (dr.mDrawableRight != null && dr.mDrawableRight.isStateful()) { 2457 dr.mDrawableRight.setState(state); 2458 } 2459 } 2460 } 2461 2462 /** 2463 * User interface state that is stored by TextView for implementing 2464 * {@link View#onSaveInstanceState}. 2465 */ 2466 public static class SavedState extends BaseSavedState { 2467 int selStart; 2468 int selEnd; 2469 CharSequence text; 2470 boolean frozenWithFocus; 2471 CharSequence error; 2472 2473 SavedState(Parcelable superState) { 2474 super(superState); 2475 } 2476 2477 @Override 2478 public void writeToParcel(Parcel out, int flags) { 2479 super.writeToParcel(out, flags); 2480 out.writeInt(selStart); 2481 out.writeInt(selEnd); 2482 out.writeInt(frozenWithFocus ? 1 : 0); 2483 TextUtils.writeToParcel(text, out, flags); 2484 2485 if (error == null) { 2486 out.writeInt(0); 2487 } else { 2488 out.writeInt(1); 2489 TextUtils.writeToParcel(error, out, flags); 2490 } 2491 } 2492 2493 @Override 2494 public String toString() { 2495 String str = "TextView.SavedState{" 2496 + Integer.toHexString(System.identityHashCode(this)) 2497 + " start=" + selStart + " end=" + selEnd; 2498 if (text != null) { 2499 str += " text=" + text; 2500 } 2501 return str + "}"; 2502 } 2503 2504 @SuppressWarnings("hiding") 2505 public static final Parcelable.Creator<SavedState> CREATOR 2506 = new Parcelable.Creator<SavedState>() { 2507 public SavedState createFromParcel(Parcel in) { 2508 return new SavedState(in); 2509 } 2510 2511 public SavedState[] newArray(int size) { 2512 return new SavedState[size]; 2513 } 2514 }; 2515 2516 private SavedState(Parcel in) { 2517 super(in); 2518 selStart = in.readInt(); 2519 selEnd = in.readInt(); 2520 frozenWithFocus = (in.readInt() != 0); 2521 text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 2522 2523 if (in.readInt() != 0) { 2524 error = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 2525 } 2526 } 2527 } 2528 2529 @Override 2530 public Parcelable onSaveInstanceState() { 2531 Parcelable superState = super.onSaveInstanceState(); 2532 2533 // Save state if we are forced to 2534 boolean save = mFreezesText; 2535 int start = 0; 2536 int end = 0; 2537 2538 if (mText != null) { 2539 start = getSelectionStart(); 2540 end = getSelectionEnd(); 2541 if (start >= 0 || end >= 0) { 2542 // Or save state if there is a selection 2543 save = true; 2544 } 2545 } 2546 2547 if (save) { 2548 SavedState ss = new SavedState(superState); 2549 // XXX Should also save the current scroll position! 2550 ss.selStart = start; 2551 ss.selEnd = end; 2552 2553 if (mText instanceof Spanned) { 2554 /* 2555 * Calling setText() strips off any ChangeWatchers; 2556 * strip them now to avoid leaking references. 2557 * But do it to a copy so that if there are any 2558 * further changes to the text of this view, it 2559 * won't get into an inconsistent state. 2560 */ 2561 2562 Spannable sp = new SpannableString(mText); 2563 2564 for (ChangeWatcher cw : 2565 sp.getSpans(0, sp.length(), ChangeWatcher.class)) { 2566 sp.removeSpan(cw); 2567 } 2568 2569 // hideControllers would do it, but it gets called after this method on rotation 2570 sp.removeSpan(mSuggestionRangeSpan); 2571 2572 ss.text = sp; 2573 } else { 2574 ss.text = mText.toString(); 2575 } 2576 2577 if (isFocused() && start >= 0 && end >= 0) { 2578 ss.frozenWithFocus = true; 2579 } 2580 2581 ss.error = mError; 2582 2583 return ss; 2584 } 2585 2586 return superState; 2587 } 2588 2589 @Override 2590 public void onRestoreInstanceState(Parcelable state) { 2591 if (!(state instanceof SavedState)) { 2592 super.onRestoreInstanceState(state); 2593 return; 2594 } 2595 2596 SavedState ss = (SavedState)state; 2597 super.onRestoreInstanceState(ss.getSuperState()); 2598 2599 // XXX restore buffer type too, as well as lots of other stuff 2600 if (ss.text != null) { 2601 setText(ss.text); 2602 } 2603 2604 if (ss.selStart >= 0 && ss.selEnd >= 0) { 2605 if (mText instanceof Spannable) { 2606 int len = mText.length(); 2607 2608 if (ss.selStart > len || ss.selEnd > len) { 2609 String restored = ""; 2610 2611 if (ss.text != null) { 2612 restored = "(restored) "; 2613 } 2614 2615 Log.e(LOG_TAG, "Saved cursor position " + ss.selStart + 2616 "/" + ss.selEnd + " out of range for " + restored + 2617 "text " + mText); 2618 } else { 2619 Selection.setSelection((Spannable) mText, ss.selStart, 2620 ss.selEnd); 2621 2622 if (ss.frozenWithFocus) { 2623 mFrozenWithFocus = true; 2624 } 2625 } 2626 } 2627 } 2628 2629 if (ss.error != null) { 2630 final CharSequence error = ss.error; 2631 // Display the error later, after the first layout pass 2632 post(new Runnable() { 2633 public void run() { 2634 setError(error); 2635 } 2636 }); 2637 } 2638 } 2639 2640 /** 2641 * Control whether this text view saves its entire text contents when 2642 * freezing to an icicle, in addition to dynamic state such as cursor 2643 * position. By default this is false, not saving the text. Set to true 2644 * if the text in the text view is not being saved somewhere else in 2645 * persistent storage (such as in a content provider) so that if the 2646 * view is later thawed the user will not lose their data. 2647 * 2648 * @param freezesText Controls whether a frozen icicle should include the 2649 * entire text data: true to include it, false to not. 2650 * 2651 * @attr ref android.R.styleable#TextView_freezesText 2652 */ 2653 @android.view.RemotableViewMethod 2654 public void setFreezesText(boolean freezesText) { 2655 mFreezesText = freezesText; 2656 } 2657 2658 /** 2659 * Return whether this text view is including its entire text contents 2660 * in frozen icicles. 2661 * 2662 * @return Returns true if text is included, false if it isn't. 2663 * 2664 * @see #setFreezesText 2665 */ 2666 public boolean getFreezesText() { 2667 return mFreezesText; 2668 } 2669 2670 /////////////////////////////////////////////////////////////////////////// 2671 2672 /** 2673 * Sets the Factory used to create new Editables. 2674 */ 2675 public final void setEditableFactory(Editable.Factory factory) { 2676 mEditableFactory = factory; 2677 setText(mText); 2678 } 2679 2680 /** 2681 * Sets the Factory used to create new Spannables. 2682 */ 2683 public final void setSpannableFactory(Spannable.Factory factory) { 2684 mSpannableFactory = factory; 2685 setText(mText); 2686 } 2687 2688 /** 2689 * Sets the string value of the TextView. TextView <em>does not</em> accept 2690 * HTML-like formatting, which you can do with text strings in XML resource files. 2691 * To style your strings, attach android.text.style.* objects to a 2692 * {@link android.text.SpannableString SpannableString}, or see the 2693 * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources"> 2694 * Available Resource Types</a> documentation for an example of setting 2695 * formatted text in the XML resource file. 2696 * 2697 * @attr ref android.R.styleable#TextView_text 2698 */ 2699 @android.view.RemotableViewMethod 2700 public final void setText(CharSequence text) { 2701 setText(text, mBufferType); 2702 } 2703 2704 /** 2705 * Like {@link #setText(CharSequence)}, 2706 * except that the cursor position (if any) is retained in the new text. 2707 * 2708 * @param text The new text to place in the text view. 2709 * 2710 * @see #setText(CharSequence) 2711 */ 2712 @android.view.RemotableViewMethod 2713 public final void setTextKeepState(CharSequence text) { 2714 setTextKeepState(text, mBufferType); 2715 } 2716 2717 /** 2718 * Sets the text that this TextView is to display (see 2719 * {@link #setText(CharSequence)}) and also sets whether it is stored 2720 * in a styleable/spannable buffer and whether it is editable. 2721 * 2722 * @attr ref android.R.styleable#TextView_text 2723 * @attr ref android.R.styleable#TextView_bufferType 2724 */ 2725 public void setText(CharSequence text, BufferType type) { 2726 setText(text, type, true, 0); 2727 2728 if (mCharWrapper != null) { 2729 mCharWrapper.mChars = null; 2730 } 2731 } 2732 2733 private void setText(CharSequence text, BufferType type, 2734 boolean notifyBefore, int oldlen) { 2735 if (text == null) { 2736 text = ""; 2737 } 2738 2739 if (!mUserSetTextScaleX) mTextPaint.setTextScaleX(1.0f); 2740 2741 if (text instanceof Spanned && 2742 ((Spanned) text).getSpanStart(TextUtils.TruncateAt.MARQUEE) >= 0) { 2743 setHorizontalFadingEdgeEnabled(true); 2744 setEllipsize(TextUtils.TruncateAt.MARQUEE); 2745 } 2746 2747 int n = mFilters.length; 2748 for (int i = 0; i < n; i++) { 2749 CharSequence out = mFilters[i].filter(text, 0, text.length(), 2750 EMPTY_SPANNED, 0, 0); 2751 if (out != null) { 2752 text = out; 2753 } 2754 } 2755 2756 if (notifyBefore) { 2757 if (mText != null) { 2758 oldlen = mText.length(); 2759 sendBeforeTextChanged(mText, 0, oldlen, text.length()); 2760 } else { 2761 sendBeforeTextChanged("", 0, 0, text.length()); 2762 } 2763 } 2764 2765 boolean needEditableForNotification = false; 2766 2767 if (mListeners != null && mListeners.size() != 0) { 2768 needEditableForNotification = true; 2769 } 2770 2771 if (type == BufferType.EDITABLE || mInput != null || 2772 needEditableForNotification) { 2773 Editable t = mEditableFactory.newEditable(text); 2774 text = t; 2775 setFilters(t, mFilters); 2776 InputMethodManager imm = InputMethodManager.peekInstance(); 2777 if (imm != null) imm.restartInput(this); 2778 } else if (type == BufferType.SPANNABLE || mMovement != null) { 2779 text = mSpannableFactory.newSpannable(text); 2780 } else if (!(text instanceof CharWrapper)) { 2781 text = TextUtils.stringOrSpannedString(text); 2782 } 2783 2784 if (mAutoLinkMask != 0) { 2785 Spannable s2; 2786 2787 if (type == BufferType.EDITABLE || text instanceof Spannable) { 2788 s2 = (Spannable) text; 2789 } else { 2790 s2 = mSpannableFactory.newSpannable(text); 2791 } 2792 2793 if (Linkify.addLinks(s2, mAutoLinkMask)) { 2794 text = s2; 2795 type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE; 2796 2797 /* 2798 * We must go ahead and set the text before changing the 2799 * movement method, because setMovementMethod() may call 2800 * setText() again to try to upgrade the buffer type. 2801 */ 2802 mText = text; 2803 2804 // Do not change the movement method for text that support text selection as it 2805 // would prevent an arbitrary cursor displacement. 2806 final boolean hasTextSelection = this instanceof EditText || mTextIsSelectable; 2807 if (mLinksClickable && !hasTextSelection) { 2808 setMovementMethod(LinkMovementMethod.getInstance()); 2809 } 2810 } 2811 } 2812 2813 mBufferType = type; 2814 mText = text; 2815 2816 if (mTransformation == null) 2817 mTransformed = text; 2818 else 2819 mTransformed = mTransformation.getTransformation(text, this); 2820 2821 final int textLength = text.length(); 2822 2823 if (text instanceof Spannable) { 2824 Spannable sp = (Spannable) text; 2825 2826 // Remove any ChangeWatchers that might have come 2827 // from other TextViews. 2828 final ChangeWatcher[] watchers = sp.getSpans(0, sp.length(), ChangeWatcher.class); 2829 final int count = watchers.length; 2830 for (int i = 0; i < count; i++) 2831 sp.removeSpan(watchers[i]); 2832 2833 if (mChangeWatcher == null) 2834 mChangeWatcher = new ChangeWatcher(); 2835 2836 sp.setSpan(mChangeWatcher, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE | 2837 (PRIORITY << Spanned.SPAN_PRIORITY_SHIFT)); 2838 2839 if (mInput != null) { 2840 sp.setSpan(mInput, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 2841 } 2842 2843 if (mTransformation != null) { 2844 sp.setSpan(mTransformation, 0, textLength, Spanned.SPAN_INCLUSIVE_INCLUSIVE); 2845 2846 } 2847 2848 if (mMovement != null) { 2849 mMovement.initialize(this, (Spannable) text); 2850 2851 /* 2852 * Initializing the movement method will have set the 2853 * selection, so reset mSelectionMoved to keep that from 2854 * interfering with the normal on-focus selection-setting. 2855 */ 2856 mSelectionMoved = false; 2857 } 2858 } 2859 2860 if (mLayout != null) { 2861 checkForRelayout(); 2862 } 2863 2864 sendOnTextChanged(text, 0, oldlen, textLength); 2865 onTextChanged(text, 0, oldlen, textLength); 2866 2867 if (needEditableForNotification) { 2868 sendAfterTextChanged((Editable) text); 2869 } 2870 2871 // SelectionModifierCursorController depends on textCanBeSelected, which depends on text 2872 prepareCursorControllers(); 2873 } 2874 2875 /** 2876 * Sets the TextView to display the specified slice of the specified 2877 * char array. You must promise that you will not change the contents 2878 * of the array except for right before another call to setText(), 2879 * since the TextView has no way to know that the text 2880 * has changed and that it needs to invalidate and re-layout. 2881 */ 2882 public final void setText(char[] text, int start, int len) { 2883 int oldlen = 0; 2884 2885 if (start < 0 || len < 0 || start + len > text.length) { 2886 throw new IndexOutOfBoundsException(start + ", " + len); 2887 } 2888 2889 /* 2890 * We must do the before-notification here ourselves because if 2891 * the old text is a CharWrapper we destroy it before calling 2892 * into the normal path. 2893 */ 2894 if (mText != null) { 2895 oldlen = mText.length(); 2896 sendBeforeTextChanged(mText, 0, oldlen, len); 2897 } else { 2898 sendBeforeTextChanged("", 0, 0, len); 2899 } 2900 2901 if (mCharWrapper == null) { 2902 mCharWrapper = new CharWrapper(text, start, len); 2903 } else { 2904 mCharWrapper.set(text, start, len); 2905 } 2906 2907 setText(mCharWrapper, mBufferType, false, oldlen); 2908 } 2909 2910 private static class CharWrapper implements CharSequence, GetChars, GraphicsOperations { 2911 private char[] mChars; 2912 private int mStart, mLength; 2913 2914 public CharWrapper(char[] chars, int start, int len) { 2915 mChars = chars; 2916 mStart = start; 2917 mLength = len; 2918 } 2919 2920 /* package */ void set(char[] chars, int start, int len) { 2921 mChars = chars; 2922 mStart = start; 2923 mLength = len; 2924 } 2925 2926 public int length() { 2927 return mLength; 2928 } 2929 2930 public char charAt(int off) { 2931 return mChars[off + mStart]; 2932 } 2933 2934 @Override 2935 public String toString() { 2936 return new String(mChars, mStart, mLength); 2937 } 2938 2939 public CharSequence subSequence(int start, int end) { 2940 if (start < 0 || end < 0 || start > mLength || end > mLength) { 2941 throw new IndexOutOfBoundsException(start + ", " + end); 2942 } 2943 2944 return new String(mChars, start + mStart, end - start); 2945 } 2946 2947 public void getChars(int start, int end, char[] buf, int off) { 2948 if (start < 0 || end < 0 || start > mLength || end > mLength) { 2949 throw new IndexOutOfBoundsException(start + ", " + end); 2950 } 2951 2952 System.arraycopy(mChars, start + mStart, buf, off, end - start); 2953 } 2954 2955 public void drawText(Canvas c, int start, int end, 2956 float x, float y, Paint p) { 2957 c.drawText(mChars, start + mStart, end - start, x, y, p); 2958 } 2959 2960 public void drawTextRun(Canvas c, int start, int end, 2961 int contextStart, int contextEnd, float x, float y, int flags, Paint p) { 2962 int count = end - start; 2963 int contextCount = contextEnd - contextStart; 2964 c.drawTextRun(mChars, start + mStart, count, contextStart + mStart, 2965 contextCount, x, y, flags, p); 2966 } 2967 2968 public float measureText(int start, int end, Paint p) { 2969 return p.measureText(mChars, start + mStart, end - start); 2970 } 2971 2972 public int getTextWidths(int start, int end, float[] widths, Paint p) { 2973 return p.getTextWidths(mChars, start + mStart, end - start, widths); 2974 } 2975 2976 public float getTextRunAdvances(int start, int end, int contextStart, 2977 int contextEnd, int flags, float[] advances, int advancesIndex, 2978 Paint p) { 2979 int count = end - start; 2980 int contextCount = contextEnd - contextStart; 2981 return p.getTextRunAdvances(mChars, start + mStart, count, 2982 contextStart + mStart, contextCount, flags, advances, 2983 advancesIndex); 2984 } 2985 2986 public float getTextRunAdvances(int start, int end, int contextStart, 2987 int contextEnd, int flags, float[] advances, int advancesIndex, 2988 Paint p, int reserved) { 2989 int count = end - start; 2990 int contextCount = contextEnd - contextStart; 2991 return p.getTextRunAdvances(mChars, start + mStart, count, 2992 contextStart + mStart, contextCount, flags, advances, 2993 advancesIndex, reserved); 2994 } 2995 2996 public int getTextRunCursor(int contextStart, int contextEnd, int flags, 2997 int offset, int cursorOpt, Paint p) { 2998 int contextCount = contextEnd - contextStart; 2999 return p.getTextRunCursor(mChars, contextStart + mStart, 3000 contextCount, flags, offset + mStart, cursorOpt); 3001 } 3002 } 3003 3004 /** 3005 * Like {@link #setText(CharSequence, android.widget.TextView.BufferType)}, 3006 * except that the cursor position (if any) is retained in the new text. 3007 * 3008 * @see #setText(CharSequence, android.widget.TextView.BufferType) 3009 */ 3010 public final void setTextKeepState(CharSequence text, BufferType type) { 3011 int start = getSelectionStart(); 3012 int end = getSelectionEnd(); 3013 int len = text.length(); 3014 3015 setText(text, type); 3016 3017 if (start >= 0 || end >= 0) { 3018 if (mText instanceof Spannable) { 3019 Selection.setSelection((Spannable) mText, 3020 Math.max(0, Math.min(start, len)), 3021 Math.max(0, Math.min(end, len))); 3022 } 3023 } 3024 } 3025 3026 @android.view.RemotableViewMethod 3027 public final void setText(int resid) { 3028 setText(getContext().getResources().getText(resid)); 3029 } 3030 3031 public final void setText(int resid, BufferType type) { 3032 setText(getContext().getResources().getText(resid), type); 3033 } 3034 3035 /** 3036 * Sets the text to be displayed when the text of the TextView is empty. 3037 * Null means to use the normal empty text. The hint does not currently 3038 * participate in determining the size of the view. 3039 * 3040 * @attr ref android.R.styleable#TextView_hint 3041 */ 3042 @android.view.RemotableViewMethod 3043 public final void setHint(CharSequence hint) { 3044 mHint = TextUtils.stringOrSpannedString(hint); 3045 3046 if (mLayout != null) { 3047 checkForRelayout(); 3048 } 3049 3050 if (mText.length() == 0) { 3051 invalidate(); 3052 } 3053 } 3054 3055 /** 3056 * Sets the text to be displayed when the text of the TextView is empty, 3057 * from a resource. 3058 * 3059 * @attr ref android.R.styleable#TextView_hint 3060 */ 3061 @android.view.RemotableViewMethod 3062 public final void setHint(int resid) { 3063 setHint(getContext().getResources().getText(resid)); 3064 } 3065 3066 /** 3067 * Returns the hint that is displayed when the text of the TextView 3068 * is empty. 3069 * 3070 * @attr ref android.R.styleable#TextView_hint 3071 */ 3072 @ViewDebug.CapturedViewProperty 3073 public CharSequence getHint() { 3074 return mHint; 3075 } 3076 3077 private boolean isMultilineInputType(int type) { 3078 return (type & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == 3079 (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); 3080 } 3081 3082 /** 3083 * Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This 3084 * will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)}, 3085 * to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL} 3086 * then a soft keyboard will not be displayed for this text view. 3087 * 3088 * Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be 3089 * modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input 3090 * type. 3091 * 3092 * @see #getInputType() 3093 * @see #setRawInputType(int) 3094 * @see android.text.InputType 3095 * @attr ref android.R.styleable#TextView_inputType 3096 */ 3097 public void setInputType(int type) { 3098 final boolean wasPassword = isPasswordInputType(mInputType); 3099 final boolean wasVisiblePassword = isVisiblePasswordInputType(mInputType); 3100 setInputType(type, false); 3101 final boolean isPassword = isPasswordInputType(type); 3102 final boolean isVisiblePassword = isVisiblePasswordInputType(type); 3103 boolean forceUpdate = false; 3104 if (isPassword) { 3105 setTransformationMethod(PasswordTransformationMethod.getInstance()); 3106 setTypefaceByIndex(MONOSPACE, 0); 3107 } else if (isVisiblePassword) { 3108 if (mTransformation == PasswordTransformationMethod.getInstance()) { 3109 forceUpdate = true; 3110 } 3111 setTypefaceByIndex(MONOSPACE, 0); 3112 } else if (wasPassword || wasVisiblePassword) { 3113 // not in password mode, clean up typeface and transformation 3114 setTypefaceByIndex(-1, -1); 3115 if (mTransformation == PasswordTransformationMethod.getInstance()) { 3116 forceUpdate = true; 3117 } 3118 } 3119 3120 boolean singleLine = !isMultilineInputType(type); 3121 3122 // We need to update the single line mode if it has changed or we 3123 // were previously in password mode. 3124 if (mSingleLine != singleLine || forceUpdate) { 3125 // Change single line mode, but only change the transformation if 3126 // we are not in password mode. 3127 applySingleLine(singleLine, !isPassword, true); 3128 } 3129 3130 InputMethodManager imm = InputMethodManager.peekInstance(); 3131 if (imm != null) imm.restartInput(this); 3132 } 3133 3134 /** 3135 * It would be better to rely on the input type for everything. A password inputType should have 3136 * a password transformation. We should hence use isPasswordInputType instead of this method. 3137 * 3138 * We should: 3139 * - Call setInputType in setKeyListener instead of changing the input type directly (which 3140 * would install the correct transformation). 3141 * - Refuse the installation of a non-password transformation in setTransformation if the input 3142 * type is password. 3143 * 3144 * However, this is like this for legacy reasons and we cannot break existing apps. This method 3145 * is useful since it matches what the user can see (obfuscated text or not). 3146 * 3147 * @return true if the current transformation method is of the password type. 3148 */ 3149 private boolean hasPasswordTransformationMethod() { 3150 return mTransformation instanceof PasswordTransformationMethod; 3151 } 3152 3153 private boolean isPasswordInputType(int inputType) { 3154 final int variation = 3155 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 3156 return variation 3157 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD) 3158 || variation 3159 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_WEB_PASSWORD) 3160 || variation 3161 == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD); 3162 } 3163 3164 private boolean isVisiblePasswordInputType(int inputType) { 3165 final int variation = 3166 inputType & (EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_MASK_VARIATION); 3167 return variation 3168 == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); 3169 } 3170 3171 /** 3172 * Directly change the content type integer of the text view, without 3173 * modifying any other state. 3174 * @see #setInputType(int) 3175 * @see android.text.InputType 3176 * @attr ref android.R.styleable#TextView_inputType 3177 */ 3178 public void setRawInputType(int type) { 3179 mInputType = type; 3180 } 3181 3182 private void setInputType(int type, boolean direct) { 3183 final int cls = type & EditorInfo.TYPE_MASK_CLASS; 3184 KeyListener input; 3185 if (cls == EditorInfo.TYPE_CLASS_TEXT) { 3186 boolean autotext = (type & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) != 0; 3187 TextKeyListener.Capitalize cap; 3188 if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_CHARACTERS) != 0) { 3189 cap = TextKeyListener.Capitalize.CHARACTERS; 3190 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_WORDS) != 0) { 3191 cap = TextKeyListener.Capitalize.WORDS; 3192 } else if ((type & EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES) != 0) { 3193 cap = TextKeyListener.Capitalize.SENTENCES; 3194 } else { 3195 cap = TextKeyListener.Capitalize.NONE; 3196 } 3197 input = TextKeyListener.getInstance(autotext, cap); 3198 } else if (cls == EditorInfo.TYPE_CLASS_NUMBER) { 3199 input = DigitsKeyListener.getInstance( 3200 (type & EditorInfo.TYPE_NUMBER_FLAG_SIGNED) != 0, 3201 (type & EditorInfo.TYPE_NUMBER_FLAG_DECIMAL) != 0); 3202 } else if (cls == EditorInfo.TYPE_CLASS_DATETIME) { 3203 switch (type & EditorInfo.TYPE_MASK_VARIATION) { 3204 case EditorInfo.TYPE_DATETIME_VARIATION_DATE: 3205 input = DateKeyListener.getInstance(); 3206 break; 3207 case EditorInfo.TYPE_DATETIME_VARIATION_TIME: 3208 input = TimeKeyListener.getInstance(); 3209 break; 3210 default: 3211 input = DateTimeKeyListener.getInstance(); 3212 break; 3213 } 3214 } else if (cls == EditorInfo.TYPE_CLASS_PHONE) { 3215 input = DialerKeyListener.getInstance(); 3216 } else { 3217 input = TextKeyListener.getInstance(); 3218 } 3219 setRawInputType(type); 3220 if (direct) mInput = input; 3221 else { 3222 setKeyListenerOnly(input); 3223 } 3224 } 3225 3226 /** 3227 * Get the type of the content. 3228 * 3229 * @see #setInputType(int) 3230 * @see android.text.InputType 3231 */ 3232 public int getInputType() { 3233 return mInputType; 3234 } 3235 3236 /** 3237 * Change the editor type integer associated with the text view, which 3238 * will be reported to an IME with {@link EditorInfo#imeOptions} when it 3239 * has focus. 3240 * @see #getImeOptions 3241 * @see android.view.inputmethod.EditorInfo 3242 * @attr ref android.R.styleable#TextView_imeOptions 3243 */ 3244 public void setImeOptions(int imeOptions) { 3245 if (mInputContentType == null) { 3246 mInputContentType = new InputContentType(); 3247 } 3248 mInputContentType.imeOptions = imeOptions; 3249 } 3250 3251 /** 3252 * Get the type of the IME editor. 3253 * 3254 * @see #setImeOptions(int) 3255 * @see android.view.inputmethod.EditorInfo 3256 */ 3257 public int getImeOptions() { 3258 return mInputContentType != null 3259 ? mInputContentType.imeOptions : EditorInfo.IME_NULL; 3260 } 3261 3262 /** 3263 * Change the custom IME action associated with the text view, which 3264 * will be reported to an IME with {@link EditorInfo#actionLabel} 3265 * and {@link EditorInfo#actionId} when it has focus. 3266 * @see #getImeActionLabel 3267 * @see #getImeActionId 3268 * @see android.view.inputmethod.EditorInfo 3269 * @attr ref android.R.styleable#TextView_imeActionLabel 3270 * @attr ref android.R.styleable#TextView_imeActionId 3271 */ 3272 public void setImeActionLabel(CharSequence label, int actionId) { 3273 if (mInputContentType == null) { 3274 mInputContentType = new InputContentType(); 3275 } 3276 mInputContentType.imeActionLabel = label; 3277 mInputContentType.imeActionId = actionId; 3278 } 3279 3280 /** 3281 * Get the IME action label previous set with {@link #setImeActionLabel}. 3282 * 3283 * @see #setImeActionLabel 3284 * @see android.view.inputmethod.EditorInfo 3285 */ 3286 public CharSequence getImeActionLabel() { 3287 return mInputContentType != null 3288 ? mInputContentType.imeActionLabel : null; 3289 } 3290 3291 /** 3292 * Get the IME action ID previous set with {@link #setImeActionLabel}. 3293 * 3294 * @see #setImeActionLabel 3295 * @see android.view.inputmethod.EditorInfo 3296 */ 3297 public int getImeActionId() { 3298 return mInputContentType != null 3299 ? mInputContentType.imeActionId : 0; 3300 } 3301 3302 /** 3303 * Set a special listener to be called when an action is performed 3304 * on the text view. This will be called when the enter key is pressed, 3305 * or when an action supplied to the IME is selected by the user. Setting 3306 * this means that the normal hard key event will not insert a newline 3307 * into the text view, even if it is multi-line; holding down the ALT 3308 * modifier will, however, allow the user to insert a newline character. 3309 */ 3310 public void setOnEditorActionListener(OnEditorActionListener l) { 3311 if (mInputContentType == null) { 3312 mInputContentType = new InputContentType(); 3313 } 3314 mInputContentType.onEditorActionListener = l; 3315 } 3316 3317 /** 3318 * Called when an attached input method calls 3319 * {@link InputConnection#performEditorAction(int) 3320 * InputConnection.performEditorAction()} 3321 * for this text view. The default implementation will call your action 3322 * listener supplied to {@link #setOnEditorActionListener}, or perform 3323 * a standard operation for {@link EditorInfo#IME_ACTION_NEXT 3324 * EditorInfo.IME_ACTION_NEXT}, {@link EditorInfo#IME_ACTION_PREVIOUS 3325 * EditorInfo.IME_ACTION_PREVIOUS}, or {@link EditorInfo#IME_ACTION_DONE 3326 * EditorInfo.IME_ACTION_DONE}. 3327 * 3328 * <p>For backwards compatibility, if no IME options have been set and the 3329 * text view would not normally advance focus on enter, then 3330 * the NEXT and DONE actions received here will be turned into an enter 3331 * key down/up pair to go through the normal key handling. 3332 * 3333 * @param actionCode The code of the action being performed. 3334 * 3335 * @see #setOnEditorActionListener 3336 */ 3337 public void onEditorAction(int actionCode) { 3338 final InputContentType ict = mInputContentType; 3339 if (ict != null) { 3340 if (ict.onEditorActionListener != null) { 3341 if (ict.onEditorActionListener.onEditorAction(this, 3342 actionCode, null)) { 3343 return; 3344 } 3345 } 3346 3347 // This is the handling for some default action. 3348 // Note that for backwards compatibility we don't do this 3349 // default handling if explicit ime options have not been given, 3350 // instead turning this into the normal enter key codes that an 3351 // app may be expecting. 3352 if (actionCode == EditorInfo.IME_ACTION_NEXT) { 3353 View v = focusSearch(FOCUS_DOWN); 3354 if (v != null) { 3355 if (!v.requestFocus(FOCUS_DOWN)) { 3356 throw new IllegalStateException("focus search returned a view " + 3357 "that wasn't able to take focus!"); 3358 } 3359 } 3360 return; 3361 3362 } else if (actionCode == EditorInfo.IME_ACTION_PREVIOUS) { 3363 View v = focusSearch(FOCUS_UP); 3364 if (v != null) { 3365 if (!v.requestFocus(FOCUS_UP)) { 3366 throw new IllegalStateException("focus search returned a view " + 3367 "that wasn't able to take focus!"); 3368 } 3369 } 3370 return; 3371 3372 } else if (actionCode == EditorInfo.IME_ACTION_DONE) { 3373 InputMethodManager imm = InputMethodManager.peekInstance(); 3374 if (imm != null && imm.isActive(this)) { 3375 imm.hideSoftInputFromWindow(getWindowToken(), 0); 3376 } 3377 return; 3378 } 3379 } 3380 3381 Handler h = getHandler(); 3382 if (h != null) { 3383 long eventTime = SystemClock.uptimeMillis(); 3384 h.sendMessage(h.obtainMessage(ViewAncestor.DISPATCH_KEY_FROM_IME, 3385 new KeyEvent(eventTime, eventTime, 3386 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, 3387 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3388 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3389 | KeyEvent.FLAG_EDITOR_ACTION))); 3390 h.sendMessage(h.obtainMessage(ViewAncestor.DISPATCH_KEY_FROM_IME, 3391 new KeyEvent(SystemClock.uptimeMillis(), eventTime, 3392 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 3393 KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 3394 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 3395 | KeyEvent.FLAG_EDITOR_ACTION))); 3396 } 3397 } 3398 3399 /** 3400 * Set the private content type of the text, which is the 3401 * {@link EditorInfo#privateImeOptions EditorInfo.privateImeOptions} 3402 * field that will be filled in when creating an input connection. 3403 * 3404 * @see #getPrivateImeOptions() 3405 * @see EditorInfo#privateImeOptions 3406 * @attr ref android.R.styleable#TextView_privateImeOptions 3407 */ 3408 public void setPrivateImeOptions(String type) { 3409 if (mInputContentType == null) mInputContentType = new InputContentType(); 3410 mInputContentType.privateImeOptions = type; 3411 } 3412 3413 /** 3414 * Get the private type of the content. 3415 * 3416 * @see #setPrivateImeOptions(String) 3417 * @see EditorInfo#privateImeOptions 3418 */ 3419 public String getPrivateImeOptions() { 3420 return mInputContentType != null 3421 ? mInputContentType.privateImeOptions : null; 3422 } 3423 3424 /** 3425 * Set the extra input data of the text, which is the 3426 * {@link EditorInfo#extras TextBoxAttribute.extras} 3427 * Bundle that will be filled in when creating an input connection. The 3428 * given integer is the resource ID of an XML resource holding an 3429 * {@link android.R.styleable#InputExtras <input-extras>} XML tree. 3430 * 3431 * @see #getInputExtras(boolean) 3432 * @see EditorInfo#extras 3433 * @attr ref android.R.styleable#TextView_editorExtras 3434 */ 3435 public void setInputExtras(int xmlResId) 3436 throws XmlPullParserException, IOException { 3437 XmlResourceParser parser = getResources().getXml(xmlResId); 3438 if (mInputContentType == null) mInputContentType = new InputContentType(); 3439 mInputContentType.extras = new Bundle(); 3440 getResources().parseBundleExtras(parser, mInputContentType.extras); 3441 } 3442 3443 /** 3444 * Retrieve the input extras currently associated with the text view, which 3445 * can be viewed as well as modified. 3446 * 3447 * @param create If true, the extras will be created if they don't already 3448 * exist. Otherwise, null will be returned if none have been created. 3449 * @see #setInputExtras(int) 3450 * @see EditorInfo#extras 3451 * @attr ref android.R.styleable#TextView_editorExtras 3452 */ 3453 public Bundle getInputExtras(boolean create) { 3454 if (mInputContentType == null) { 3455 if (!create) return null; 3456 mInputContentType = new InputContentType(); 3457 } 3458 if (mInputContentType.extras == null) { 3459 if (!create) return null; 3460 mInputContentType.extras = new Bundle(); 3461 } 3462 return mInputContentType.extras; 3463 } 3464 3465 /** 3466 * Returns the error message that was set to be displayed with 3467 * {@link #setError}, or <code>null</code> if no error was set 3468 * or if it the error was cleared by the widget after user input. 3469 */ 3470 public CharSequence getError() { 3471 return mError; 3472 } 3473 3474 /** 3475 * Sets the right-hand compound drawable of the TextView to the "error" 3476 * icon and sets an error message that will be displayed in a popup when 3477 * the TextView has focus. The icon and error message will be reset to 3478 * null when any key events cause changes to the TextView's text. If the 3479 * <code>error</code> is <code>null</code>, the error message and icon 3480 * will be cleared. 3481 */ 3482 @android.view.RemotableViewMethod 3483 public void setError(CharSequence error) { 3484 if (error == null) { 3485 setError(null, null); 3486 } else { 3487 Drawable dr = getContext().getResources(). 3488 getDrawable(com.android.internal.R.drawable.indicator_input_error); 3489 3490 dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight()); 3491 setError(error, dr); 3492 } 3493 } 3494 3495 /** 3496 * Sets the right-hand compound drawable of the TextView to the specified 3497 * icon and sets an error message that will be displayed in a popup when 3498 * the TextView has focus. The icon and error message will be reset to 3499 * null when any key events cause changes to the TextView's text. The 3500 * drawable must already have had {@link Drawable#setBounds} set on it. 3501 * If the <code>error</code> is <code>null</code>, the error message will 3502 * be cleared (and you should provide a <code>null</code> icon as well). 3503 */ 3504 public void setError(CharSequence error, Drawable icon) { 3505 error = TextUtils.stringOrSpannedString(error); 3506 3507 mError = error; 3508 mErrorWasChanged = true; 3509 final Drawables dr = mDrawables; 3510 if (dr != null) { 3511 setCompoundDrawables(dr.mDrawableLeft, dr.mDrawableTop, icon, dr.mDrawableBottom); 3512 } else { 3513 setCompoundDrawables(null, null, icon, null); 3514 } 3515 3516 if (error == null) { 3517 if (mPopup != null) { 3518 if (mPopup.isShowing()) { 3519 mPopup.dismiss(); 3520 } 3521 3522 mPopup = null; 3523 } 3524 } else { 3525 if (isFocused()) { 3526 showError(); 3527 } 3528 } 3529 } 3530 3531 private void showError() { 3532 if (getWindowToken() == null) { 3533 mShowErrorAfterAttach = true; 3534 return; 3535 } 3536 3537 if (mPopup == null) { 3538 LayoutInflater inflater = LayoutInflater.from(getContext()); 3539 final TextView err = (TextView) inflater.inflate( 3540 com.android.internal.R.layout.textview_hint, null); 3541 3542 final float scale = getResources().getDisplayMetrics().density; 3543 mPopup = new ErrorPopup(err, (int) (200 * scale + 0.5f), (int) (50 * scale + 0.5f)); 3544 mPopup.setFocusable(false); 3545 // The user is entering text, so the input method is needed. We 3546 // don't want the popup to be displayed on top of it. 3547 mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); 3548 } 3549 3550 TextView tv = (TextView) mPopup.getContentView(); 3551 chooseSize(mPopup, mError, tv); 3552 tv.setText(mError); 3553 3554 mPopup.showAsDropDown(this, getErrorX(), getErrorY()); 3555 mPopup.fixDirection(mPopup.isAboveAnchor()); 3556 } 3557 3558 private static class ErrorPopup extends PopupWindow { 3559 private boolean mAbove = false; 3560 private final TextView mView; 3561 private int mPopupInlineErrorBackgroundId = 0; 3562 private int mPopupInlineErrorAboveBackgroundId = 0; 3563 3564 ErrorPopup(TextView v, int width, int height) { 3565 super(v, width, height); 3566 mView = v; 3567 // Make sure the TextView has a background set as it will be used the first time it is 3568 // shown and positionned. Initialized with below background, which should have 3569 // dimensions identical to the above version for this to work (and is more likely). 3570 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3571 com.android.internal.R.styleable.Theme_errorMessageBackground); 3572 mView.setBackgroundResource(mPopupInlineErrorBackgroundId); 3573 } 3574 3575 void fixDirection(boolean above) { 3576 mAbove = above; 3577 3578 if (above) { 3579 mPopupInlineErrorAboveBackgroundId = 3580 getResourceId(mPopupInlineErrorAboveBackgroundId, 3581 com.android.internal.R.styleable.Theme_errorMessageAboveBackground); 3582 } else { 3583 mPopupInlineErrorBackgroundId = getResourceId(mPopupInlineErrorBackgroundId, 3584 com.android.internal.R.styleable.Theme_errorMessageBackground); 3585 } 3586 3587 mView.setBackgroundResource(above ? mPopupInlineErrorAboveBackgroundId : 3588 mPopupInlineErrorBackgroundId); 3589 } 3590 3591 private int getResourceId(int currentId, int index) { 3592 if (currentId == 0) { 3593 TypedArray styledAttributes = mView.getContext().obtainStyledAttributes( 3594 R.styleable.Theme); 3595 currentId = styledAttributes.getResourceId(index, 0); 3596 styledAttributes.recycle(); 3597 } 3598 return currentId; 3599 } 3600 3601 @Override 3602 public void update(int x, int y, int w, int h, boolean force) { 3603 super.update(x, y, w, h, force); 3604 3605 boolean above = isAboveAnchor(); 3606 if (above != mAbove) { 3607 fixDirection(above); 3608 } 3609 } 3610 } 3611 3612 /** 3613 * Returns the Y offset to make the pointy top of the error point 3614 * at the middle of the error icon. 3615 */ 3616 private int getErrorX() { 3617 /* 3618 * The "25" is the distance between the point and the right edge 3619 * of the background 3620 */ 3621 final float scale = getResources().getDisplayMetrics().density; 3622 3623 final Drawables dr = mDrawables; 3624 return getWidth() - mPopup.getWidth() - getPaddingRight() - 3625 (dr != null ? dr.mDrawableSizeRight : 0) / 2 + (int) (25 * scale + 0.5f); 3626 } 3627 3628 /** 3629 * Returns the Y offset to make the pointy top of the error point 3630 * at the bottom of the error icon. 3631 */ 3632 private int getErrorY() { 3633 /* 3634 * Compound, not extended, because the icon is not clipped 3635 * if the text height is smaller. 3636 */ 3637 final int compoundPaddingTop = getCompoundPaddingTop(); 3638 int vspace = mBottom - mTop - getCompoundPaddingBottom() - compoundPaddingTop; 3639 3640 final Drawables dr = mDrawables; 3641 int icontop = compoundPaddingTop + 3642 (vspace - (dr != null ? dr.mDrawableHeightRight : 0)) / 2; 3643 3644 /* 3645 * The "2" is the distance between the point and the top edge 3646 * of the background. 3647 */ 3648 final float scale = getResources().getDisplayMetrics().density; 3649 return icontop + (dr != null ? dr.mDrawableHeightRight : 0) - getHeight() - 3650 (int) (2 * scale + 0.5f); 3651 } 3652 3653 private void hideError() { 3654 if (mPopup != null) { 3655 if (mPopup.isShowing()) { 3656 mPopup.dismiss(); 3657 } 3658 } 3659 3660 mShowErrorAfterAttach = false; 3661 } 3662 3663 private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { 3664 int wid = tv.getPaddingLeft() + tv.getPaddingRight(); 3665 int ht = tv.getPaddingTop() + tv.getPaddingBottom(); 3666 3667 /* 3668 * Figure out how big the text would be if we laid it out to the 3669 * full width of this view minus the border. 3670 */ 3671 int cap = getWidth() - wid; 3672 if (cap < 0) { 3673 cap = 200; // We must not be measured yet -- setFrame() will fix it. 3674 } 3675 3676 Layout l = new StaticLayout(text, tv.getPaint(), cap, 3677 Layout.Alignment.ALIGN_NORMAL, 1, 0, true); 3678 float max = 0; 3679 for (int i = 0; i < l.getLineCount(); i++) { 3680 max = Math.max(max, l.getLineWidth(i)); 3681 } 3682 3683 /* 3684 * Now set the popup size to be big enough for the text plus the border. 3685 */ 3686 pop.setWidth(wid + (int) Math.ceil(max)); 3687 pop.setHeight(ht + l.getHeight()); 3688 } 3689 3690 3691 @Override 3692 protected boolean setFrame(int l, int t, int r, int b) { 3693 boolean result = super.setFrame(l, t, r, b); 3694 3695 if (mPopup != null) { 3696 TextView tv = (TextView) mPopup.getContentView(); 3697 chooseSize(mPopup, mError, tv); 3698 mPopup.update(this, getErrorX(), getErrorY(), 3699 mPopup.getWidth(), mPopup.getHeight()); 3700 } 3701 3702 restartMarqueeIfNeeded(); 3703 3704 return result; 3705 } 3706 3707 private void restartMarqueeIfNeeded() { 3708 if (mRestartMarquee && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 3709 mRestartMarquee = false; 3710 startMarquee(); 3711 } 3712 } 3713 3714 /** 3715 * Sets the list of input filters that will be used if the buffer is 3716 * Editable. Has no effect otherwise. 3717 * 3718 * @attr ref android.R.styleable#TextView_maxLength 3719 */ 3720 public void setFilters(InputFilter[] filters) { 3721 if (filters == null) { 3722 throw new IllegalArgumentException(); 3723 } 3724 3725 mFilters = filters; 3726 3727 if (mText instanceof Editable) { 3728 setFilters((Editable) mText, filters); 3729 } 3730 } 3731 3732 /** 3733 * Sets the list of input filters on the specified Editable, 3734 * and includes mInput in the list if it is an InputFilter. 3735 */ 3736 private void setFilters(Editable e, InputFilter[] filters) { 3737 if (mInput instanceof InputFilter) { 3738 InputFilter[] nf = new InputFilter[filters.length + 1]; 3739 3740 System.arraycopy(filters, 0, nf, 0, filters.length); 3741 nf[filters.length] = (InputFilter) mInput; 3742 3743 e.setFilters(nf); 3744 } else { 3745 e.setFilters(filters); 3746 } 3747 } 3748 3749 /** 3750 * Returns the current list of input filters. 3751 */ 3752 public InputFilter[] getFilters() { 3753 return mFilters; 3754 } 3755 3756 ///////////////////////////////////////////////////////////////////////// 3757 3758 private int getVerticalOffset(boolean forceNormal) { 3759 int voffset = 0; 3760 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 3761 3762 Layout l = mLayout; 3763 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 3764 l = mHintLayout; 3765 } 3766 3767 if (gravity != Gravity.TOP) { 3768 int boxht; 3769 3770 if (l == mHintLayout) { 3771 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 3772 getCompoundPaddingBottom(); 3773 } else { 3774 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 3775 getExtendedPaddingBottom(); 3776 } 3777 int textht = l.getHeight(); 3778 3779 if (textht < boxht) { 3780 if (gravity == Gravity.BOTTOM) 3781 voffset = boxht - textht; 3782 else // (gravity == Gravity.CENTER_VERTICAL) 3783 voffset = (boxht - textht) >> 1; 3784 } 3785 } 3786 return voffset; 3787 } 3788 3789 private int getBottomVerticalOffset(boolean forceNormal) { 3790 int voffset = 0; 3791 final int gravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; 3792 3793 Layout l = mLayout; 3794 if (!forceNormal && mText.length() == 0 && mHintLayout != null) { 3795 l = mHintLayout; 3796 } 3797 3798 if (gravity != Gravity.BOTTOM) { 3799 int boxht; 3800 3801 if (l == mHintLayout) { 3802 boxht = getMeasuredHeight() - getCompoundPaddingTop() - 3803 getCompoundPaddingBottom(); 3804 } else { 3805 boxht = getMeasuredHeight() - getExtendedPaddingTop() - 3806 getExtendedPaddingBottom(); 3807 } 3808 int textht = l.getHeight(); 3809 3810 if (textht < boxht) { 3811 if (gravity == Gravity.TOP) 3812 voffset = boxht - textht; 3813 else // (gravity == Gravity.CENTER_VERTICAL) 3814 voffset = (boxht - textht) >> 1; 3815 } 3816 } 3817 return voffset; 3818 } 3819 3820 private void invalidateCursorPath() { 3821 if (mHighlightPathBogus) { 3822 invalidateCursor(); 3823 } else { 3824 final int horizontalPadding = getCompoundPaddingLeft(); 3825 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 3826 3827 if (mCursorCount == 0) { 3828 synchronized (sTempRect) { 3829 /* 3830 * The reason for this concern about the thickness of the 3831 * cursor and doing the floor/ceil on the coordinates is that 3832 * some EditTexts (notably textfields in the Browser) have 3833 * anti-aliased text where not all the characters are 3834 * necessarily at integer-multiple locations. This should 3835 * make sure the entire cursor gets invalidated instead of 3836 * sometimes missing half a pixel. 3837 */ 3838 float thick = FloatMath.ceil(mTextPaint.getStrokeWidth()); 3839 if (thick < 1.0f) { 3840 thick = 1.0f; 3841 } 3842 3843 thick /= 2.0f; 3844 3845 mHighlightPath.computeBounds(sTempRect, false); 3846 3847 invalidate((int) FloatMath.floor(horizontalPadding + sTempRect.left - thick), 3848 (int) FloatMath.floor(verticalPadding + sTempRect.top - thick), 3849 (int) FloatMath.ceil(horizontalPadding + sTempRect.right + thick), 3850 (int) FloatMath.ceil(verticalPadding + sTempRect.bottom + thick)); 3851 } 3852 } else { 3853 for (int i = 0; i < mCursorCount; i++) { 3854 Rect bounds = mCursorDrawable[i].getBounds(); 3855 invalidate(bounds.left + horizontalPadding, bounds.top + verticalPadding, 3856 bounds.right + horizontalPadding, bounds.bottom + verticalPadding); 3857 } 3858 } 3859 } 3860 } 3861 3862 private void invalidateCursor() { 3863 int where = getSelectionEnd(); 3864 3865 invalidateCursor(where, where, where); 3866 } 3867 3868 private void invalidateCursor(int a, int b, int c) { 3869 if (mLayout == null) { 3870 invalidate(); 3871 } else { 3872 if (a >= 0 || b >= 0 || c >= 0) { 3873 int first = Math.min(Math.min(a, b), c); 3874 int last = Math.max(Math.max(a, b), c); 3875 3876 int line = mLayout.getLineForOffset(first); 3877 int top = mLayout.getLineTop(line); 3878 3879 // This is ridiculous, but the descent from the line above 3880 // can hang down into the line we really want to redraw, 3881 // so we have to invalidate part of the line above to make 3882 // sure everything that needs to be redrawn really is. 3883 // (But not the whole line above, because that would cause 3884 // the same problem with the descenders on the line above it!) 3885 if (line > 0) { 3886 top -= mLayout.getLineDescent(line - 1); 3887 } 3888 3889 int line2; 3890 3891 if (first == last) 3892 line2 = line; 3893 else 3894 line2 = mLayout.getLineForOffset(last); 3895 3896 int bottom = mLayout.getLineTop(line2 + 1); 3897 3898 final int horizontalPadding = getCompoundPaddingLeft(); 3899 final int verticalPadding = getExtendedPaddingTop() + getVerticalOffset(true); 3900 3901 // If used, the cursor drawables can have an arbitrary dimension that can go beyond 3902 // the invalidated lines specified above. 3903 for (int i = 0; i < mCursorCount; i++) { 3904 Rect bounds = mCursorDrawable[i].getBounds(); 3905 top = Math.min(top, bounds.top); 3906 bottom = Math.max(bottom, bounds.bottom); 3907 // Horizontal bounds are already full width, no need to update 3908 } 3909 3910 invalidate(horizontalPadding + mScrollX, top + verticalPadding, 3911 horizontalPadding + mScrollX + getWidth() - 3912 getCompoundPaddingLeft() - getCompoundPaddingRight(), 3913 bottom + verticalPadding); 3914 } 3915 } 3916 } 3917 3918 private void registerForPreDraw() { 3919 final ViewTreeObserver observer = getViewTreeObserver(); 3920 3921 if (mPreDrawState == PREDRAW_NOT_REGISTERED) { 3922 observer.addOnPreDrawListener(this); 3923 mPreDrawState = PREDRAW_PENDING; 3924 } else if (mPreDrawState == PREDRAW_DONE) { 3925 mPreDrawState = PREDRAW_PENDING; 3926 } 3927 3928 // else state is PREDRAW_PENDING, so keep waiting. 3929 } 3930 3931 /** 3932 * {@inheritDoc} 3933 */ 3934 public boolean onPreDraw() { 3935 if (mPreDrawState != PREDRAW_PENDING) { 3936 return true; 3937 } 3938 3939 if (mLayout == null) { 3940 assumeLayout(); 3941 } 3942 3943 boolean changed = false; 3944 3945 if (mMovement != null) { 3946 /* This code also provides auto-scrolling when a cursor is moved using a 3947 * CursorController (insertion point or selection limits). 3948 * For selection, ensure start or end is visible depending on controller's state. 3949 */ 3950 int curs = getSelectionEnd(); 3951 // Do not create the controller if it is not already created. 3952 if (mSelectionModifierCursorController != null && 3953 mSelectionModifierCursorController.isSelectionStartDragged()) { 3954 curs = getSelectionStart(); 3955 } 3956 3957 /* 3958 * TODO: This should really only keep the end in view if 3959 * it already was before the text changed. I'm not sure 3960 * of a good way to tell from here if it was. 3961 */ 3962 if (curs < 0 && 3963 (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 3964 curs = mText.length(); 3965 } 3966 3967 if (curs >= 0) { 3968 changed = bringPointIntoView(curs); 3969 } 3970 } else { 3971 changed = bringTextIntoView(); 3972 } 3973 3974 // This has to be checked here since: 3975 // - onFocusChanged cannot start it when focus is given to a view with selected text (after 3976 // a screen rotation) since layout is not yet initialized at that point. 3977 if (mCreatedWithASelection) { 3978 startSelectionActionMode(); 3979 mCreatedWithASelection = false; 3980 } 3981 3982 // Phone specific code (there is no ExtractEditText on tablets). 3983 // ExtractEditText does not call onFocus when it is displayed, and mHasSelectionOnFocus can 3984 // not be set. Do the test here instead. 3985 if (this instanceof ExtractEditText && hasSelection()) { 3986 startSelectionActionMode(); 3987 } 3988 3989 mPreDrawState = PREDRAW_DONE; 3990 return !changed; 3991 } 3992 3993 @Override 3994 protected void onAttachedToWindow() { 3995 super.onAttachedToWindow(); 3996 3997 mTemporaryDetach = false; 3998 3999 if (mShowErrorAfterAttach) { 4000 showError(); 4001 mShowErrorAfterAttach = false; 4002 } 4003 4004 final ViewTreeObserver observer = getViewTreeObserver(); 4005 // No need to create the controller. 4006 // The get method will add the listener on controller creation. 4007 if (mInsertionPointCursorController != null) { 4008 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 4009 } 4010 if (mSelectionModifierCursorController != null) { 4011 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 4012 } 4013 } 4014 4015 @Override 4016 protected void onDetachedFromWindow() { 4017 super.onDetachedFromWindow(); 4018 4019 final ViewTreeObserver observer = getViewTreeObserver(); 4020 if (mPreDrawState != PREDRAW_NOT_REGISTERED) { 4021 observer.removeOnPreDrawListener(this); 4022 mPreDrawState = PREDRAW_NOT_REGISTERED; 4023 } 4024 4025 if (mError != null) { 4026 hideError(); 4027 } 4028 4029 if (mBlink != null) { 4030 mBlink.removeCallbacks(mBlink); 4031 } 4032 4033 if (mInsertionPointCursorController != null) { 4034 mInsertionPointCursorController.onDetached(); 4035 } 4036 4037 if (mSelectionModifierCursorController != null) { 4038 mSelectionModifierCursorController.onDetached(); 4039 } 4040 4041 hideControllers(); 4042 } 4043 4044 @Override 4045 protected boolean isPaddingOffsetRequired() { 4046 return mShadowRadius != 0 || mDrawables != null; 4047 } 4048 4049 @Override 4050 protected int getLeftPaddingOffset() { 4051 return getCompoundPaddingLeft() - mPaddingLeft + 4052 (int) Math.min(0, mShadowDx - mShadowRadius); 4053 } 4054 4055 @Override 4056 protected int getTopPaddingOffset() { 4057 return (int) Math.min(0, mShadowDy - mShadowRadius); 4058 } 4059 4060 @Override 4061 protected int getBottomPaddingOffset() { 4062 return (int) Math.max(0, mShadowDy + mShadowRadius); 4063 } 4064 4065 @Override 4066 protected int getRightPaddingOffset() { 4067 return -(getCompoundPaddingRight() - mPaddingRight) + 4068 (int) Math.max(0, mShadowDx + mShadowRadius); 4069 } 4070 4071 @Override 4072 protected boolean verifyDrawable(Drawable who) { 4073 final boolean verified = super.verifyDrawable(who); 4074 if (!verified && mDrawables != null) { 4075 return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || 4076 who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom; 4077 } 4078 return verified; 4079 } 4080 4081 @Override 4082 public void jumpDrawablesToCurrentState() { 4083 super.jumpDrawablesToCurrentState(); 4084 if (mDrawables != null) { 4085 if (mDrawables.mDrawableLeft != null) { 4086 mDrawables.mDrawableLeft.jumpToCurrentState(); 4087 } 4088 if (mDrawables.mDrawableTop != null) { 4089 mDrawables.mDrawableTop.jumpToCurrentState(); 4090 } 4091 if (mDrawables.mDrawableRight != null) { 4092 mDrawables.mDrawableRight.jumpToCurrentState(); 4093 } 4094 if (mDrawables.mDrawableBottom != null) { 4095 mDrawables.mDrawableBottom.jumpToCurrentState(); 4096 } 4097 } 4098 } 4099 4100 @Override 4101 public void invalidateDrawable(Drawable drawable) { 4102 if (verifyDrawable(drawable)) { 4103 final Rect dirty = drawable.getBounds(); 4104 int scrollX = mScrollX; 4105 int scrollY = mScrollY; 4106 4107 // IMPORTANT: The coordinates below are based on the coordinates computed 4108 // for each compound drawable in onDraw(). Make sure to update each section 4109 // accordingly. 4110 final TextView.Drawables drawables = mDrawables; 4111 if (drawables != null) { 4112 if (drawable == drawables.mDrawableLeft) { 4113 final int compoundPaddingTop = getCompoundPaddingTop(); 4114 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4115 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4116 4117 scrollX += mPaddingLeft; 4118 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightLeft) / 2; 4119 } else if (drawable == drawables.mDrawableRight) { 4120 final int compoundPaddingTop = getCompoundPaddingTop(); 4121 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4122 final int vspace = mBottom - mTop - compoundPaddingBottom - compoundPaddingTop; 4123 4124 scrollX += (mRight - mLeft - mPaddingRight - drawables.mDrawableSizeRight); 4125 scrollY += compoundPaddingTop + (vspace - drawables.mDrawableHeightRight) / 2; 4126 } else if (drawable == drawables.mDrawableTop) { 4127 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4128 final int compoundPaddingRight = getCompoundPaddingRight(); 4129 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4130 4131 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthTop) / 2; 4132 scrollY += mPaddingTop; 4133 } else if (drawable == drawables.mDrawableBottom) { 4134 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4135 final int compoundPaddingRight = getCompoundPaddingRight(); 4136 final int hspace = mRight - mLeft - compoundPaddingRight - compoundPaddingLeft; 4137 4138 scrollX += compoundPaddingLeft + (hspace - drawables.mDrawableWidthBottom) / 2; 4139 scrollY += (mBottom - mTop - mPaddingBottom - drawables.mDrawableSizeBottom); 4140 } 4141 } 4142 4143 invalidate(dirty.left + scrollX, dirty.top + scrollY, 4144 dirty.right + scrollX, dirty.bottom + scrollY); 4145 } 4146 } 4147 4148 /** 4149 * @hide 4150 */ 4151 @Override 4152 public int getResolvedLayoutDirection(Drawable who) { 4153 if (who == null) return View.LAYOUT_DIRECTION_LTR; 4154 if (mDrawables != null) { 4155 final Drawables drawables = mDrawables; 4156 if (who == drawables.mDrawableLeft || who == drawables.mDrawableRight || 4157 who == drawables.mDrawableTop || who == drawables.mDrawableBottom) { 4158 return getResolvedLayoutDirection(); 4159 } 4160 } 4161 return super.getResolvedLayoutDirection(who); 4162 } 4163 4164 @Override 4165 protected boolean onSetAlpha(int alpha) { 4166 // Alpha is supported if and only if the drawing can be done in one pass. 4167 // TODO text with spans with a background color currently do not respect this alpha. 4168 if (getBackground() == null) { 4169 mCurrentAlpha = alpha; 4170 final Drawables dr = mDrawables; 4171 if (dr != null) { 4172 if (dr.mDrawableLeft != null) dr.mDrawableLeft.mutate().setAlpha(alpha); 4173 if (dr.mDrawableTop != null) dr.mDrawableTop.mutate().setAlpha(alpha); 4174 if (dr.mDrawableRight != null) dr.mDrawableRight.mutate().setAlpha(alpha); 4175 if (dr.mDrawableBottom != null) dr.mDrawableBottom.mutate().setAlpha(alpha); 4176 } 4177 return true; 4178 } 4179 4180 mCurrentAlpha = 255; 4181 return false; 4182 } 4183 4184 /** 4185 * When a TextView is used to display a useful piece of information to the user (such as a 4186 * contact's address), it should be made selectable, so that the user can select and copy this 4187 * content. 4188 * 4189 * Use {@link #setTextIsSelectable(boolean)} or the 4190 * {@link android.R.styleable#TextView_textIsSelectable} XML attribute to make this TextView 4191 * selectable (text is not selectable by default). 4192 * 4193 * Note that the content of an EditText is always selectable. 4194 * 4195 * @return True if the text displayed in this TextView can be selected by the user. 4196 * 4197 * @attr ref android.R.styleable#TextView_textIsSelectable 4198 */ 4199 public boolean isTextSelectable() { 4200 return mTextIsSelectable; 4201 } 4202 4203 /** 4204 * Sets whether or not (default) the content of this view is selectable by the user. 4205 * 4206 * Note that this methods affect the {@link #setFocusable(boolean)}, 4207 * {@link #setFocusableInTouchMode(boolean)} {@link #setClickable(boolean)} and 4208 * {@link #setLongClickable(boolean)} states and you may want to restore these if they were 4209 * customized. 4210 * 4211 * See {@link #isTextSelectable} for details. 4212 * 4213 * @param selectable Whether or not the content of this TextView should be selectable. 4214 */ 4215 public void setTextIsSelectable(boolean selectable) { 4216 if (mTextIsSelectable == selectable) return; 4217 4218 mTextIsSelectable = selectable; 4219 4220 setFocusableInTouchMode(selectable); 4221 setFocusable(selectable); 4222 setClickable(selectable); 4223 setLongClickable(selectable); 4224 4225 // mInputType is already EditorInfo.TYPE_NULL and mInput is null; 4226 4227 setMovementMethod(selectable ? ArrowKeyMovementMethod.getInstance() : null); 4228 setText(getText(), selectable ? BufferType.SPANNABLE : BufferType.NORMAL); 4229 4230 // Called by setText above, but safer in case of future code changes 4231 prepareCursorControllers(); 4232 } 4233 4234 @Override 4235 protected int[] onCreateDrawableState(int extraSpace) { 4236 final int[] drawableState; 4237 4238 if (mSingleLine) { 4239 drawableState = super.onCreateDrawableState(extraSpace); 4240 } else { 4241 drawableState = super.onCreateDrawableState(extraSpace + 1); 4242 mergeDrawableStates(drawableState, MULTILINE_STATE_SET); 4243 } 4244 4245 if (mTextIsSelectable) { 4246 // Disable pressed state, which was introduced when TextView was made clickable. 4247 // Prevents text color change. 4248 // setClickable(false) would have a similar effect, but it also disables focus changes 4249 // and long press actions, which are both needed by text selection. 4250 final int length = drawableState.length; 4251 for (int i = 0; i < length; i++) { 4252 if (drawableState[i] == R.attr.state_pressed) { 4253 final int[] nonPressedState = new int[length - 1]; 4254 System.arraycopy(drawableState, 0, nonPressedState, 0, i); 4255 System.arraycopy(drawableState, i + 1, nonPressedState, i, length - i - 1); 4256 return nonPressedState; 4257 } 4258 } 4259 } 4260 4261 return drawableState; 4262 } 4263 4264 @Override 4265 protected void onDraw(Canvas canvas) { 4266 if (mPreDrawState == PREDRAW_DONE) { 4267 final ViewTreeObserver observer = getViewTreeObserver(); 4268 observer.removeOnPreDrawListener(this); 4269 mPreDrawState = PREDRAW_NOT_REGISTERED; 4270 } 4271 4272 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return; 4273 4274 restartMarqueeIfNeeded(); 4275 4276 // Draw the background for this view 4277 super.onDraw(canvas); 4278 4279 final int compoundPaddingLeft = getCompoundPaddingLeft(); 4280 final int compoundPaddingTop = getCompoundPaddingTop(); 4281 final int compoundPaddingRight = getCompoundPaddingRight(); 4282 final int compoundPaddingBottom = getCompoundPaddingBottom(); 4283 final int scrollX = mScrollX; 4284 final int scrollY = mScrollY; 4285 final int right = mRight; 4286 final int left = mLeft; 4287 final int bottom = mBottom; 4288 final int top = mTop; 4289 4290 final Drawables dr = mDrawables; 4291 if (dr != null) { 4292 /* 4293 * Compound, not extended, because the icon is not clipped 4294 * if the text height is smaller. 4295 */ 4296 4297 int vspace = bottom - top - compoundPaddingBottom - compoundPaddingTop; 4298 int hspace = right - left - compoundPaddingRight - compoundPaddingLeft; 4299 4300 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4301 // Make sure to update invalidateDrawable() when changing this code. 4302 if (dr.mDrawableLeft != null) { 4303 canvas.save(); 4304 canvas.translate(scrollX + mPaddingLeft, 4305 scrollY + compoundPaddingTop + 4306 (vspace - dr.mDrawableHeightLeft) / 2); 4307 dr.mDrawableLeft.draw(canvas); 4308 canvas.restore(); 4309 } 4310 4311 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4312 // Make sure to update invalidateDrawable() when changing this code. 4313 if (dr.mDrawableRight != null) { 4314 canvas.save(); 4315 canvas.translate(scrollX + right - left - mPaddingRight - dr.mDrawableSizeRight, 4316 scrollY + compoundPaddingTop + (vspace - dr.mDrawableHeightRight) / 2); 4317 dr.mDrawableRight.draw(canvas); 4318 canvas.restore(); 4319 } 4320 4321 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4322 // Make sure to update invalidateDrawable() when changing this code. 4323 if (dr.mDrawableTop != null) { 4324 canvas.save(); 4325 canvas.translate(scrollX + compoundPaddingLeft + (hspace - dr.mDrawableWidthTop) / 2, 4326 scrollY + mPaddingTop); 4327 dr.mDrawableTop.draw(canvas); 4328 canvas.restore(); 4329 } 4330 4331 // IMPORTANT: The coordinates computed are also used in invalidateDrawable() 4332 // Make sure to update invalidateDrawable() when changing this code. 4333 if (dr.mDrawableBottom != null) { 4334 canvas.save(); 4335 canvas.translate(scrollX + compoundPaddingLeft + 4336 (hspace - dr.mDrawableWidthBottom) / 2, 4337 scrollY + bottom - top - mPaddingBottom - dr.mDrawableSizeBottom); 4338 dr.mDrawableBottom.draw(canvas); 4339 canvas.restore(); 4340 } 4341 } 4342 4343 int color = mCurTextColor; 4344 4345 if (mLayout == null) { 4346 assumeLayout(); 4347 } 4348 4349 Layout layout = mLayout; 4350 int cursorcolor = color; 4351 4352 if (mHint != null && mText.length() == 0) { 4353 if (mHintTextColor != null) { 4354 color = mCurHintTextColor; 4355 } 4356 4357 layout = mHintLayout; 4358 } 4359 4360 mTextPaint.setColor(color); 4361 if (mCurrentAlpha != 255) { 4362 // If set, the alpha will override the color's alpha. Multiply the alphas. 4363 mTextPaint.setAlpha((mCurrentAlpha * Color.alpha(color)) / 255); 4364 } 4365 mTextPaint.drawableState = getDrawableState(); 4366 4367 canvas.save(); 4368 /* Would be faster if we didn't have to do this. Can we chop the 4369 (displayable) text so that we don't need to do this ever? 4370 */ 4371 4372 int extendedPaddingTop = getExtendedPaddingTop(); 4373 int extendedPaddingBottom = getExtendedPaddingBottom(); 4374 4375 float clipLeft = compoundPaddingLeft + scrollX; 4376 float clipTop = extendedPaddingTop + scrollY; 4377 float clipRight = right - left - compoundPaddingRight + scrollX; 4378 float clipBottom = bottom - top - extendedPaddingBottom + scrollY; 4379 4380 if (mShadowRadius != 0) { 4381 clipLeft += Math.min(0, mShadowDx - mShadowRadius); 4382 clipRight += Math.max(0, mShadowDx + mShadowRadius); 4383 4384 clipTop += Math.min(0, mShadowDy - mShadowRadius); 4385 clipBottom += Math.max(0, mShadowDy + mShadowRadius); 4386 } 4387 4388 canvas.clipRect(clipLeft, clipTop, clipRight, clipBottom); 4389 4390 int voffsetText = 0; 4391 int voffsetCursor = 0; 4392 4393 // translate in by our padding 4394 { 4395 /* shortcircuit calling getVerticaOffset() */ 4396 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4397 voffsetText = getVerticalOffset(false); 4398 voffsetCursor = getVerticalOffset(true); 4399 } 4400 canvas.translate(compoundPaddingLeft, extendedPaddingTop + voffsetText); 4401 } 4402 4403 final int layoutDirection = getResolvedLayoutDirection(); 4404 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 4405 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 4406 if (!mSingleLine && getLineCount() == 1 && canMarquee() && 4407 (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) != Gravity.LEFT) { 4408 canvas.translate(mLayout.getLineRight(0) - (mRight - mLeft - 4409 getCompoundPaddingLeft() - getCompoundPaddingRight()), 0.0f); 4410 } 4411 4412 if (mMarquee != null && mMarquee.isRunning()) { 4413 canvas.translate(-mMarquee.mScroll, 0.0f); 4414 } 4415 } 4416 4417 Path highlight = null; 4418 int selStart = -1, selEnd = -1; 4419 boolean drawCursor = false; 4420 4421 // If there is no movement method, then there can be no selection. 4422 // Check that first and attempt to skip everything having to do with 4423 // the cursor. 4424 // XXX This is not strictly true -- a program could set the 4425 // selection manually if it really wanted to. 4426 if (mMovement != null && (isFocused() || isPressed())) { 4427 selStart = getSelectionStart(); 4428 selEnd = getSelectionEnd(); 4429 4430 if ((isCursorVisible() || mTextIsSelectable) && selStart >= 0 && isEnabled()) { 4431 if (mHighlightPath == null) 4432 mHighlightPath = new Path(); 4433 4434 if (selStart == selEnd) { 4435 if (!mTextIsSelectable && 4436 (SystemClock.uptimeMillis() - mShowCursor) % (2 * BLINK) < BLINK) { 4437 if (mHighlightPathBogus) { 4438 mHighlightPath.reset(); 4439 mLayout.getCursorPath(selStart, mHighlightPath, mText); 4440 updateCursorsPositions(); 4441 mHighlightPathBogus = false; 4442 } 4443 4444 // XXX should pass to skin instead of drawing directly 4445 mHighlightPaint.setColor(cursorcolor); 4446 if (mCurrentAlpha != 255) { 4447 mHighlightPaint.setAlpha( 4448 (mCurrentAlpha * Color.alpha(cursorcolor)) / 255); 4449 } 4450 mHighlightPaint.setStyle(Paint.Style.STROKE); 4451 highlight = mHighlightPath; 4452 drawCursor = mCursorCount > 0; 4453 } 4454 } else { 4455 if (mHighlightPathBogus) { 4456 mHighlightPath.reset(); 4457 mLayout.getSelectionPath(selStart, selEnd, mHighlightPath); 4458 mHighlightPathBogus = false; 4459 } 4460 4461 // XXX should pass to skin instead of drawing directly 4462 mHighlightPaint.setColor(mHighlightColor); 4463 if (mCurrentAlpha != 255) { 4464 mHighlightPaint.setAlpha( 4465 (mCurrentAlpha * Color.alpha(mHighlightColor)) / 255); 4466 } 4467 mHighlightPaint.setStyle(Paint.Style.FILL); 4468 4469 highlight = mHighlightPath; 4470 } 4471 } 4472 } 4473 4474 /* Comment out until we decide what to do about animations 4475 boolean isLinearTextOn = false; 4476 if (currentTransformation != null) { 4477 isLinearTextOn = mTextPaint.isLinearTextOn(); 4478 Matrix m = currentTransformation.getMatrix(); 4479 if (!m.isIdentity()) { 4480 // mTextPaint.setLinearTextOn(true); 4481 } 4482 } 4483 */ 4484 4485 final InputMethodState ims = mInputMethodState; 4486 final int cursorOffsetVertical = voffsetCursor - voffsetText; 4487 if (ims != null && ims.mBatchEditNesting == 0) { 4488 InputMethodManager imm = InputMethodManager.peekInstance(); 4489 if (imm != null) { 4490 if (imm.isActive(this)) { 4491 boolean reported = false; 4492 if (ims.mContentChanged || ims.mSelectionModeChanged) { 4493 // We are in extract mode and the content has changed 4494 // in some way... just report complete new text to the 4495 // input method. 4496 reported = reportExtractedText(); 4497 } 4498 if (!reported && highlight != null) { 4499 int candStart = -1; 4500 int candEnd = -1; 4501 if (mText instanceof Spannable) { 4502 Spannable sp = (Spannable)mText; 4503 candStart = EditableInputConnection.getComposingSpanStart(sp); 4504 candEnd = EditableInputConnection.getComposingSpanEnd(sp); 4505 } 4506 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 4507 } 4508 } 4509 4510 if (imm.isWatchingCursor(this) && highlight != null) { 4511 highlight.computeBounds(ims.mTmpRectF, true); 4512 ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; 4513 4514 canvas.getMatrix().mapPoints(ims.mTmpOffset); 4515 ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); 4516 4517 ims.mTmpRectF.offset(0, cursorOffsetVertical); 4518 4519 ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), 4520 (int)(ims.mTmpRectF.top + 0.5), 4521 (int)(ims.mTmpRectF.right + 0.5), 4522 (int)(ims.mTmpRectF.bottom + 0.5)); 4523 4524 imm.updateCursor(this, 4525 ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, 4526 ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); 4527 } 4528 } 4529 } 4530 4531 if (mCorrectionHighlighter != null) { 4532 mCorrectionHighlighter.draw(canvas, cursorOffsetVertical); 4533 } 4534 4535 if (drawCursor) { 4536 drawCursor(canvas, cursorOffsetVertical); 4537 // Rely on the drawable entirely, do not draw the cursor line. 4538 // Has to be done after the IMM related code above which relies on the highlight. 4539 highlight = null; 4540 } 4541 4542 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 4543 4544 if (mMarquee != null && mMarquee.shouldDrawGhost()) { 4545 canvas.translate((int) mMarquee.getGhostOffset(), 0.0f); 4546 layout.draw(canvas, highlight, mHighlightPaint, cursorOffsetVertical); 4547 } 4548 4549 /* Comment out until we decide what to do about animations 4550 if (currentTransformation != null) { 4551 mTextPaint.setLinearTextOn(isLinearTextOn); 4552 } 4553 */ 4554 4555 canvas.restore(); 4556 } 4557 4558 private void updateCursorsPositions() { 4559 if (mCursorDrawableRes == 0) { 4560 mCursorCount = 0; 4561 return; 4562 } 4563 4564 final int offset = getSelectionStart(); 4565 final int line = mLayout.getLineForOffset(offset); 4566 final int top = mLayout.getLineTop(line); 4567 final int bottom = mLayout.getLineTop(line + 1); 4568 4569 mCursorCount = mLayout.isLevelBoundary(offset) ? 2 : 1; 4570 4571 int middle = bottom; 4572 if (mCursorCount == 2) { 4573 // Similar to what is done in {@link Layout.#getCursorPath(int, Path, CharSequence)} 4574 middle = (top + bottom) >> 1; 4575 } 4576 4577 updateCursorPosition(0, top, middle, mLayout.getPrimaryHorizontal(offset)); 4578 4579 if (mCursorCount == 2) { 4580 updateCursorPosition(1, middle, bottom, mLayout.getSecondaryHorizontal(offset)); 4581 } 4582 } 4583 4584 private void updateCursorPosition(int cursorIndex, int top, int bottom, float horizontal) { 4585 if (mCursorDrawable[cursorIndex] == null) 4586 mCursorDrawable[cursorIndex] = mContext.getResources().getDrawable(mCursorDrawableRes); 4587 4588 if (mTempRect == null) mTempRect = new Rect(); 4589 4590 mCursorDrawable[cursorIndex].getPadding(mTempRect); 4591 final int width = mCursorDrawable[cursorIndex].getIntrinsicWidth(); 4592 horizontal = Math.max(0.5f, horizontal - 0.5f); 4593 final int left = (int) (horizontal) - mTempRect.left; 4594 mCursorDrawable[cursorIndex].setBounds(left, top - mTempRect.top, left + width, 4595 bottom + mTempRect.bottom); 4596 } 4597 4598 private void drawCursor(Canvas canvas, int cursorOffsetVertical) { 4599 final boolean translate = cursorOffsetVertical != 0; 4600 if (translate) canvas.translate(0, cursorOffsetVertical); 4601 for (int i = 0; i < mCursorCount; i++) { 4602 mCursorDrawable[i].draw(canvas); 4603 } 4604 if (translate) canvas.translate(0, -cursorOffsetVertical); 4605 } 4606 4607 @Override 4608 public void getFocusedRect(Rect r) { 4609 if (mLayout == null) { 4610 super.getFocusedRect(r); 4611 return; 4612 } 4613 4614 int sel = getSelectionEnd(); 4615 if (sel < 0) { 4616 super.getFocusedRect(r); 4617 return; 4618 } 4619 4620 int line = mLayout.getLineForOffset(sel); 4621 r.top = mLayout.getLineTop(line); 4622 r.bottom = mLayout.getLineBottom(line); 4623 4624 r.left = (int) mLayout.getPrimaryHorizontal(sel); 4625 r.right = r.left + 1; 4626 4627 // Adjust for padding and gravity. 4628 int paddingLeft = getCompoundPaddingLeft(); 4629 int paddingTop = getExtendedPaddingTop(); 4630 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4631 paddingTop += getVerticalOffset(false); 4632 } 4633 r.offset(paddingLeft, paddingTop); 4634 } 4635 4636 /** 4637 * Return the number of lines of text, or 0 if the internal Layout has not 4638 * been built. 4639 */ 4640 public int getLineCount() { 4641 return mLayout != null ? mLayout.getLineCount() : 0; 4642 } 4643 4644 /** 4645 * Return the baseline for the specified line (0...getLineCount() - 1) 4646 * If bounds is not null, return the top, left, right, bottom extents 4647 * of the specified line in it. If the internal Layout has not been built, 4648 * return 0 and set bounds to (0, 0, 0, 0) 4649 * @param line which line to examine (0..getLineCount() - 1) 4650 * @param bounds Optional. If not null, it returns the extent of the line 4651 * @return the Y-coordinate of the baseline 4652 */ 4653 public int getLineBounds(int line, Rect bounds) { 4654 if (mLayout == null) { 4655 if (bounds != null) { 4656 bounds.set(0, 0, 0, 0); 4657 } 4658 return 0; 4659 } 4660 else { 4661 int baseline = mLayout.getLineBounds(line, bounds); 4662 4663 int voffset = getExtendedPaddingTop(); 4664 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4665 voffset += getVerticalOffset(true); 4666 } 4667 if (bounds != null) { 4668 bounds.offset(getCompoundPaddingLeft(), voffset); 4669 } 4670 return baseline + voffset; 4671 } 4672 } 4673 4674 @Override 4675 public int getBaseline() { 4676 if (mLayout == null) { 4677 return super.getBaseline(); 4678 } 4679 4680 int voffset = 0; 4681 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 4682 voffset = getVerticalOffset(true); 4683 } 4684 4685 return getExtendedPaddingTop() + voffset + mLayout.getLineBaseline(0); 4686 } 4687 4688 @Override 4689 public boolean onKeyDown(int keyCode, KeyEvent event) { 4690 int which = doKeyDown(keyCode, event, null); 4691 if (which == 0) { 4692 // Go through default dispatching. 4693 return super.onKeyDown(keyCode, event); 4694 } 4695 4696 return true; 4697 } 4698 4699 @Override 4700 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4701 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 4702 4703 int which = doKeyDown(keyCode, down, event); 4704 if (which == 0) { 4705 // Go through default dispatching. 4706 return super.onKeyMultiple(keyCode, repeatCount, event); 4707 } 4708 if (which == -1) { 4709 // Consumed the whole thing. 4710 return true; 4711 } 4712 4713 repeatCount--; 4714 4715 // We are going to dispatch the remaining events to either the input 4716 // or movement method. To do this, we will just send a repeated stream 4717 // of down and up events until we have done the complete repeatCount. 4718 // It would be nice if those interfaces had an onKeyMultiple() method, 4719 // but adding that is a more complicated change. 4720 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 4721 if (which == 1) { 4722 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4723 while (--repeatCount > 0) { 4724 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 4725 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 4726 } 4727 hideErrorIfUnchanged(); 4728 4729 } else if (which == 2) { 4730 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4731 while (--repeatCount > 0) { 4732 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 4733 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 4734 } 4735 } 4736 4737 return true; 4738 } 4739 4740 /** 4741 * Returns true if pressing ENTER in this field advances focus instead 4742 * of inserting the character. This is true mostly in single-line fields, 4743 * but also in mail addresses and subjects which will display on multiple 4744 * lines but where it doesn't make sense to insert newlines. 4745 */ 4746 private boolean shouldAdvanceFocusOnEnter() { 4747 if (mInput == null) { 4748 return false; 4749 } 4750 4751 if (mSingleLine) { 4752 return true; 4753 } 4754 4755 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 4756 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 4757 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS 4758 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 4759 return true; 4760 } 4761 } 4762 4763 return false; 4764 } 4765 4766 /** 4767 * Returns true if pressing TAB in this field advances focus instead 4768 * of inserting the character. Insert tabs only in multi-line editors. 4769 */ 4770 private boolean shouldAdvanceFocusOnTab() { 4771 if (mInput != null && !mSingleLine) { 4772 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 4773 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 4774 if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE 4775 || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { 4776 return false; 4777 } 4778 } 4779 } 4780 return true; 4781 } 4782 4783 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 4784 if (!isEnabled()) { 4785 return 0; 4786 } 4787 4788 switch (keyCode) { 4789 case KeyEvent.KEYCODE_ENTER: 4790 mEnterKeyIsDown = true; 4791 if (event.hasNoModifiers()) { 4792 // When mInputContentType is set, we know that we are 4793 // running in a "modern" cupcake environment, so don't need 4794 // to worry about the application trying to capture 4795 // enter key events. 4796 if (mInputContentType != null) { 4797 // If there is an action listener, given them a 4798 // chance to consume the event. 4799 if (mInputContentType.onEditorActionListener != null && 4800 mInputContentType.onEditorActionListener.onEditorAction( 4801 this, EditorInfo.IME_NULL, event)) { 4802 mInputContentType.enterDown = true; 4803 // We are consuming the enter key for them. 4804 return -1; 4805 } 4806 } 4807 4808 // If our editor should move focus when enter is pressed, or 4809 // this is a generated event from an IME action button, then 4810 // don't let it be inserted into the text. 4811 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 4812 || shouldAdvanceFocusOnEnter()) { 4813 if (mOnClickListener != null) { 4814 return 0; 4815 } 4816 return -1; 4817 } 4818 } 4819 break; 4820 4821 case KeyEvent.KEYCODE_DPAD_CENTER: 4822 mDPadCenterIsDown = true; 4823 if (event.hasNoModifiers()) { 4824 if (shouldAdvanceFocusOnEnter()) { 4825 return 0; 4826 } 4827 } 4828 break; 4829 4830 case KeyEvent.KEYCODE_TAB: 4831 if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 4832 if (shouldAdvanceFocusOnTab()) { 4833 return 0; 4834 } 4835 } 4836 break; 4837 4838 // Has to be done on key down (and not on key up) to correctly be intercepted. 4839 case KeyEvent.KEYCODE_BACK: 4840 if (mSelectionActionMode != null) { 4841 stopSelectionActionMode(); 4842 return -1; 4843 } 4844 break; 4845 } 4846 4847 if (mInput != null) { 4848 resetErrorChangedFlag(); 4849 4850 boolean doDown = true; 4851 if (otherEvent != null) { 4852 try { 4853 beginBatchEdit(); 4854 final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent); 4855 hideErrorIfUnchanged(); 4856 doDown = false; 4857 if (handled) { 4858 return -1; 4859 } 4860 } catch (AbstractMethodError e) { 4861 // onKeyOther was added after 1.0, so if it isn't 4862 // implemented we need to try to dispatch as a regular down. 4863 } finally { 4864 endBatchEdit(); 4865 } 4866 } 4867 4868 if (doDown) { 4869 beginBatchEdit(); 4870 final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event); 4871 endBatchEdit(); 4872 hideErrorIfUnchanged(); 4873 if (handled) return 1; 4874 } 4875 } 4876 4877 // bug 650865: sometimes we get a key event before a layout. 4878 // don't try to move around if we don't know the layout. 4879 4880 if (mMovement != null && mLayout != null) { 4881 boolean doDown = true; 4882 if (otherEvent != null) { 4883 try { 4884 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 4885 otherEvent); 4886 doDown = false; 4887 if (handled) { 4888 return -1; 4889 } 4890 } catch (AbstractMethodError e) { 4891 // onKeyOther was added after 1.0, so if it isn't 4892 // implemented we need to try to dispatch as a regular down. 4893 } 4894 } 4895 if (doDown) { 4896 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 4897 return 2; 4898 } 4899 } 4900 4901 return 0; 4902 } 4903 4904 /** 4905 * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} 4906 * can be recorded. 4907 * @hide 4908 */ 4909 public void resetErrorChangedFlag() { 4910 /* 4911 * Keep track of what the error was before doing the input 4912 * so that if an input filter changed the error, we leave 4913 * that error showing. Otherwise, we take down whatever 4914 * error was showing when the user types something. 4915 */ 4916 mErrorWasChanged = false; 4917 } 4918 4919 /** 4920 * @hide 4921 */ 4922 public void hideErrorIfUnchanged() { 4923 if (mError != null && !mErrorWasChanged) { 4924 setError(null, null); 4925 } 4926 } 4927 4928 @Override 4929 public boolean onKeyUp(int keyCode, KeyEvent event) { 4930 if (!isEnabled()) { 4931 return super.onKeyUp(keyCode, event); 4932 } 4933 4934 switch (keyCode) { 4935 case KeyEvent.KEYCODE_DPAD_CENTER: 4936 mDPadCenterIsDown = false; 4937 if (event.hasNoModifiers()) { 4938 /* 4939 * If there is a click listener, just call through to 4940 * super, which will invoke it. 4941 * 4942 * If there isn't a click listener, try to show the soft 4943 * input method. (It will also 4944 * call performClick(), but that won't do anything in 4945 * this case.) 4946 */ 4947 if (mOnClickListener == null) { 4948 if (mMovement != null && mText instanceof Editable 4949 && mLayout != null && onCheckIsTextEditor()) { 4950 InputMethodManager imm = InputMethodManager.peekInstance(); 4951 if (imm != null) { 4952 imm.viewClicked(this); 4953 imm.showSoftInput(this, 0); 4954 } 4955 } 4956 } 4957 } 4958 return super.onKeyUp(keyCode, event); 4959 4960 case KeyEvent.KEYCODE_ENTER: 4961 mEnterKeyIsDown = false; 4962 if (event.hasNoModifiers()) { 4963 if (mInputContentType != null 4964 && mInputContentType.onEditorActionListener != null 4965 && mInputContentType.enterDown) { 4966 mInputContentType.enterDown = false; 4967 if (mInputContentType.onEditorActionListener.onEditorAction( 4968 this, EditorInfo.IME_NULL, event)) { 4969 return true; 4970 } 4971 } 4972 4973 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 4974 || shouldAdvanceFocusOnEnter()) { 4975 /* 4976 * If there is a click listener, just call through to 4977 * super, which will invoke it. 4978 * 4979 * If there isn't a click listener, try to advance focus, 4980 * but still call through to super, which will reset the 4981 * pressed state and longpress state. (It will also 4982 * call performClick(), but that won't do anything in 4983 * this case.) 4984 */ 4985 if (mOnClickListener == null) { 4986 View v = focusSearch(FOCUS_DOWN); 4987 4988 if (v != null) { 4989 if (!v.requestFocus(FOCUS_DOWN)) { 4990 throw new IllegalStateException( 4991 "focus search returned a view " + 4992 "that wasn't able to take focus!"); 4993 } 4994 4995 /* 4996 * Return true because we handled the key; super 4997 * will return false because there was no click 4998 * listener. 4999 */ 5000 super.onKeyUp(keyCode, event); 5001 return true; 5002 } else if ((event.getFlags() 5003 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 5004 // No target for next focus, but make sure the IME 5005 // if this came from it. 5006 InputMethodManager imm = InputMethodManager.peekInstance(); 5007 if (imm != null && imm.isActive(this)) { 5008 imm.hideSoftInputFromWindow(getWindowToken(), 0); 5009 } 5010 } 5011 } 5012 } 5013 return super.onKeyUp(keyCode, event); 5014 } 5015 break; 5016 } 5017 5018 if (mInput != null) 5019 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 5020 return true; 5021 5022 if (mMovement != null && mLayout != null) 5023 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 5024 return true; 5025 5026 return super.onKeyUp(keyCode, event); 5027 } 5028 5029 @Override public boolean onCheckIsTextEditor() { 5030 return mInputType != EditorInfo.TYPE_NULL; 5031 } 5032 5033 @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5034 if (onCheckIsTextEditor() && isEnabled()) { 5035 if (mInputMethodState == null) { 5036 mInputMethodState = new InputMethodState(); 5037 } 5038 outAttrs.inputType = mInputType; 5039 if (mInputContentType != null) { 5040 outAttrs.imeOptions = mInputContentType.imeOptions; 5041 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 5042 outAttrs.actionLabel = mInputContentType.imeActionLabel; 5043 outAttrs.actionId = mInputContentType.imeActionId; 5044 outAttrs.extras = mInputContentType.extras; 5045 } else { 5046 outAttrs.imeOptions = EditorInfo.IME_NULL; 5047 } 5048 if (focusSearch(FOCUS_DOWN) != null) { 5049 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 5050 } 5051 if (focusSearch(FOCUS_UP) != null) { 5052 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 5053 } 5054 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 5055 == EditorInfo.IME_ACTION_UNSPECIFIED) { 5056 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 5057 // An action has not been set, but the enter key will move to 5058 // the next focus, so set the action to that. 5059 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 5060 } else { 5061 // An action has not been set, and there is no focus to move 5062 // to, so let's just supply a "done" action. 5063 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 5064 } 5065 if (!shouldAdvanceFocusOnEnter()) { 5066 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5067 } 5068 } 5069 if (isMultilineInputType(outAttrs.inputType)) { 5070 // Multi-line text editors should always show an enter key. 5071 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5072 } 5073 outAttrs.hintText = mHint; 5074 if (mText instanceof Editable) { 5075 InputConnection ic = new EditableInputConnection(this); 5076 outAttrs.initialSelStart = getSelectionStart(); 5077 outAttrs.initialSelEnd = getSelectionEnd(); 5078 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 5079 return ic; 5080 } 5081 } 5082 return null; 5083 } 5084 5085 /** 5086 * If this TextView contains editable content, extract a portion of it 5087 * based on the information in <var>request</var> in to <var>outText</var>. 5088 * @return Returns true if the text was successfully extracted, else false. 5089 */ 5090 public boolean extractText(ExtractedTextRequest request, 5091 ExtractedText outText) { 5092 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 5093 EXTRACT_UNKNOWN, outText); 5094 } 5095 5096 static final int EXTRACT_NOTHING = -2; 5097 static final int EXTRACT_UNKNOWN = -1; 5098 5099 boolean extractTextInternal(ExtractedTextRequest request, 5100 int partialStartOffset, int partialEndOffset, int delta, 5101 ExtractedText outText) { 5102 final CharSequence content = mText; 5103 if (content != null) { 5104 if (partialStartOffset != EXTRACT_NOTHING) { 5105 final int N = content.length(); 5106 if (partialStartOffset < 0) { 5107 outText.partialStartOffset = outText.partialEndOffset = -1; 5108 partialStartOffset = 0; 5109 partialEndOffset = N; 5110 } else { 5111 // Now use the delta to determine the actual amount of text 5112 // we need. 5113 partialEndOffset += delta; 5114 // Adjust offsets to ensure we contain full spans. 5115 if (content instanceof Spanned) { 5116 Spanned spanned = (Spanned)content; 5117 Object[] spans = spanned.getSpans(partialStartOffset, 5118 partialEndOffset, ParcelableSpan.class); 5119 int i = spans.length; 5120 while (i > 0) { 5121 i--; 5122 int j = spanned.getSpanStart(spans[i]); 5123 if (j < partialStartOffset) partialStartOffset = j; 5124 j = spanned.getSpanEnd(spans[i]); 5125 if (j > partialEndOffset) partialEndOffset = j; 5126 } 5127 } 5128 outText.partialStartOffset = partialStartOffset; 5129 outText.partialEndOffset = partialEndOffset - delta; 5130 5131 if (partialStartOffset > N) { 5132 partialStartOffset = N; 5133 } else if (partialStartOffset < 0) { 5134 partialStartOffset = 0; 5135 } 5136 if (partialEndOffset > N) { 5137 partialEndOffset = N; 5138 } else if (partialEndOffset < 0) { 5139 partialEndOffset = 0; 5140 } 5141 } 5142 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 5143 outText.text = content.subSequence(partialStartOffset, 5144 partialEndOffset); 5145 } else { 5146 outText.text = TextUtils.substring(content, partialStartOffset, 5147 partialEndOffset); 5148 } 5149 } else { 5150 outText.partialStartOffset = 0; 5151 outText.partialEndOffset = 0; 5152 outText.text = ""; 5153 } 5154 outText.flags = 0; 5155 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 5156 outText.flags |= ExtractedText.FLAG_SELECTING; 5157 } 5158 if (mSingleLine) { 5159 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 5160 } 5161 outText.startOffset = 0; 5162 outText.selectionStart = getSelectionStart(); 5163 outText.selectionEnd = getSelectionEnd(); 5164 return true; 5165 } 5166 return false; 5167 } 5168 5169 boolean reportExtractedText() { 5170 final InputMethodState ims = mInputMethodState; 5171 if (ims != null) { 5172 final boolean contentChanged = ims.mContentChanged; 5173 if (contentChanged || ims.mSelectionModeChanged) { 5174 ims.mContentChanged = false; 5175 ims.mSelectionModeChanged = false; 5176 final ExtractedTextRequest req = mInputMethodState.mExtracting; 5177 if (req != null) { 5178 InputMethodManager imm = InputMethodManager.peekInstance(); 5179 if (imm != null) { 5180 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 5181 + ims.mChangedStart + " end=" + ims.mChangedEnd 5182 + " delta=" + ims.mChangedDelta); 5183 if (ims.mChangedStart < 0 && !contentChanged) { 5184 ims.mChangedStart = EXTRACT_NOTHING; 5185 } 5186 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 5187 ims.mChangedDelta, ims.mTmpExtracted)) { 5188 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 5189 + ims.mTmpExtracted.partialStartOffset 5190 + " end=" + ims.mTmpExtracted.partialEndOffset 5191 + ": " + ims.mTmpExtracted.text); 5192 imm.updateExtractedText(this, req.token, 5193 mInputMethodState.mTmpExtracted); 5194 ims.mChangedStart = EXTRACT_UNKNOWN; 5195 ims.mChangedEnd = EXTRACT_UNKNOWN; 5196 ims.mChangedDelta = 0; 5197 ims.mContentChanged = false; 5198 return true; 5199 } 5200 } 5201 } 5202 } 5203 } 5204 return false; 5205 } 5206 5207 /** 5208 * This is used to remove all style-impacting spans from text before new 5209 * extracted text is being replaced into it, so that we don't have any 5210 * lingering spans applied during the replace. 5211 */ 5212 static void removeParcelableSpans(Spannable spannable, int start, int end) { 5213 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 5214 int i = spans.length; 5215 while (i > 0) { 5216 i--; 5217 spannable.removeSpan(spans[i]); 5218 } 5219 } 5220 5221 /** 5222 * Apply to this text view the given extracted text, as previously 5223 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 5224 */ 5225 public void setExtractedText(ExtractedText text) { 5226 Editable content = getEditableText(); 5227 if (text.text != null) { 5228 if (content == null) { 5229 setText(text.text, TextView.BufferType.EDITABLE); 5230 } else if (text.partialStartOffset < 0) { 5231 removeParcelableSpans(content, 0, content.length()); 5232 content.replace(0, content.length(), text.text); 5233 } else { 5234 final int N = content.length(); 5235 int start = text.partialStartOffset; 5236 if (start > N) start = N; 5237 int end = text.partialEndOffset; 5238 if (end > N) end = N; 5239 removeParcelableSpans(content, start, end); 5240 content.replace(start, end, text.text); 5241 } 5242 } 5243 5244 // Now set the selection position... make sure it is in range, to 5245 // avoid crashes. If this is a partial update, it is possible that 5246 // the underlying text may have changed, causing us problems here. 5247 // Also we just don't want to trust clients to do the right thing. 5248 Spannable sp = (Spannable)getText(); 5249 final int N = sp.length(); 5250 int start = text.selectionStart; 5251 if (start < 0) start = 0; 5252 else if (start > N) start = N; 5253 int end = text.selectionEnd; 5254 if (end < 0) end = 0; 5255 else if (end > N) end = N; 5256 Selection.setSelection(sp, start, end); 5257 5258 // Finally, update the selection mode. 5259 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 5260 MetaKeyKeyListener.startSelecting(this, sp); 5261 } else { 5262 MetaKeyKeyListener.stopSelecting(this, sp); 5263 } 5264 } 5265 5266 /** 5267 * @hide 5268 */ 5269 public void setExtracting(ExtractedTextRequest req) { 5270 if (mInputMethodState != null) { 5271 mInputMethodState.mExtracting = req; 5272 } 5273 // This stops a possible text selection mode. Maybe not intended. 5274 hideControllers(); 5275 } 5276 5277 /** 5278 * Called by the framework in response to a text completion from 5279 * the current input method, provided by it calling 5280 * {@link InputConnection#commitCompletion 5281 * InputConnection.commitCompletion()}. The default implementation does 5282 * nothing; text views that are supporting auto-completion should override 5283 * this to do their desired behavior. 5284 * 5285 * @param text The auto complete text the user has selected. 5286 */ 5287 public void onCommitCompletion(CompletionInfo text) { 5288 // intentionally empty 5289 } 5290 5291 /** 5292 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 5293 * a dictionnary) from the current input method, provided by it calling 5294 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 5295 * implementation flashes the background of the corrected word to provide feedback to the user. 5296 * 5297 * @param info The auto correct info about the text that was corrected. 5298 */ 5299 public void onCommitCorrection(CorrectionInfo info) { 5300 if (mCorrectionHighlighter == null) { 5301 mCorrectionHighlighter = new CorrectionHighlighter(); 5302 } else { 5303 mCorrectionHighlighter.invalidate(false); 5304 } 5305 5306 mCorrectionHighlighter.highlight(info); 5307 } 5308 5309 private class CorrectionHighlighter { 5310 private final Path mPath = new Path(); 5311 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5312 private int mStart, mEnd; 5313 private long mFadingStartTime; 5314 private final static int FADE_OUT_DURATION = 400; 5315 5316 public CorrectionHighlighter() { 5317 mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale); 5318 mPaint.setStyle(Paint.Style.FILL); 5319 } 5320 5321 public void highlight(CorrectionInfo info) { 5322 mStart = info.getOffset(); 5323 mEnd = mStart + info.getNewText().length(); 5324 mFadingStartTime = SystemClock.uptimeMillis(); 5325 5326 if (mStart < 0 || mEnd < 0) { 5327 stopAnimation(); 5328 } 5329 } 5330 5331 public void draw(Canvas canvas, int cursorOffsetVertical) { 5332 if (updatePath() && updatePaint()) { 5333 if (cursorOffsetVertical != 0) { 5334 canvas.translate(0, cursorOffsetVertical); 5335 } 5336 5337 canvas.drawPath(mPath, mPaint); 5338 5339 if (cursorOffsetVertical != 0) { 5340 canvas.translate(0, -cursorOffsetVertical); 5341 } 5342 invalidate(true); 5343 } else { 5344 stopAnimation(); 5345 invalidate(false); 5346 } 5347 } 5348 5349 private boolean updatePaint() { 5350 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5351 if (duration > FADE_OUT_DURATION) return false; 5352 5353 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5354 final int highlightColorAlpha = Color.alpha(mHighlightColor); 5355 final int color = (mHighlightColor & 0x00FFFFFF) + 5356 ((int) (highlightColorAlpha * coef) << 24); 5357 mPaint.setColor(color); 5358 return true; 5359 } 5360 5361 private boolean updatePath() { 5362 final Layout layout = TextView.this.mLayout; 5363 if (layout == null) return false; 5364 5365 // Update in case text is edited while the animation is run 5366 final int length = mText.length(); 5367 int start = Math.min(length, mStart); 5368 int end = Math.min(length, mEnd); 5369 5370 mPath.reset(); 5371 TextView.this.mLayout.getSelectionPath(start, end, mPath); 5372 return true; 5373 } 5374 5375 private void invalidate(boolean delayed) { 5376 if (TextView.this.mLayout == null) return; 5377 5378 synchronized (sTempRect) { 5379 mPath.computeBounds(sTempRect, false); 5380 5381 int left = getCompoundPaddingLeft(); 5382 int top = getExtendedPaddingTop() + getVerticalOffset(true); 5383 5384 if (delayed) { 5385 TextView.this.postInvalidateDelayed(16, // 60 Hz update 5386 left + (int) sTempRect.left, top + (int) sTempRect.top, 5387 left + (int) sTempRect.right, top + (int) sTempRect.bottom); 5388 } else { 5389 TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top, 5390 (int) sTempRect.right, (int) sTempRect.bottom); 5391 } 5392 } 5393 } 5394 5395 private void stopAnimation() { 5396 TextView.this.mCorrectionHighlighter = null; 5397 } 5398 } 5399 5400 public void beginBatchEdit() { 5401 mInBatchEditControllers = true; 5402 final InputMethodState ims = mInputMethodState; 5403 if (ims != null) { 5404 int nesting = ++ims.mBatchEditNesting; 5405 if (nesting == 1) { 5406 ims.mCursorChanged = false; 5407 ims.mChangedDelta = 0; 5408 if (ims.mContentChanged) { 5409 // We already have a pending change from somewhere else, 5410 // so turn this into a full update. 5411 ims.mChangedStart = 0; 5412 ims.mChangedEnd = mText.length(); 5413 } else { 5414 ims.mChangedStart = EXTRACT_UNKNOWN; 5415 ims.mChangedEnd = EXTRACT_UNKNOWN; 5416 ims.mContentChanged = false; 5417 } 5418 onBeginBatchEdit(); 5419 } 5420 } 5421 } 5422 5423 public void endBatchEdit() { 5424 mInBatchEditControllers = false; 5425 final InputMethodState ims = mInputMethodState; 5426 if (ims != null) { 5427 int nesting = --ims.mBatchEditNesting; 5428 if (nesting == 0) { 5429 finishBatchEdit(ims); 5430 } 5431 } 5432 } 5433 5434 void ensureEndedBatchEdit() { 5435 final InputMethodState ims = mInputMethodState; 5436 if (ims != null && ims.mBatchEditNesting != 0) { 5437 ims.mBatchEditNesting = 0; 5438 finishBatchEdit(ims); 5439 } 5440 } 5441 5442 void finishBatchEdit(final InputMethodState ims) { 5443 onEndBatchEdit(); 5444 5445 if (ims.mContentChanged || ims.mSelectionModeChanged) { 5446 updateAfterEdit(); 5447 reportExtractedText(); 5448 } else if (ims.mCursorChanged) { 5449 // Cheezy way to get us to report the current cursor location. 5450 invalidateCursor(); 5451 } 5452 } 5453 5454 void updateAfterEdit() { 5455 invalidate(); 5456 int curs = getSelectionStart(); 5457 5458 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 5459 registerForPreDraw(); 5460 } 5461 5462 if (curs >= 0) { 5463 mHighlightPathBogus = true; 5464 makeBlink(); 5465 } 5466 5467 checkForResize(); 5468 } 5469 5470 /** 5471 * Called by the framework in response to a request to begin a batch 5472 * of edit operations through a call to link {@link #beginBatchEdit()}. 5473 */ 5474 public void onBeginBatchEdit() { 5475 // intentionally empty 5476 } 5477 5478 /** 5479 * Called by the framework in response to a request to end a batch 5480 * of edit operations through a call to link {@link #endBatchEdit}. 5481 */ 5482 public void onEndBatchEdit() { 5483 // intentionally empty 5484 } 5485 5486 /** 5487 * Called by the framework in response to a private command from the 5488 * current method, provided by it calling 5489 * {@link InputConnection#performPrivateCommand 5490 * InputConnection.performPrivateCommand()}. 5491 * 5492 * @param action The action name of the command. 5493 * @param data Any additional data for the command. This may be null. 5494 * @return Return true if you handled the command, else false. 5495 */ 5496 public boolean onPrivateIMECommand(String action, Bundle data) { 5497 return false; 5498 } 5499 5500 private void nullLayouts() { 5501 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 5502 mSavedLayout = (BoringLayout) mLayout; 5503 } 5504 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 5505 mSavedHintLayout = (BoringLayout) mHintLayout; 5506 } 5507 5508 mLayout = mHintLayout = null; 5509 5510 // Since it depends on the value of mLayout 5511 prepareCursorControllers(); 5512 } 5513 5514 /** 5515 * Make a new Layout based on the already-measured size of the view, 5516 * on the assumption that it was measured correctly at some point. 5517 */ 5518 private void assumeLayout() { 5519 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5520 5521 if (width < 1) { 5522 width = 0; 5523 } 5524 5525 int physicalWidth = width; 5526 5527 if (mHorizontallyScrolling) { 5528 width = VERY_WIDE; 5529 } 5530 5531 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 5532 physicalWidth, false); 5533 } 5534 5535 /** 5536 * The width passed in is now the desired layout width, 5537 * not the full view width with padding. 5538 * {@hide} 5539 */ 5540 protected void makeNewLayout(int w, int hintWidth, 5541 BoringLayout.Metrics boring, 5542 BoringLayout.Metrics hintBoring, 5543 int ellipsisWidth, boolean bringIntoView) { 5544 stopMarquee(); 5545 5546 mHighlightPathBogus = true; 5547 5548 if (w < 0) { 5549 w = 0; 5550 } 5551 if (hintWidth < 0) { 5552 hintWidth = 0; 5553 } 5554 5555 final int layoutDirection = getResolvedLayoutDirection(); 5556 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 5557 5558 Layout.Alignment alignment; 5559 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 5560 case Gravity.CENTER_HORIZONTAL: 5561 alignment = Layout.Alignment.ALIGN_CENTER; 5562 break; 5563 5564 case Gravity.RIGHT: 5565 // Note, Layout resolves ALIGN_OPPOSITE to left or 5566 // right based on the paragraph direction. 5567 alignment = Layout.Alignment.ALIGN_OPPOSITE; 5568 break; 5569 5570 default: 5571 alignment = Layout.Alignment.ALIGN_NORMAL; 5572 } 5573 5574 boolean shouldEllipsize = mEllipsize != null && mInput == null; 5575 5576 if (mText instanceof Spannable) { 5577 mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w, 5578 alignment, mSpacingMult, 5579 mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null, 5580 ellipsisWidth); 5581 } else { 5582 if (boring == UNKNOWN_BORING) { 5583 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring); 5584 if (boring != null) { 5585 mBoring = boring; 5586 } 5587 } 5588 5589 if (boring != null) { 5590 if (boring.width <= w && 5591 (mEllipsize == null || boring.width <= ellipsisWidth)) { 5592 if (mSavedLayout != null) { 5593 mLayout = mSavedLayout. 5594 replaceOrMake(mTransformed, mTextPaint, 5595 w, alignment, mSpacingMult, mSpacingAdd, 5596 boring, mIncludePad); 5597 } else { 5598 mLayout = BoringLayout.make(mTransformed, mTextPaint, 5599 w, alignment, mSpacingMult, mSpacingAdd, 5600 boring, mIncludePad); 5601 } 5602 5603 mSavedLayout = (BoringLayout) mLayout; 5604 } else if (shouldEllipsize && boring.width <= w) { 5605 if (mSavedLayout != null) { 5606 mLayout = mSavedLayout. 5607 replaceOrMake(mTransformed, mTextPaint, 5608 w, alignment, mSpacingMult, mSpacingAdd, 5609 boring, mIncludePad, mEllipsize, 5610 ellipsisWidth); 5611 } else { 5612 mLayout = BoringLayout.make(mTransformed, mTextPaint, 5613 w, alignment, mSpacingMult, mSpacingAdd, 5614 boring, mIncludePad, mEllipsize, 5615 ellipsisWidth); 5616 } 5617 } else if (shouldEllipsize) { 5618 mLayout = new StaticLayout(mTransformed, 5619 0, mTransformed.length(), 5620 mTextPaint, w, alignment, mSpacingMult, 5621 mSpacingAdd, mIncludePad, mEllipsize, 5622 ellipsisWidth); 5623 } else { 5624 mLayout = new StaticLayout(mTransformed, mTextPaint, 5625 w, alignment, mSpacingMult, mSpacingAdd, 5626 mIncludePad); 5627 } 5628 } else if (shouldEllipsize) { 5629 mLayout = new StaticLayout(mTransformed, 5630 0, mTransformed.length(), 5631 mTextPaint, w, alignment, mSpacingMult, 5632 mSpacingAdd, mIncludePad, mEllipsize, 5633 ellipsisWidth); 5634 } else { 5635 mLayout = new StaticLayout(mTransformed, mTextPaint, 5636 w, alignment, mSpacingMult, mSpacingAdd, 5637 mIncludePad); 5638 } 5639 } 5640 5641 shouldEllipsize = mEllipsize != null; 5642 mHintLayout = null; 5643 5644 if (mHint != null) { 5645 if (shouldEllipsize) hintWidth = w; 5646 5647 if (hintBoring == UNKNOWN_BORING) { 5648 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, 5649 mHintBoring); 5650 if (hintBoring != null) { 5651 mHintBoring = hintBoring; 5652 } 5653 } 5654 5655 if (hintBoring != null) { 5656 if (hintBoring.width <= hintWidth && 5657 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 5658 if (mSavedHintLayout != null) { 5659 mHintLayout = mSavedHintLayout. 5660 replaceOrMake(mHint, mTextPaint, 5661 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5662 hintBoring, mIncludePad); 5663 } else { 5664 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5665 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5666 hintBoring, mIncludePad); 5667 } 5668 5669 mSavedHintLayout = (BoringLayout) mHintLayout; 5670 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 5671 if (mSavedHintLayout != null) { 5672 mHintLayout = mSavedHintLayout. 5673 replaceOrMake(mHint, mTextPaint, 5674 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5675 hintBoring, mIncludePad, mEllipsize, 5676 ellipsisWidth); 5677 } else { 5678 mHintLayout = BoringLayout.make(mHint, mTextPaint, 5679 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5680 hintBoring, mIncludePad, mEllipsize, 5681 ellipsisWidth); 5682 } 5683 } else if (shouldEllipsize) { 5684 mHintLayout = new StaticLayout(mHint, 5685 0, mHint.length(), 5686 mTextPaint, hintWidth, alignment, mSpacingMult, 5687 mSpacingAdd, mIncludePad, mEllipsize, 5688 ellipsisWidth); 5689 } else { 5690 mHintLayout = new StaticLayout(mHint, mTextPaint, 5691 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5692 mIncludePad); 5693 } 5694 } else if (shouldEllipsize) { 5695 mHintLayout = new StaticLayout(mHint, 5696 0, mHint.length(), 5697 mTextPaint, hintWidth, alignment, mSpacingMult, 5698 mSpacingAdd, mIncludePad, mEllipsize, 5699 ellipsisWidth); 5700 } else { 5701 mHintLayout = new StaticLayout(mHint, mTextPaint, 5702 hintWidth, alignment, mSpacingMult, mSpacingAdd, 5703 mIncludePad); 5704 } 5705 } 5706 5707 if (bringIntoView) { 5708 registerForPreDraw(); 5709 } 5710 5711 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 5712 if (!compressText(ellipsisWidth)) { 5713 final int height = mLayoutParams.height; 5714 // If the size of the view does not depend on the size of the text, try to 5715 // start the marquee immediately 5716 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 5717 startMarquee(); 5718 } else { 5719 // Defer the start of the marquee until we know our width (see setFrame()) 5720 mRestartMarquee = true; 5721 } 5722 } 5723 } 5724 5725 // CursorControllers need a non-null mLayout 5726 prepareCursorControllers(); 5727 } 5728 5729 private boolean compressText(float width) { 5730 if (isHardwareAccelerated()) return false; 5731 5732 // Only compress the text if it hasn't been compressed by the previous pass 5733 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 5734 mTextPaint.getTextScaleX() == 1.0f) { 5735 final float textWidth = mLayout.getLineWidth(0); 5736 final float overflow = (textWidth + 1.0f - width) / width; 5737 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 5738 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 5739 post(new Runnable() { 5740 public void run() { 5741 requestLayout(); 5742 } 5743 }); 5744 return true; 5745 } 5746 } 5747 5748 return false; 5749 } 5750 5751 private static int desired(Layout layout) { 5752 int n = layout.getLineCount(); 5753 CharSequence text = layout.getText(); 5754 float max = 0; 5755 5756 // if any line was wrapped, we can't use it. 5757 // but it's ok for the last line not to have a newline 5758 5759 for (int i = 0; i < n - 1; i++) { 5760 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 5761 return -1; 5762 } 5763 5764 for (int i = 0; i < n; i++) { 5765 max = Math.max(max, layout.getLineWidth(i)); 5766 } 5767 5768 return (int) FloatMath.ceil(max); 5769 } 5770 5771 /** 5772 * Set whether the TextView includes extra top and bottom padding to make 5773 * room for accents that go above the normal ascent and descent. 5774 * The default is true. 5775 * 5776 * @attr ref android.R.styleable#TextView_includeFontPadding 5777 */ 5778 public void setIncludeFontPadding(boolean includepad) { 5779 mIncludePad = includepad; 5780 5781 if (mLayout != null) { 5782 nullLayouts(); 5783 requestLayout(); 5784 invalidate(); 5785 } 5786 } 5787 5788 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 5789 5790 @Override 5791 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5792 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5793 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5794 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5795 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5796 5797 int width; 5798 int height; 5799 5800 BoringLayout.Metrics boring = UNKNOWN_BORING; 5801 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 5802 5803 int des = -1; 5804 boolean fromexisting = false; 5805 5806 if (widthMode == MeasureSpec.EXACTLY) { 5807 // Parent has told us how big to be. So be it. 5808 width = widthSize; 5809 } else { 5810 if (mLayout != null && mEllipsize == null) { 5811 des = desired(mLayout); 5812 } 5813 5814 if (des < 0) { 5815 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mBoring); 5816 if (boring != null) { 5817 mBoring = boring; 5818 } 5819 } else { 5820 fromexisting = true; 5821 } 5822 5823 if (boring == null || boring == UNKNOWN_BORING) { 5824 if (des < 0) { 5825 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 5826 } 5827 5828 width = des; 5829 } else { 5830 width = boring.width; 5831 } 5832 5833 final Drawables dr = mDrawables; 5834 if (dr != null) { 5835 width = Math.max(width, dr.mDrawableWidthTop); 5836 width = Math.max(width, dr.mDrawableWidthBottom); 5837 } 5838 5839 if (mHint != null) { 5840 int hintDes = -1; 5841 int hintWidth; 5842 5843 if (mHintLayout != null && mEllipsize == null) { 5844 hintDes = desired(mHintLayout); 5845 } 5846 5847 if (hintDes < 0) { 5848 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 5849 if (hintBoring != null) { 5850 mHintBoring = hintBoring; 5851 } 5852 } 5853 5854 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 5855 if (hintDes < 0) { 5856 hintDes = (int) FloatMath.ceil( 5857 Layout.getDesiredWidth(mHint, mTextPaint)); 5858 } 5859 5860 hintWidth = hintDes; 5861 } else { 5862 hintWidth = hintBoring.width; 5863 } 5864 5865 if (hintWidth > width) { 5866 width = hintWidth; 5867 } 5868 } 5869 5870 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 5871 5872 if (mMaxWidthMode == EMS) { 5873 width = Math.min(width, mMaxWidth * getLineHeight()); 5874 } else { 5875 width = Math.min(width, mMaxWidth); 5876 } 5877 5878 if (mMinWidthMode == EMS) { 5879 width = Math.max(width, mMinWidth * getLineHeight()); 5880 } else { 5881 width = Math.max(width, mMinWidth); 5882 } 5883 5884 // Check against our minimum width 5885 width = Math.max(width, getSuggestedMinimumWidth()); 5886 5887 if (widthMode == MeasureSpec.AT_MOST) { 5888 width = Math.min(widthSize, width); 5889 } 5890 } 5891 5892 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5893 int unpaddedWidth = want; 5894 5895 if (mHorizontallyScrolling) want = VERY_WIDE; 5896 5897 int hintWant = want; 5898 int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth(); 5899 5900 if (mLayout == null) { 5901 makeNewLayout(want, hintWant, boring, hintBoring, 5902 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5903 } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) || 5904 (mLayout.getEllipsizedWidth() != 5905 width - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 5906 if (mHint == null && mEllipsize == null && 5907 want > mLayout.getWidth() && 5908 (mLayout instanceof BoringLayout || 5909 (fromexisting && des >= 0 && des <= want))) { 5910 mLayout.increaseWidthTo(want); 5911 } else { 5912 makeNewLayout(want, hintWant, boring, hintBoring, 5913 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 5914 } 5915 } else { 5916 // Width has not changed. 5917 } 5918 5919 if (heightMode == MeasureSpec.EXACTLY) { 5920 // Parent has told us how big to be. So be it. 5921 height = heightSize; 5922 mDesiredHeightAtMeasure = -1; 5923 } else { 5924 int desired = getDesiredHeight(); 5925 5926 height = desired; 5927 mDesiredHeightAtMeasure = desired; 5928 5929 if (heightMode == MeasureSpec.AT_MOST) { 5930 height = Math.min(desired, heightSize); 5931 } 5932 } 5933 5934 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 5935 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 5936 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 5937 } 5938 5939 /* 5940 * We didn't let makeNewLayout() register to bring the cursor into view, 5941 * so do it here if there is any possibility that it is needed. 5942 */ 5943 if (mMovement != null || 5944 mLayout.getWidth() > unpaddedWidth || 5945 mLayout.getHeight() > unpaddedHeight) { 5946 registerForPreDraw(); 5947 } else { 5948 scrollTo(0, 0); 5949 } 5950 5951 setMeasuredDimension(width, height); 5952 } 5953 5954 private int getDesiredHeight() { 5955 return Math.max( 5956 getDesiredHeight(mLayout, true), 5957 getDesiredHeight(mHintLayout, mEllipsize != null)); 5958 } 5959 5960 private int getDesiredHeight(Layout layout, boolean cap) { 5961 if (layout == null) { 5962 return 0; 5963 } 5964 5965 int linecount = layout.getLineCount(); 5966 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 5967 int desired = layout.getLineTop(linecount); 5968 5969 final Drawables dr = mDrawables; 5970 if (dr != null) { 5971 desired = Math.max(desired, dr.mDrawableHeightLeft); 5972 desired = Math.max(desired, dr.mDrawableHeightRight); 5973 } 5974 5975 desired += pad; 5976 layout.setMaximumVisibleLineCount(0); 5977 5978 if (mMaxMode == LINES) { 5979 /* 5980 * Don't cap the hint to a certain number of lines. 5981 * (Do cap it, though, if we have a maximum pixel height.) 5982 */ 5983 if (cap) { 5984 if (linecount > mMaximum) { 5985 layout.setMaximumVisibleLineCount(mMaximum); 5986 desired = layout.getLineTop(mMaximum); 5987 5988 if (dr != null) { 5989 desired = Math.max(desired, dr.mDrawableHeightLeft); 5990 desired = Math.max(desired, dr.mDrawableHeightRight); 5991 } 5992 5993 desired += pad; 5994 linecount = mMaximum; 5995 } 5996 } 5997 } else { 5998 desired = Math.min(desired, mMaximum); 5999 } 6000 6001 if (mMinMode == LINES) { 6002 if (linecount < mMinimum) { 6003 desired += getLineHeight() * (mMinimum - linecount); 6004 } 6005 } else { 6006 desired = Math.max(desired, mMinimum); 6007 } 6008 6009 // Check against our minimum height 6010 desired = Math.max(desired, getSuggestedMinimumHeight()); 6011 6012 return desired; 6013 } 6014 6015 /** 6016 * Check whether a change to the existing text layout requires a 6017 * new view layout. 6018 */ 6019 private void checkForResize() { 6020 boolean sizeChanged = false; 6021 6022 if (mLayout != null) { 6023 // Check if our width changed 6024 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 6025 sizeChanged = true; 6026 invalidate(); 6027 } 6028 6029 // Check if our height changed 6030 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 6031 int desiredHeight = getDesiredHeight(); 6032 6033 if (desiredHeight != this.getHeight()) { 6034 sizeChanged = true; 6035 } 6036 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 6037 if (mDesiredHeightAtMeasure >= 0) { 6038 int desiredHeight = getDesiredHeight(); 6039 6040 if (desiredHeight != mDesiredHeightAtMeasure) { 6041 sizeChanged = true; 6042 } 6043 } 6044 } 6045 } 6046 6047 if (sizeChanged) { 6048 requestLayout(); 6049 // caller will have already invalidated 6050 } 6051 } 6052 6053 /** 6054 * Check whether entirely new text requires a new view layout 6055 * or merely a new text layout. 6056 */ 6057 private void checkForRelayout() { 6058 // If we have a fixed width, we can just swap in a new text layout 6059 // if the text height stays the same or if the view height is fixed. 6060 6061 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 6062 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 6063 (mHint == null || mHintLayout != null) && 6064 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 6065 // Static width, so try making a new text layout. 6066 6067 int oldht = mLayout.getHeight(); 6068 int want = mLayout.getWidth(); 6069 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 6070 6071 /* 6072 * No need to bring the text into view, since the size is not 6073 * changing (unless we do the requestLayout(), in which case it 6074 * will happen at measure). 6075 */ 6076 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 6077 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 6078 false); 6079 6080 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 6081 // In a fixed-height view, so use our new text layout. 6082 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 6083 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 6084 invalidate(); 6085 return; 6086 } 6087 6088 // Dynamic height, but height has stayed the same, 6089 // so use our new text layout. 6090 if (mLayout.getHeight() == oldht && 6091 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 6092 invalidate(); 6093 return; 6094 } 6095 } 6096 6097 // We lose: the height has changed and we have a dynamic height. 6098 // Request a new view layout using our new text layout. 6099 requestLayout(); 6100 invalidate(); 6101 } else { 6102 // Dynamic width, so we have no choice but to request a new 6103 // view layout with a new text layout. 6104 6105 nullLayouts(); 6106 requestLayout(); 6107 invalidate(); 6108 } 6109 } 6110 6111 /** 6112 * Returns true if anything changed. 6113 */ 6114 private boolean bringTextIntoView() { 6115 int line = 0; 6116 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6117 line = mLayout.getLineCount() - 1; 6118 } 6119 6120 Layout.Alignment a = mLayout.getParagraphAlignment(line); 6121 int dir = mLayout.getParagraphDirection(line); 6122 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6123 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6124 int ht = mLayout.getHeight(); 6125 6126 int scrollx, scrolly; 6127 6128 if (a == Layout.Alignment.ALIGN_CENTER) { 6129 /* 6130 * Keep centered if possible, or, if it is too wide to fit, 6131 * keep leading edge in view. 6132 */ 6133 6134 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6135 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6136 6137 if (right - left < hspace) { 6138 scrollx = (right + left) / 2 - hspace / 2; 6139 } else { 6140 if (dir < 0) { 6141 scrollx = right - hspace; 6142 } else { 6143 scrollx = left; 6144 } 6145 } 6146 } else if (a == Layout.Alignment.ALIGN_NORMAL) { 6147 /* 6148 * Keep leading edge in view. 6149 */ 6150 6151 if (dir < 0) { 6152 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6153 scrollx = right - hspace; 6154 } else { 6155 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6156 } 6157 } else /* a == Layout.Alignment.ALIGN_OPPOSITE */ { 6158 /* 6159 * Keep trailing edge in view. 6160 */ 6161 6162 if (dir < 0) { 6163 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6164 } else { 6165 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6166 scrollx = right - hspace; 6167 } 6168 } 6169 6170 if (ht < vspace) { 6171 scrolly = 0; 6172 } else { 6173 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6174 scrolly = ht - vspace; 6175 } else { 6176 scrolly = 0; 6177 } 6178 } 6179 6180 if (scrollx != mScrollX || scrolly != mScrollY) { 6181 scrollTo(scrollx, scrolly); 6182 return true; 6183 } else { 6184 return false; 6185 } 6186 } 6187 6188 /** 6189 * Move the point, specified by the offset, into the view if it is needed. 6190 * This has to be called after layout. Returns true if anything changed. 6191 */ 6192 public boolean bringPointIntoView(int offset) { 6193 boolean changed = false; 6194 6195 int line = mLayout.getLineForOffset(offset); 6196 6197 // FIXME: Is it okay to truncate this, or should we round? 6198 final int x = (int)mLayout.getPrimaryHorizontal(offset); 6199 final int top = mLayout.getLineTop(line); 6200 final int bottom = mLayout.getLineTop(line + 1); 6201 6202 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6203 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6204 int ht = mLayout.getHeight(); 6205 6206 int grav; 6207 6208 switch (mLayout.getParagraphAlignment(line)) { 6209 case ALIGN_NORMAL: 6210 grav = 1; 6211 break; 6212 6213 case ALIGN_OPPOSITE: 6214 grav = -1; 6215 break; 6216 6217 default: 6218 grav = 0; 6219 } 6220 6221 grav *= mLayout.getParagraphDirection(line); 6222 6223 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6224 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6225 6226 int hslack = (bottom - top) / 2; 6227 int vslack = hslack; 6228 6229 if (vslack > vspace / 4) 6230 vslack = vspace / 4; 6231 if (hslack > hspace / 4) 6232 hslack = hspace / 4; 6233 6234 int hs = mScrollX; 6235 int vs = mScrollY; 6236 6237 if (top - vs < vslack) 6238 vs = top - vslack; 6239 if (bottom - vs > vspace - vslack) 6240 vs = bottom - (vspace - vslack); 6241 if (ht - vs < vspace) 6242 vs = ht - vspace; 6243 if (0 - vs > 0) 6244 vs = 0; 6245 6246 if (grav != 0) { 6247 if (x - hs < hslack) { 6248 hs = x - hslack; 6249 } 6250 if (x - hs > hspace - hslack) { 6251 hs = x - (hspace - hslack); 6252 } 6253 } 6254 6255 if (grav < 0) { 6256 if (left - hs > 0) 6257 hs = left; 6258 if (right - hs < hspace) 6259 hs = right - hspace; 6260 } else if (grav > 0) { 6261 if (right - hs < hspace) 6262 hs = right - hspace; 6263 if (left - hs > 0) 6264 hs = left; 6265 } else /* grav == 0 */ { 6266 if (right - left <= hspace) { 6267 /* 6268 * If the entire text fits, center it exactly. 6269 */ 6270 hs = left - (hspace - (right - left)) / 2; 6271 } else if (x > right - hslack) { 6272 /* 6273 * If we are near the right edge, keep the right edge 6274 * at the edge of the view. 6275 */ 6276 hs = right - hspace; 6277 } else if (x < left + hslack) { 6278 /* 6279 * If we are near the left edge, keep the left edge 6280 * at the edge of the view. 6281 */ 6282 hs = left; 6283 } else if (left > hs) { 6284 /* 6285 * Is there whitespace visible at the left? Fix it if so. 6286 */ 6287 hs = left; 6288 } else if (right < hs + hspace) { 6289 /* 6290 * Is there whitespace visible at the right? Fix it if so. 6291 */ 6292 hs = right - hspace; 6293 } else { 6294 /* 6295 * Otherwise, float as needed. 6296 */ 6297 if (x - hs < hslack) { 6298 hs = x - hslack; 6299 } 6300 if (x - hs > hspace - hslack) { 6301 hs = x - (hspace - hslack); 6302 } 6303 } 6304 } 6305 6306 if (hs != mScrollX || vs != mScrollY) { 6307 if (mScroller == null) { 6308 scrollTo(hs, vs); 6309 } else { 6310 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6311 int dx = hs - mScrollX; 6312 int dy = vs - mScrollY; 6313 6314 if (duration > ANIMATED_SCROLL_GAP) { 6315 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6316 awakenScrollBars(mScroller.getDuration()); 6317 invalidate(); 6318 } else { 6319 if (!mScroller.isFinished()) { 6320 mScroller.abortAnimation(); 6321 } 6322 6323 scrollBy(dx, dy); 6324 } 6325 6326 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6327 } 6328 6329 changed = true; 6330 } 6331 6332 if (isFocused()) { 6333 // This offsets because getInterestingRect() is in terms of viewport coordinates, but 6334 // requestRectangleOnScreen() is in terms of content coordinates. 6335 6336 if (mTempRect == null) mTempRect = new Rect(); 6337 mTempRect.set(x, top, x + 1, bottom); 6338 getInterestingRect(mTempRect, line); 6339 mTempRect.offset(mScrollX, mScrollY); 6340 6341 if (requestRectangleOnScreen(mTempRect)) { 6342 changed = true; 6343 } 6344 } 6345 6346 return changed; 6347 } 6348 6349 /** 6350 * Move the cursor, if needed, so that it is at an offset that is visible 6351 * to the user. This will not move the cursor if it represents more than 6352 * one character (a selection range). This will only work if the 6353 * TextView contains spannable text; otherwise it will do nothing. 6354 * 6355 * @return True if the cursor was actually moved, false otherwise. 6356 */ 6357 public boolean moveCursorToVisibleOffset() { 6358 if (!(mText instanceof Spannable)) { 6359 return false; 6360 } 6361 int start = getSelectionStart(); 6362 int end = getSelectionEnd(); 6363 if (start != end) { 6364 return false; 6365 } 6366 6367 // First: make sure the line is visible on screen: 6368 6369 int line = mLayout.getLineForOffset(start); 6370 6371 final int top = mLayout.getLineTop(line); 6372 final int bottom = mLayout.getLineTop(line + 1); 6373 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6374 int vslack = (bottom - top) / 2; 6375 if (vslack > vspace / 4) 6376 vslack = vspace / 4; 6377 final int vs = mScrollY; 6378 6379 if (top < (vs+vslack)) { 6380 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 6381 } else if (bottom > (vspace+vs-vslack)) { 6382 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 6383 } 6384 6385 // Next: make sure the character is visible on screen: 6386 6387 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6388 final int hs = mScrollX; 6389 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 6390 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 6391 6392 // line might contain bidirectional text 6393 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 6394 final int highChar = leftChar > rightChar ? leftChar : rightChar; 6395 6396 int newStart = start; 6397 if (newStart < lowChar) { 6398 newStart = lowChar; 6399 } else if (newStart > highChar) { 6400 newStart = highChar; 6401 } 6402 6403 if (newStart != start) { 6404 Selection.setSelection((Spannable)mText, newStart); 6405 return true; 6406 } 6407 6408 return false; 6409 } 6410 6411 @Override 6412 public void computeScroll() { 6413 if (mScroller != null) { 6414 if (mScroller.computeScrollOffset()) { 6415 mScrollX = mScroller.getCurrX(); 6416 mScrollY = mScroller.getCurrY(); 6417 invalidateParentCaches(); 6418 postInvalidate(); // So we draw again 6419 } 6420 } 6421 } 6422 6423 private void getInterestingRect(Rect r, int line) { 6424 convertFromViewportToContentCoordinates(r); 6425 6426 // Rectangle can can be expanded on first and last line to take 6427 // padding into account. 6428 // TODO Take left/right padding into account too? 6429 if (line == 0) r.top -= getExtendedPaddingTop(); 6430 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 6431 } 6432 6433 private void convertFromViewportToContentCoordinates(Rect r) { 6434 final int horizontalOffset = viewportToContentHorizontalOffset(); 6435 r.left += horizontalOffset; 6436 r.right += horizontalOffset; 6437 6438 final int verticalOffset = viewportToContentVerticalOffset(); 6439 r.top += verticalOffset; 6440 r.bottom += verticalOffset; 6441 } 6442 6443 private int viewportToContentHorizontalOffset() { 6444 return getCompoundPaddingLeft() - mScrollX; 6445 } 6446 6447 private int viewportToContentVerticalOffset() { 6448 int offset = getExtendedPaddingTop() - mScrollY; 6449 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 6450 offset += getVerticalOffset(false); 6451 } 6452 return offset; 6453 } 6454 6455 @Override 6456 public void debug(int depth) { 6457 super.debug(depth); 6458 6459 String output = debugIndent(depth); 6460 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 6461 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 6462 + "} "; 6463 6464 if (mText != null) { 6465 6466 output += "mText=\"" + mText + "\" "; 6467 if (mLayout != null) { 6468 output += "mLayout width=" + mLayout.getWidth() 6469 + " height=" + mLayout.getHeight(); 6470 } 6471 } else { 6472 output += "mText=NULL"; 6473 } 6474 Log.d(VIEW_LOG_TAG, output); 6475 } 6476 6477 /** 6478 * Convenience for {@link Selection#getSelectionStart}. 6479 */ 6480 @ViewDebug.ExportedProperty(category = "text") 6481 public int getSelectionStart() { 6482 return Selection.getSelectionStart(getText()); 6483 } 6484 6485 /** 6486 * Convenience for {@link Selection#getSelectionEnd}. 6487 */ 6488 @ViewDebug.ExportedProperty(category = "text") 6489 public int getSelectionEnd() { 6490 return Selection.getSelectionEnd(getText()); 6491 } 6492 6493 /** 6494 * Return true iff there is a selection inside this text view. 6495 */ 6496 public boolean hasSelection() { 6497 final int selectionStart = getSelectionStart(); 6498 final int selectionEnd = getSelectionEnd(); 6499 6500 return selectionStart >= 0 && selectionStart != selectionEnd; 6501 } 6502 6503 /** 6504 * Sets the properties of this field (lines, horizontally scrolling, 6505 * transformation method) to be for a single-line input. 6506 * 6507 * @attr ref android.R.styleable#TextView_singleLine 6508 */ 6509 public void setSingleLine() { 6510 setSingleLine(true); 6511 } 6512 6513 /** 6514 * If true, sets the properties of this field (number of lines, horizontally scrolling, 6515 * transformation method) to be for a single-line input; if false, restores these to the default 6516 * conditions. 6517 * 6518 * Note that the default conditions are not necessarily those that were in effect prior this 6519 * method, and you may want to reset these properties to your custom values. 6520 * 6521 * @attr ref android.R.styleable#TextView_singleLine 6522 */ 6523 @android.view.RemotableViewMethod 6524 public void setSingleLine(boolean singleLine) { 6525 // Could be used, but may break backward compatibility. 6526 // if (mSingleLine == singleLine) return; 6527 setInputTypeSingleLine(singleLine); 6528 applySingleLine(singleLine, true, true); 6529 } 6530 6531 /** 6532 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 6533 * @param singleLine 6534 */ 6535 private void setInputTypeSingleLine(boolean singleLine) { 6536 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 6537 if (singleLine) { 6538 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 6539 } else { 6540 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 6541 } 6542 } 6543 } 6544 6545 private void applySingleLine(boolean singleLine, boolean applyTransformation, 6546 boolean changeMaxLines) { 6547 mSingleLine = singleLine; 6548 if (singleLine) { 6549 setLines(1); 6550 setHorizontallyScrolling(true); 6551 if (applyTransformation) { 6552 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 6553 } 6554 } else { 6555 if (changeMaxLines) { 6556 setMaxLines(Integer.MAX_VALUE); 6557 } 6558 setHorizontallyScrolling(false); 6559 if (applyTransformation) { 6560 setTransformationMethod(null); 6561 } 6562 } 6563 } 6564 6565 /** 6566 * Causes words in the text that are longer than the view is wide 6567 * to be ellipsized instead of broken in the middle. You may also 6568 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 6569 * to constrain the text to a single line. Use <code>null</code> 6570 * to turn off ellipsizing. 6571 * 6572 * @attr ref android.R.styleable#TextView_ellipsize 6573 */ 6574 public void setEllipsize(TextUtils.TruncateAt where) { 6575 mEllipsize = where; 6576 6577 if (mLayout != null) { 6578 nullLayouts(); 6579 requestLayout(); 6580 invalidate(); 6581 } 6582 } 6583 6584 /** 6585 * Sets how many times to repeat the marquee animation. Only applied if the 6586 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 6587 * 6588 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 6589 */ 6590 public void setMarqueeRepeatLimit(int marqueeLimit) { 6591 mMarqueeRepeatLimit = marqueeLimit; 6592 } 6593 6594 /** 6595 * Returns where, if anywhere, words that are longer than the view 6596 * is wide should be ellipsized. 6597 */ 6598 @ViewDebug.ExportedProperty 6599 public TextUtils.TruncateAt getEllipsize() { 6600 return mEllipsize; 6601 } 6602 6603 /** 6604 * Set the TextView so that when it takes focus, all the text is 6605 * selected. 6606 * 6607 * @attr ref android.R.styleable#TextView_selectAllOnFocus 6608 */ 6609 @android.view.RemotableViewMethod 6610 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 6611 mSelectAllOnFocus = selectAllOnFocus; 6612 6613 if (selectAllOnFocus && !(mText instanceof Spannable)) { 6614 setText(mText, BufferType.SPANNABLE); 6615 } 6616 } 6617 6618 /** 6619 * Set whether the cursor is visible. The default is true. 6620 * 6621 * @attr ref android.R.styleable#TextView_cursorVisible 6622 */ 6623 @android.view.RemotableViewMethod 6624 public void setCursorVisible(boolean visible) { 6625 if (mCursorVisible != visible) { 6626 mCursorVisible = visible; 6627 invalidate(); 6628 6629 makeBlink(); 6630 6631 // InsertionPointCursorController depends on mCursorVisible 6632 prepareCursorControllers(); 6633 } 6634 } 6635 6636 private boolean isCursorVisible() { 6637 return mCursorVisible && isTextEditable(); 6638 } 6639 6640 private boolean canMarquee() { 6641 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 6642 return width > 0 && mLayout.getLineWidth(0) > width; 6643 } 6644 6645 private void startMarquee() { 6646 // Do not ellipsize EditText 6647 if (mInput != null) return; 6648 6649 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 6650 return; 6651 } 6652 6653 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 6654 getLineCount() == 1 && canMarquee()) { 6655 6656 if (mMarquee == null) mMarquee = new Marquee(this); 6657 mMarquee.start(mMarqueeRepeatLimit); 6658 } 6659 } 6660 6661 private void stopMarquee() { 6662 if (mMarquee != null && !mMarquee.isStopped()) { 6663 mMarquee.stop(); 6664 } 6665 } 6666 6667 private void startStopMarquee(boolean start) { 6668 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6669 if (start) { 6670 startMarquee(); 6671 } else { 6672 stopMarquee(); 6673 } 6674 } 6675 } 6676 6677 private static final class Marquee extends Handler { 6678 // TODO: Add an option to configure this 6679 private static final float MARQUEE_DELTA_MAX = 0.07f; 6680 private static final int MARQUEE_DELAY = 1200; 6681 private static final int MARQUEE_RESTART_DELAY = 1200; 6682 private static final int MARQUEE_RESOLUTION = 1000 / 30; 6683 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 6684 6685 private static final byte MARQUEE_STOPPED = 0x0; 6686 private static final byte MARQUEE_STARTING = 0x1; 6687 private static final byte MARQUEE_RUNNING = 0x2; 6688 6689 private static final int MESSAGE_START = 0x1; 6690 private static final int MESSAGE_TICK = 0x2; 6691 private static final int MESSAGE_RESTART = 0x3; 6692 6693 private final WeakReference<TextView> mView; 6694 6695 private byte mStatus = MARQUEE_STOPPED; 6696 private final float mScrollUnit; 6697 private float mMaxScroll; 6698 float mMaxFadeScroll; 6699 private float mGhostStart; 6700 private float mGhostOffset; 6701 private float mFadeStop; 6702 private int mRepeatLimit; 6703 6704 float mScroll; 6705 6706 Marquee(TextView v) { 6707 final float density = v.getContext().getResources().getDisplayMetrics().density; 6708 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 6709 mView = new WeakReference<TextView>(v); 6710 } 6711 6712 @Override 6713 public void handleMessage(Message msg) { 6714 switch (msg.what) { 6715 case MESSAGE_START: 6716 mStatus = MARQUEE_RUNNING; 6717 tick(); 6718 break; 6719 case MESSAGE_TICK: 6720 tick(); 6721 break; 6722 case MESSAGE_RESTART: 6723 if (mStatus == MARQUEE_RUNNING) { 6724 if (mRepeatLimit >= 0) { 6725 mRepeatLimit--; 6726 } 6727 start(mRepeatLimit); 6728 } 6729 break; 6730 } 6731 } 6732 6733 void tick() { 6734 if (mStatus != MARQUEE_RUNNING) { 6735 return; 6736 } 6737 6738 removeMessages(MESSAGE_TICK); 6739 6740 final TextView textView = mView.get(); 6741 if (textView != null && (textView.isFocused() || textView.isSelected())) { 6742 mScroll += mScrollUnit; 6743 if (mScroll > mMaxScroll) { 6744 mScroll = mMaxScroll; 6745 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 6746 } else { 6747 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 6748 } 6749 textView.invalidate(); 6750 } 6751 } 6752 6753 void stop() { 6754 mStatus = MARQUEE_STOPPED; 6755 removeMessages(MESSAGE_START); 6756 removeMessages(MESSAGE_RESTART); 6757 removeMessages(MESSAGE_TICK); 6758 resetScroll(); 6759 } 6760 6761 private void resetScroll() { 6762 mScroll = 0.0f; 6763 final TextView textView = mView.get(); 6764 if (textView != null) textView.invalidate(); 6765 } 6766 6767 void start(int repeatLimit) { 6768 if (repeatLimit == 0) { 6769 stop(); 6770 return; 6771 } 6772 mRepeatLimit = repeatLimit; 6773 final TextView textView = mView.get(); 6774 if (textView != null && textView.mLayout != null) { 6775 mStatus = MARQUEE_STARTING; 6776 mScroll = 0.0f; 6777 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 6778 textView.getCompoundPaddingRight(); 6779 final float lineWidth = textView.mLayout.getLineWidth(0); 6780 final float gap = textWidth / 3.0f; 6781 mGhostStart = lineWidth - textWidth + gap; 6782 mMaxScroll = mGhostStart + textWidth; 6783 mGhostOffset = lineWidth + gap; 6784 mFadeStop = lineWidth + textWidth / 6.0f; 6785 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 6786 6787 textView.invalidate(); 6788 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 6789 } 6790 } 6791 6792 float getGhostOffset() { 6793 return mGhostOffset; 6794 } 6795 6796 boolean shouldDrawLeftFade() { 6797 return mScroll <= mFadeStop; 6798 } 6799 6800 boolean shouldDrawGhost() { 6801 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 6802 } 6803 6804 boolean isRunning() { 6805 return mStatus == MARQUEE_RUNNING; 6806 } 6807 6808 boolean isStopped() { 6809 return mStatus == MARQUEE_STOPPED; 6810 } 6811 } 6812 6813 /** 6814 * This method is called when the text is changed, in case any subclasses 6815 * would like to know. 6816 * 6817 * Within <code>text</code>, the <code>lengthAfter</code> characters 6818 * beginning at <code>start</code> have just replaced old text that had 6819 * length <code>lengthBefore</code>. It is an error to attempt to make 6820 * changes to <code>text</code> from this callback. 6821 * 6822 * @param text The text the TextView is displaying 6823 * @param start The offset of the start of the range of the text that was 6824 * modified 6825 * @param lengthBefore The length of the former text that has been replaced 6826 * @param lengthAfter The length of the replacement modified text 6827 */ 6828 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 6829 // intentionally empty 6830 } 6831 6832 /** 6833 * This method is called when the selection has changed, in case any 6834 * subclasses would like to know. 6835 * 6836 * @param selStart The new selection start location. 6837 * @param selEnd The new selection end location. 6838 */ 6839 protected void onSelectionChanged(int selStart, int selEnd) { 6840 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 6841 } 6842 6843 /** 6844 * Adds a TextWatcher to the list of those whose methods are called 6845 * whenever this TextView's text changes. 6846 * <p> 6847 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 6848 * not called after {@link #setText} calls. Now, doing {@link #setText} 6849 * if there are any text changed listeners forces the buffer type to 6850 * Editable if it would not otherwise be and does call this method. 6851 */ 6852 public void addTextChangedListener(TextWatcher watcher) { 6853 if (mListeners == null) { 6854 mListeners = new ArrayList<TextWatcher>(); 6855 } 6856 6857 mListeners.add(watcher); 6858 } 6859 6860 /** 6861 * Removes the specified TextWatcher from the list of those whose 6862 * methods are called 6863 * whenever this TextView's text changes. 6864 */ 6865 public void removeTextChangedListener(TextWatcher watcher) { 6866 if (mListeners != null) { 6867 int i = mListeners.indexOf(watcher); 6868 6869 if (i >= 0) { 6870 mListeners.remove(i); 6871 } 6872 } 6873 } 6874 6875 private void sendBeforeTextChanged(CharSequence text, int start, int before, 6876 int after) { 6877 if (mListeners != null) { 6878 final ArrayList<TextWatcher> list = mListeners; 6879 final int count = list.size(); 6880 for (int i = 0; i < count; i++) { 6881 list.get(i).beforeTextChanged(text, start, before, after); 6882 } 6883 } 6884 } 6885 6886 /** 6887 * Not private so it can be called from an inner class without going 6888 * through a thunk. 6889 */ 6890 void sendOnTextChanged(CharSequence text, int start, int before, 6891 int after) { 6892 if (mListeners != null) { 6893 final ArrayList<TextWatcher> list = mListeners; 6894 final int count = list.size(); 6895 for (int i = 0; i < count; i++) { 6896 list.get(i).onTextChanged(text, start, before, after); 6897 } 6898 } 6899 } 6900 6901 /** 6902 * Not private so it can be called from an inner class without going 6903 * through a thunk. 6904 */ 6905 void sendAfterTextChanged(Editable text) { 6906 if (mListeners != null) { 6907 final ArrayList<TextWatcher> list = mListeners; 6908 final int count = list.size(); 6909 for (int i = 0; i < count; i++) { 6910 list.get(i).afterTextChanged(text); 6911 } 6912 } 6913 } 6914 6915 /** 6916 * Not private so it can be called from an inner class without going 6917 * through a thunk. 6918 */ 6919 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 6920 final InputMethodState ims = mInputMethodState; 6921 if (ims == null || ims.mBatchEditNesting == 0) { 6922 updateAfterEdit(); 6923 } 6924 if (ims != null) { 6925 ims.mContentChanged = true; 6926 if (ims.mChangedStart < 0) { 6927 ims.mChangedStart = start; 6928 ims.mChangedEnd = start+before; 6929 } else { 6930 ims.mChangedStart = Math.min(ims.mChangedStart, start); 6931 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 6932 } 6933 ims.mChangedDelta += after-before; 6934 } 6935 6936 sendOnTextChanged(buffer, start, before, after); 6937 onTextChanged(buffer, start, before, after); 6938 6939 // Hide the controllers if the amount of content changed 6940 if (before != after) { 6941 hideControllers(); 6942 } 6943 } 6944 6945 /** 6946 * Not private so it can be called from an inner class without going 6947 * through a thunk. 6948 */ 6949 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 6950 // XXX Make the start and end move together if this ends up 6951 // spending too much time invalidating. 6952 6953 boolean selChanged = false; 6954 int newSelStart=-1, newSelEnd=-1; 6955 6956 final InputMethodState ims = mInputMethodState; 6957 6958 if (what == Selection.SELECTION_END) { 6959 mHighlightPathBogus = true; 6960 selChanged = true; 6961 newSelEnd = newStart; 6962 6963 if (!isFocused()) { 6964 mSelectionMoved = true; 6965 } 6966 6967 if (oldStart >= 0 || newStart >= 0) { 6968 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 6969 registerForPreDraw(); 6970 makeBlink(); 6971 } 6972 } 6973 6974 if (what == Selection.SELECTION_START) { 6975 mHighlightPathBogus = true; 6976 selChanged = true; 6977 newSelStart = newStart; 6978 6979 if (!isFocused()) { 6980 mSelectionMoved = true; 6981 } 6982 6983 if (oldStart >= 0 || newStart >= 0) { 6984 int end = Selection.getSelectionEnd(buf); 6985 invalidateCursor(end, oldStart, newStart); 6986 } 6987 } 6988 6989 if (selChanged) { 6990 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 6991 if (newSelStart < 0) { 6992 newSelStart = Selection.getSelectionStart(buf); 6993 } 6994 if (newSelEnd < 0) { 6995 newSelEnd = Selection.getSelectionEnd(buf); 6996 } 6997 onSelectionChanged(newSelStart, newSelEnd); 6998 } 6999 } 7000 7001 if (what instanceof UpdateAppearance || 7002 what instanceof ParagraphStyle) { 7003 if (ims == null || ims.mBatchEditNesting == 0) { 7004 invalidate(); 7005 mHighlightPathBogus = true; 7006 checkForResize(); 7007 } else { 7008 ims.mContentChanged = true; 7009 } 7010 } 7011 7012 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 7013 mHighlightPathBogus = true; 7014 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 7015 ims.mSelectionModeChanged = true; 7016 } 7017 7018 if (Selection.getSelectionStart(buf) >= 0) { 7019 if (ims == null || ims.mBatchEditNesting == 0) { 7020 invalidateCursor(); 7021 } else { 7022 ims.mCursorChanged = true; 7023 } 7024 } 7025 } 7026 7027 if (what instanceof ParcelableSpan) { 7028 // If this is a span that can be sent to a remote process, 7029 // the current extract editor would be interested in it. 7030 if (ims != null && ims.mExtracting != null) { 7031 if (ims.mBatchEditNesting != 0) { 7032 if (oldStart >= 0) { 7033 if (ims.mChangedStart > oldStart) { 7034 ims.mChangedStart = oldStart; 7035 } 7036 if (ims.mChangedStart > oldEnd) { 7037 ims.mChangedStart = oldEnd; 7038 } 7039 } 7040 if (newStart >= 0) { 7041 if (ims.mChangedStart > newStart) { 7042 ims.mChangedStart = newStart; 7043 } 7044 if (ims.mChangedStart > newEnd) { 7045 ims.mChangedStart = newEnd; 7046 } 7047 } 7048 } else { 7049 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 7050 + oldStart + "-" + oldEnd + "," 7051 + newStart + "-" + newEnd + what); 7052 ims.mContentChanged = true; 7053 } 7054 } 7055 } 7056 } 7057 7058 private class ChangeWatcher 7059 implements TextWatcher, SpanWatcher { 7060 7061 private CharSequence mBeforeText; 7062 7063 public void beforeTextChanged(CharSequence buffer, int start, 7064 int before, int after) { 7065 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 7066 + " before=" + before + " after=" + after + ": " + buffer); 7067 7068 if (AccessibilityManager.getInstance(mContext).isEnabled() 7069 && !isPasswordInputType(mInputType) 7070 && !hasPasswordTransformationMethod()) { 7071 mBeforeText = buffer.toString(); 7072 } 7073 7074 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 7075 } 7076 7077 public void onTextChanged(CharSequence buffer, int start, 7078 int before, int after) { 7079 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 7080 + " before=" + before + " after=" + after + ": " + buffer); 7081 TextView.this.handleTextChanged(buffer, start, before, after); 7082 7083 if (AccessibilityManager.getInstance(mContext).isEnabled() && 7084 (isFocused() || isSelected() && 7085 isShown())) { 7086 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 7087 mBeforeText = null; 7088 } 7089 } 7090 7091 public void afterTextChanged(Editable buffer) { 7092 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 7093 TextView.this.sendAfterTextChanged(buffer); 7094 7095 if (MetaKeyKeyListener.getMetaState(buffer, 7096 MetaKeyKeyListener.META_SELECTING) != 0) { 7097 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 7098 } 7099 } 7100 7101 public void onSpanChanged(Spannable buf, 7102 Object what, int s, int e, int st, int en) { 7103 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 7104 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 7105 TextView.this.spanChange(buf, what, s, st, e, en); 7106 } 7107 7108 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 7109 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 7110 + " what=" + what + ": " + buf); 7111 TextView.this.spanChange(buf, what, -1, s, -1, e); 7112 } 7113 7114 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 7115 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 7116 + " what=" + what + ": " + buf); 7117 TextView.this.spanChange(buf, what, s, -1, e, -1); 7118 } 7119 } 7120 7121 /** 7122 * @hide 7123 */ 7124 @Override 7125 public void dispatchFinishTemporaryDetach() { 7126 mDispatchTemporaryDetach = true; 7127 super.dispatchFinishTemporaryDetach(); 7128 mDispatchTemporaryDetach = false; 7129 } 7130 7131 @Override 7132 public void onStartTemporaryDetach() { 7133 super.onStartTemporaryDetach(); 7134 // Only track when onStartTemporaryDetach() is called directly, 7135 // usually because this instance is an editable field in a list 7136 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 7137 7138 // Because of View recycling in ListView, there is no easy way to know when a TextView with 7139 // selection becomes visible again. Until a better solution is found, stop text selection 7140 // mode (if any) as soon as this TextView is recycled. 7141 stopSelectionActionMode(); 7142 } 7143 7144 @Override 7145 public void onFinishTemporaryDetach() { 7146 super.onFinishTemporaryDetach(); 7147 // Only track when onStartTemporaryDetach() is called directly, 7148 // usually because this instance is an editable field in a list 7149 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 7150 } 7151 7152 @Override 7153 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 7154 if (mTemporaryDetach) { 7155 // If we are temporarily in the detach state, then do nothing. 7156 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7157 return; 7158 } 7159 7160 mShowCursor = SystemClock.uptimeMillis(); 7161 7162 ensureEndedBatchEdit(); 7163 7164 if (focused) { 7165 int selStart = getSelectionStart(); 7166 int selEnd = getSelectionEnd(); 7167 7168 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 7169 // mode for these, unless there was a specific selection already started. 7170 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 7171 selEnd == mText.length(); 7172 mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted; 7173 7174 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 7175 // If a tap was used to give focus to that view, move cursor at tap position. 7176 // Has to be done before onTakeFocus, which can be overloaded. 7177 final int lastTapPosition = getLastTapPosition(); 7178 if (lastTapPosition >= 0) { 7179 Selection.setSelection((Spannable) mText, lastTapPosition); 7180 } 7181 7182 if (mMovement != null) { 7183 mMovement.onTakeFocus(this, (Spannable) mText, direction); 7184 } 7185 7186 // The DecorView does not have focus when the 'Done' ExtractEditText button is 7187 // pressed. Since it is the ViewAncestor's mView, it requests focus before 7188 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 7189 // This special case ensure that we keep current selection in that case. 7190 // It would be better to know why the DecorView does not have focus at that time. 7191 if (((this instanceof ExtractEditText) || mSelectionMoved) && 7192 selStart >= 0 && selEnd >= 0) { 7193 /* 7194 * Someone intentionally set the selection, so let them 7195 * do whatever it is that they wanted to do instead of 7196 * the default on-focus behavior. We reset the selection 7197 * here instead of just skipping the onTakeFocus() call 7198 * because some movement methods do something other than 7199 * just setting the selection in theirs and we still 7200 * need to go through that path. 7201 */ 7202 Selection.setSelection((Spannable) mText, selStart, selEnd); 7203 } 7204 7205 if (mSelectAllOnFocus) { 7206 selectAll(); 7207 } 7208 7209 mTouchFocusSelected = true; 7210 } 7211 7212 mFrozenWithFocus = false; 7213 mSelectionMoved = false; 7214 7215 if (mText instanceof Spannable) { 7216 Spannable sp = (Spannable) mText; 7217 MetaKeyKeyListener.resetMetaState(sp); 7218 } 7219 7220 makeBlink(); 7221 7222 if (mError != null) { 7223 showError(); 7224 } 7225 } else { 7226 if (mError != null) { 7227 hideError(); 7228 } 7229 // Don't leave us in the middle of a batch edit. 7230 onEndBatchEdit(); 7231 7232 if (this instanceof ExtractEditText) { 7233 // terminateTextSelectionMode removes selection, which we want to keep when 7234 // ExtractEditText goes out of focus. 7235 final int selStart = getSelectionStart(); 7236 final int selEnd = getSelectionEnd(); 7237 hideControllers(); 7238 Selection.setSelection((Spannable) mText, selStart, selEnd); 7239 } else { 7240 hideControllers(); 7241 } 7242 7243 // No need to create the controller 7244 if (mSelectionModifierCursorController != null) { 7245 mSelectionModifierCursorController.resetTouchOffsets(); 7246 } 7247 } 7248 7249 startStopMarquee(focused); 7250 7251 if (mTransformation != null) { 7252 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 7253 } 7254 7255 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7256 } 7257 7258 private int getLastTapPosition() { 7259 // No need to create the controller at that point, no last tap position saved 7260 if (mSelectionModifierCursorController != null) { 7261 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 7262 if (lastTapPosition >= 0) { 7263 // Safety check, should not be possible. 7264 if (lastTapPosition > mText.length()) { 7265 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 7266 + mText.length() + ")"); 7267 lastTapPosition = mText.length(); 7268 } 7269 return lastTapPosition; 7270 } 7271 } 7272 7273 return -1; 7274 } 7275 7276 @Override 7277 public void onWindowFocusChanged(boolean hasWindowFocus) { 7278 super.onWindowFocusChanged(hasWindowFocus); 7279 7280 if (hasWindowFocus) { 7281 if (mBlink != null) { 7282 mBlink.uncancel(); 7283 makeBlink(); 7284 } 7285 } else { 7286 if (mBlink != null) { 7287 mBlink.cancel(); 7288 } 7289 // Don't leave us in the middle of a batch edit. 7290 onEndBatchEdit(); 7291 if (mInputContentType != null) { 7292 mInputContentType.enterDown = false; 7293 } 7294 hideControllers(); 7295 removeAllSuggestionSpans(); 7296 } 7297 7298 startStopMarquee(hasWindowFocus); 7299 } 7300 7301 private void removeAllSuggestionSpans() { 7302 if (mText instanceof Editable) { 7303 Editable editable = ((Editable) mText); 7304 SuggestionSpan[] spans = editable.getSpans(0, mText.length(), SuggestionSpan.class); 7305 final int length = spans.length; 7306 for (int i = 0; i < length; i++) { 7307 editable.removeSpan(spans[i]); 7308 } 7309 } 7310 } 7311 7312 @Override 7313 protected void onVisibilityChanged(View changedView, int visibility) { 7314 super.onVisibilityChanged(changedView, visibility); 7315 if (visibility != VISIBLE) { 7316 hideControllers(); 7317 } 7318 } 7319 7320 /** 7321 * Use {@link BaseInputConnection#removeComposingSpans 7322 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 7323 * state from this text view. 7324 */ 7325 public void clearComposingText() { 7326 if (mText instanceof Spannable) { 7327 BaseInputConnection.removeComposingSpans((Spannable)mText); 7328 } 7329 } 7330 7331 @Override 7332 public void setSelected(boolean selected) { 7333 boolean wasSelected = isSelected(); 7334 7335 super.setSelected(selected); 7336 7337 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7338 if (selected) { 7339 startMarquee(); 7340 } else { 7341 stopMarquee(); 7342 } 7343 } 7344 } 7345 7346 @Override 7347 public boolean onTouchEvent(MotionEvent event) { 7348 final int action = event.getActionMasked(); 7349 7350 if (hasInsertionController()) { 7351 getInsertionController().onTouchEvent(event); 7352 } 7353 if (hasSelectionController()) { 7354 getSelectionController().onTouchEvent(event); 7355 } 7356 7357 if (action == MotionEvent.ACTION_DOWN) { 7358 mLastDownPositionX = event.getX(); 7359 mLastDownPositionY = event.getY(); 7360 7361 // Reset this state; it will be re-set if super.onTouchEvent 7362 // causes focus to move to the view. 7363 mTouchFocusSelected = false; 7364 mIgnoreActionUpEvent = false; 7365 } 7366 7367 final boolean superResult = super.onTouchEvent(event); 7368 7369 /* 7370 * Don't handle the release after a long press, because it will 7371 * move the selection away from whatever the menu action was 7372 * trying to affect. 7373 */ 7374 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 7375 mDiscardNextActionUp = false; 7376 return superResult; 7377 } 7378 7379 final boolean touchIsFinished = action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && 7380 isFocused(); 7381 7382 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 7383 && mText instanceof Spannable && mLayout != null) { 7384 boolean handled = false; 7385 7386 if (mMovement != null) { 7387 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 7388 } 7389 7390 if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable && touchIsFinished) { 7391 // The LinkMovementMethod which should handle taps on links has not been installed 7392 // to support text selection. We reproduce its behavior here to open links. 7393 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 7394 getSelectionEnd(), ClickableSpan.class); 7395 7396 if (links.length != 0) { 7397 links[0].onClick(this); 7398 handled = true; 7399 } 7400 } 7401 7402 if ((isTextEditable() || mTextIsSelectable) && touchIsFinished) { 7403 // Show the IME, except when selecting in read-only text. 7404 final InputMethodManager imm = InputMethodManager.peekInstance(); 7405 if (imm != null) { 7406 imm.viewClicked(this); 7407 } 7408 if (!mTextIsSelectable) { 7409 handled |= imm != null && imm.showSoftInput(this, 0); 7410 } 7411 7412 boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect(); 7413 if (!selectAllGotFocus && hasSelection()) { 7414 startSelectionActionMode(); 7415 } else { 7416 stopSelectionActionMode(); 7417 hideSuggestions(); 7418 if (hasInsertionController() && !selectAllGotFocus && mText.length() > 0) { 7419 getInsertionController().show(); 7420 } 7421 } 7422 } 7423 7424 if (handled) { 7425 return true; 7426 } 7427 } 7428 7429 return superResult; 7430 } 7431 7432 @Override 7433 public boolean onGenericMotionEvent(MotionEvent event) { 7434 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 7435 try { 7436 if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { 7437 return true; 7438 } 7439 } catch (AbstractMethodError ex) { 7440 // onGenericMotionEvent was added to the MovementMethod interface in API 12. 7441 // Ignore its absence in case third party applications implemented the 7442 // interface directly. 7443 } 7444 } 7445 return super.onGenericMotionEvent(event); 7446 } 7447 7448 private void prepareCursorControllers() { 7449 boolean windowSupportsHandles = false; 7450 7451 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 7452 if (params instanceof WindowManager.LayoutParams) { 7453 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 7454 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 7455 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 7456 } 7457 7458 mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null; 7459 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 7460 mLayout != null; 7461 7462 if (!mInsertionControllerEnabled) { 7463 hideInsertionPointCursorController(); 7464 if (mInsertionPointCursorController != null) { 7465 mInsertionPointCursorController.onDetached(); 7466 mInsertionPointCursorController = null; 7467 } 7468 } 7469 7470 if (!mSelectionControllerEnabled) { 7471 stopSelectionActionMode(); 7472 if (mSelectionModifierCursorController != null) { 7473 mSelectionModifierCursorController.onDetached(); 7474 mSelectionModifierCursorController = null; 7475 } 7476 } 7477 } 7478 7479 /** 7480 * @return True iff this TextView contains a text that can be edited, or if this is 7481 * a selectable TextView. 7482 */ 7483 private boolean isTextEditable() { 7484 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 7485 } 7486 7487 /** 7488 * Returns true, only while processing a touch gesture, if the initial 7489 * touch down event caused focus to move to the text view and as a result 7490 * its selection changed. Only valid while processing the touch gesture 7491 * of interest. 7492 */ 7493 public boolean didTouchFocusSelect() { 7494 return mTouchFocusSelected; 7495 } 7496 7497 @Override 7498 public void cancelLongPress() { 7499 super.cancelLongPress(); 7500 mIgnoreActionUpEvent = true; 7501 } 7502 7503 @Override 7504 public boolean onTrackballEvent(MotionEvent event) { 7505 if (mMovement != null && mText instanceof Spannable && 7506 mLayout != null) { 7507 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 7508 return true; 7509 } 7510 } 7511 7512 return super.onTrackballEvent(event); 7513 } 7514 7515 public void setScroller(Scroller s) { 7516 mScroller = s; 7517 } 7518 7519 private static class Blink extends Handler implements Runnable { 7520 private final WeakReference<TextView> mView; 7521 private boolean mCancelled; 7522 7523 public Blink(TextView v) { 7524 mView = new WeakReference<TextView>(v); 7525 } 7526 7527 public void run() { 7528 if (mCancelled) { 7529 return; 7530 } 7531 7532 removeCallbacks(Blink.this); 7533 7534 TextView tv = mView.get(); 7535 7536 if (tv != null && tv.shouldBlink()) { 7537 if (tv.mLayout != null) { 7538 tv.invalidateCursorPath(); 7539 } 7540 7541 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 7542 } 7543 } 7544 7545 void cancel() { 7546 if (!mCancelled) { 7547 removeCallbacks(Blink.this); 7548 mCancelled = true; 7549 } 7550 } 7551 7552 void uncancel() { 7553 mCancelled = false; 7554 } 7555 } 7556 7557 /** 7558 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 7559 */ 7560 private boolean shouldBlink() { 7561 if (!isFocused()) return false; 7562 7563 final int start = getSelectionStart(); 7564 if (start < 0) return false; 7565 7566 final int end = getSelectionEnd(); 7567 if (end < 0) return false; 7568 7569 return start == end; 7570 } 7571 7572 private void makeBlink() { 7573 if (isCursorVisible()) { 7574 if (shouldBlink()) { 7575 mShowCursor = SystemClock.uptimeMillis(); 7576 if (mBlink == null) mBlink = new Blink(this); 7577 mBlink.removeCallbacks(mBlink); 7578 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 7579 } 7580 } else { 7581 if (mBlink != null) mBlink.removeCallbacks(mBlink); 7582 } 7583 } 7584 7585 @Override 7586 protected float getLeftFadingEdgeStrength() { 7587 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 7588 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7589 if (mMarquee != null && !mMarquee.isStopped()) { 7590 final Marquee marquee = mMarquee; 7591 if (marquee.shouldDrawLeftFade()) { 7592 return marquee.mScroll / getHorizontalFadingEdgeLength(); 7593 } else { 7594 return 0.0f; 7595 } 7596 } else if (getLineCount() == 1) { 7597 final int layoutDirection = getResolvedLayoutDirection(); 7598 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 7599 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 7600 case Gravity.LEFT: 7601 return 0.0f; 7602 case Gravity.RIGHT: 7603 return (mLayout.getLineRight(0) - (mRight - mLeft) - 7604 getCompoundPaddingLeft() - getCompoundPaddingRight() - 7605 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 7606 case Gravity.CENTER_HORIZONTAL: 7607 return 0.0f; 7608 } 7609 } 7610 } 7611 return super.getLeftFadingEdgeStrength(); 7612 } 7613 7614 @Override 7615 protected float getRightFadingEdgeStrength() { 7616 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 7617 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7618 if (mMarquee != null && !mMarquee.isStopped()) { 7619 final Marquee marquee = mMarquee; 7620 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 7621 } else if (getLineCount() == 1) { 7622 final int layoutDirection = getResolvedLayoutDirection(); 7623 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 7624 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 7625 case Gravity.LEFT: 7626 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 7627 getCompoundPaddingRight(); 7628 final float lineWidth = mLayout.getLineWidth(0); 7629 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 7630 case Gravity.RIGHT: 7631 return 0.0f; 7632 case Gravity.CENTER_HORIZONTAL: 7633 case Gravity.FILL_HORIZONTAL: 7634 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 7635 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 7636 getHorizontalFadingEdgeLength(); 7637 } 7638 } 7639 } 7640 return super.getRightFadingEdgeStrength(); 7641 } 7642 7643 @Override 7644 protected int computeHorizontalScrollRange() { 7645 if (mLayout != null) { 7646 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 7647 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 7648 } 7649 7650 return super.computeHorizontalScrollRange(); 7651 } 7652 7653 @Override 7654 protected int computeVerticalScrollRange() { 7655 if (mLayout != null) 7656 return mLayout.getHeight(); 7657 7658 return super.computeVerticalScrollRange(); 7659 } 7660 7661 @Override 7662 protected int computeVerticalScrollExtent() { 7663 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 7664 } 7665 7666 @Override 7667 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched) { 7668 if (TextUtils.isEmpty(searched)) { 7669 return; 7670 } 7671 CharSequence thisText = getText(); 7672 if (TextUtils.isEmpty(thisText)) { 7673 return; 7674 } 7675 String searchedLowerCase = searched.toString().toLowerCase(); 7676 String thisTextLowerCase = thisText.toString().toLowerCase(); 7677 if (thisTextLowerCase.contains(searchedLowerCase)) { 7678 outViews.add(this); 7679 } 7680 } 7681 7682 public enum BufferType { 7683 NORMAL, SPANNABLE, EDITABLE, 7684 } 7685 7686 /** 7687 * Returns the TextView_textColor attribute from the 7688 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 7689 * from the TextView_textAppearance attribute, if TextView_textColor 7690 * was not set directly. 7691 */ 7692 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 7693 ColorStateList colors; 7694 colors = attrs.getColorStateList(com.android.internal.R.styleable. 7695 TextView_textColor); 7696 7697 if (colors == null) { 7698 int ap = attrs.getResourceId(com.android.internal.R.styleable. 7699 TextView_textAppearance, -1); 7700 if (ap != -1) { 7701 TypedArray appearance; 7702 appearance = context.obtainStyledAttributes(ap, 7703 com.android.internal.R.styleable.TextAppearance); 7704 colors = appearance.getColorStateList(com.android.internal.R.styleable. 7705 TextAppearance_textColor); 7706 appearance.recycle(); 7707 } 7708 } 7709 7710 return colors; 7711 } 7712 7713 /** 7714 * Returns the default color from the TextView_textColor attribute 7715 * from the AttributeSet, if set, or the default color from the 7716 * TextAppearance_textColor from the TextView_textAppearance attribute, 7717 * if TextView_textColor was not set directly. 7718 */ 7719 public static int getTextColor(Context context, 7720 TypedArray attrs, 7721 int def) { 7722 ColorStateList colors = getTextColors(context, attrs); 7723 7724 if (colors == null) { 7725 return def; 7726 } else { 7727 return colors.getDefaultColor(); 7728 } 7729 } 7730 7731 @Override 7732 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 7733 final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; 7734 if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { 7735 switch (keyCode) { 7736 case KeyEvent.KEYCODE_A: 7737 if (canSelectText()) { 7738 return onTextContextMenuItem(ID_SELECT_ALL); 7739 } 7740 break; 7741 case KeyEvent.KEYCODE_X: 7742 if (canCut()) { 7743 return onTextContextMenuItem(ID_CUT); 7744 } 7745 break; 7746 case KeyEvent.KEYCODE_C: 7747 if (canCopy()) { 7748 return onTextContextMenuItem(ID_COPY); 7749 } 7750 break; 7751 case KeyEvent.KEYCODE_V: 7752 if (canPaste()) { 7753 return onTextContextMenuItem(ID_PASTE); 7754 } 7755 break; 7756 } 7757 } 7758 return super.onKeyShortcut(keyCode, event); 7759 } 7760 7761 /** 7762 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 7763 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 7764 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 7765 */ 7766 private boolean canSelectText() { 7767 return hasSelectionController() && mText.length() != 0; 7768 } 7769 7770 /** 7771 * Test based on the <i>intrinsic</i> charateristics of the TextView. 7772 * The text must be spannable and the movement method must allow for arbitary selection. 7773 * 7774 * See also {@link #canSelectText()}. 7775 */ 7776 private boolean textCanBeSelected() { 7777 // prepareCursorController() relies on this method. 7778 // If you change this condition, make sure prepareCursorController is called anywhere 7779 // the value of this condition might be changed. 7780 return mText instanceof Spannable && mMovement != null && mMovement.canSelectArbitrarily(); 7781 } 7782 7783 private boolean canCut() { 7784 if (hasPasswordTransformationMethod()) { 7785 return false; 7786 } 7787 7788 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 7789 return true; 7790 } 7791 7792 return false; 7793 } 7794 7795 private boolean canCopy() { 7796 if (hasPasswordTransformationMethod()) { 7797 return false; 7798 } 7799 7800 if (mText.length() > 0 && hasSelection()) { 7801 return true; 7802 } 7803 7804 return false; 7805 } 7806 7807 private boolean canPaste() { 7808 return (mText instanceof Editable && 7809 mInput != null && 7810 getSelectionStart() >= 0 && 7811 getSelectionEnd() >= 0 && 7812 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 7813 hasPrimaryClip()); 7814 } 7815 7816 private static long packRangeInLong(int start, int end) { 7817 return (((long) start) << 32) | end; 7818 } 7819 7820 private static int extractRangeStartFromLong(long range) { 7821 return (int) (range >>> 32); 7822 } 7823 7824 private static int extractRangeEndFromLong(long range) { 7825 return (int) (range & 0x00000000FFFFFFFFL); 7826 } 7827 7828 private boolean selectAll() { 7829 final int length = mText.length(); 7830 Selection.setSelection((Spannable) mText, 0, length); 7831 return length > 0; 7832 } 7833 7834 /** 7835 * Adjusts selection to the word under last touch offset. 7836 * Return true if the operation was successfully performed. 7837 */ 7838 private boolean selectCurrentWord() { 7839 if (!canSelectText()) { 7840 return false; 7841 } 7842 7843 if (hasPasswordTransformationMethod()) { 7844 // Always select all on a password field. 7845 // Cut/copy menu entries are not available for passwords, but being able to select all 7846 // is however useful to delete or paste to replace the entire content. 7847 return selectAll(); 7848 } 7849 7850 int klass = mInputType & InputType.TYPE_MASK_CLASS; 7851 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 7852 7853 // Specific text field types: select the entire text for these 7854 if (klass == InputType.TYPE_CLASS_NUMBER || 7855 klass == InputType.TYPE_CLASS_PHONE || 7856 klass == InputType.TYPE_CLASS_DATETIME || 7857 variation == InputType.TYPE_TEXT_VARIATION_URI || 7858 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 7859 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 7860 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 7861 return selectAll(); 7862 } 7863 7864 long lastTouchOffsets = getLastTouchOffsets(); 7865 final int minOffset = extractRangeStartFromLong(lastTouchOffsets); 7866 final int maxOffset = extractRangeEndFromLong(lastTouchOffsets); 7867 7868 int selectionStart, selectionEnd; 7869 7870 // If a URLSpan (web address, email, phone...) is found at that position, select it. 7871 URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class); 7872 if (urlSpans.length == 1) { 7873 URLSpan url = urlSpans[0]; 7874 selectionStart = ((Spanned) mText).getSpanStart(url); 7875 selectionEnd = ((Spanned) mText).getSpanEnd(url); 7876 } else { 7877 if (mWordIterator == null) { 7878 mWordIterator = new WordIterator(); 7879 } 7880 // WordIerator handles text changes, this is a no-op if text in unchanged. 7881 mWordIterator.setCharSequence(mText); 7882 7883 selectionStart = mWordIterator.getBeginning(minOffset); 7884 if (selectionStart == BreakIterator.DONE) return false; 7885 7886 selectionEnd = mWordIterator.getEnd(maxOffset); 7887 if (selectionEnd == BreakIterator.DONE) return false; 7888 } 7889 7890 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 7891 return true; 7892 } 7893 7894 private long getLastTouchOffsets() { 7895 int minOffset, maxOffset; 7896 7897 if (mContextMenuTriggeredByKey) { 7898 minOffset = getSelectionStart(); 7899 maxOffset = getSelectionEnd(); 7900 } else { 7901 SelectionModifierCursorController selectionController = getSelectionController(); 7902 minOffset = selectionController.getMinTouchOffset(); 7903 maxOffset = selectionController.getMaxTouchOffset(); 7904 } 7905 7906 return packRangeInLong(minOffset, maxOffset); 7907 } 7908 7909 @Override 7910 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 7911 super.onPopulateAccessibilityEvent(event); 7912 7913 final boolean isPassword = hasPasswordTransformationMethod(); 7914 if (!isPassword) { 7915 CharSequence text = getText(); 7916 if (TextUtils.isEmpty(text)) { 7917 text = getHint(); 7918 } 7919 if (!TextUtils.isEmpty(text)) { 7920 event.getText().add(text); 7921 } 7922 } 7923 } 7924 7925 @Override 7926 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 7927 super.onInitializeAccessibilityEvent(event); 7928 7929 final boolean isPassword = hasPasswordTransformationMethod(); 7930 event.setPassword(isPassword); 7931 7932 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { 7933 event.setFromIndex(Selection.getSelectionStart(mText)); 7934 event.setToIndex(Selection.getSelectionEnd(mText)); 7935 event.setItemCount(mText.length()); 7936 } 7937 } 7938 7939 @Override 7940 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 7941 super.onInitializeAccessibilityNodeInfo(info); 7942 7943 final boolean isPassword = hasPasswordTransformationMethod(); 7944 if (!isPassword) { 7945 info.setText(getText()); 7946 } 7947 info.setPassword(isPassword); 7948 } 7949 7950 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 7951 int fromIndex, int removedCount, int addedCount) { 7952 AccessibilityEvent event = 7953 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 7954 event.setFromIndex(fromIndex); 7955 event.setRemovedCount(removedCount); 7956 event.setAddedCount(addedCount); 7957 event.setBeforeText(beforeText); 7958 sendAccessibilityEventUnchecked(event); 7959 } 7960 7961 @Override 7962 protected void onCreateContextMenu(ContextMenu menu) { 7963 super.onCreateContextMenu(menu); 7964 boolean added = false; 7965 mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown; 7966 // Problem with context menu on long press: the menu appears while the key in down and when 7967 // the key is released, the view does not receive the key_up event. 7968 // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up 7969 // events. We cannot simply clear these flags in onTextContextMenuItem since 7970 // it may not be called (if the user/ discards the context menu with the back key). 7971 // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is 7972 // available in onTextContextMenuItem. 7973 mDPadCenterIsDown = mEnterKeyIsDown = false; 7974 7975 MenuHandler handler = new MenuHandler(); 7976 7977 if (mText instanceof Spanned && hasSelectionController()) { 7978 long lastTouchOffset = getLastTouchOffsets(); 7979 final int selStart = extractRangeStartFromLong(lastTouchOffset); 7980 final int selEnd = extractRangeEndFromLong(lastTouchOffset); 7981 7982 URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class); 7983 if (urls.length > 0) { 7984 menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl). 7985 setOnMenuItemClickListener(handler); 7986 7987 added = true; 7988 } 7989 } 7990 7991 // The context menu is not empty, which will prevent the selection mode from starting. 7992 // Add a entry to start it in the context menu. 7993 // TODO Does not handle the case where a subclass does not call super.thisMethod or 7994 // populates the menu AFTER this call. 7995 if (menu.size() > 0) { 7996 menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode). 7997 setOnMenuItemClickListener(handler); 7998 added = true; 7999 } 8000 8001 if (added) { 8002 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 8003 } 8004 } 8005 8006 /** 8007 * Returns whether this text view is a current input method target. The 8008 * default implementation just checks with {@link InputMethodManager}. 8009 */ 8010 public boolean isInputMethodTarget() { 8011 InputMethodManager imm = InputMethodManager.peekInstance(); 8012 return imm != null && imm.isActive(this); 8013 } 8014 8015 // Selection context mode 8016 private static final int ID_SELECT_ALL = android.R.id.selectAll; 8017 private static final int ID_CUT = android.R.id.cut; 8018 private static final int ID_COPY = android.R.id.copy; 8019 private static final int ID_PASTE = android.R.id.paste; 8020 // Context menu entries 8021 private static final int ID_COPY_URL = android.R.id.copyUrl; 8022 private static final int ID_SELECTION_MODE = android.R.id.selectTextMode; 8023 8024 private class MenuHandler implements MenuItem.OnMenuItemClickListener { 8025 public boolean onMenuItemClick(MenuItem item) { 8026 return onTextContextMenuItem(item.getItemId()); 8027 } 8028 } 8029 8030 /** 8031 * Called when a context menu option for the text view is selected. Currently 8032 * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode}, 8033 * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut} 8034 * or {@link android.R.id#copy}. 8035 * 8036 * @return true if the context menu item action was performed. 8037 */ 8038 public boolean onTextContextMenuItem(int id) { 8039 int min = 0; 8040 int max = mText.length(); 8041 8042 if (isFocused()) { 8043 final int selStart = getSelectionStart(); 8044 final int selEnd = getSelectionEnd(); 8045 8046 min = Math.max(0, Math.min(selStart, selEnd)); 8047 max = Math.max(0, Math.max(selStart, selEnd)); 8048 } 8049 8050 switch (id) { 8051 case ID_COPY_URL: 8052 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class); 8053 if (urls.length >= 1) { 8054 ClipData clip = null; 8055 for (int i=0; i<urls.length; i++) { 8056 Uri uri = Uri.parse(urls[0].getURL()); 8057 if (clip == null) { 8058 clip = ClipData.newRawUri(null, uri); 8059 } else { 8060 clip.addItem(new ClipData.Item(uri)); 8061 } 8062 } 8063 if (clip != null) { 8064 setPrimaryClip(clip); 8065 } 8066 } 8067 stopSelectionActionMode(); 8068 return true; 8069 8070 case ID_SELECTION_MODE: 8071 if (mSelectionActionMode != null) { 8072 // Selection mode is already started, simply change selected part. 8073 selectCurrentWord(); 8074 } else { 8075 startSelectionActionMode(); 8076 } 8077 return true; 8078 8079 case ID_SELECT_ALL: 8080 // This does not enter text selection mode. Text is highlighted, so that it can be 8081 // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. 8082 selectAll(); 8083 return true; 8084 8085 case ID_PASTE: 8086 paste(min, max); 8087 return true; 8088 8089 case ID_CUT: 8090 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8091 ((Editable) mText).delete(min, max); 8092 stopSelectionActionMode(); 8093 return true; 8094 8095 case ID_COPY: 8096 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8097 stopSelectionActionMode(); 8098 return true; 8099 } 8100 return false; 8101 } 8102 8103 /** 8104 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 8105 * by [min, max] when replacing this region by paste. 8106 * Note that if there were two spaces (or more) at that position before, they are kept. We just 8107 * make sure we do not add an extra one from the paste content. 8108 */ 8109 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 8110 if (paste.length() > 0) { 8111 if (min > 0) { 8112 final char charBefore = mTransformed.charAt(min - 1); 8113 final char charAfter = paste.charAt(0); 8114 8115 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8116 // Two spaces at beginning of paste: remove one 8117 final int originalLength = mText.length(); 8118 ((Editable) mText).delete(min - 1, min); 8119 // Due to filters, there is no guarantee that exactly one character was 8120 // removed: count instead. 8121 final int delta = mText.length() - originalLength; 8122 min += delta; 8123 max += delta; 8124 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8125 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8126 // No space at beginning of paste: add one 8127 final int originalLength = mText.length(); 8128 ((Editable) mText).replace(min, min, " "); 8129 // Taking possible filters into account as above. 8130 final int delta = mText.length() - originalLength; 8131 min += delta; 8132 max += delta; 8133 } 8134 } 8135 8136 if (max < mText.length()) { 8137 final char charBefore = paste.charAt(paste.length() - 1); 8138 final char charAfter = mTransformed.charAt(max); 8139 8140 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8141 // Two spaces at end of paste: remove one 8142 ((Editable) mText).delete(max, max + 1); 8143 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8144 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8145 // No space at end of paste: add one 8146 ((Editable) mText).replace(max, max, " "); 8147 } 8148 } 8149 } 8150 8151 return packRangeInLong(min, max); 8152 } 8153 8154 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 8155 TextView shadowView = (TextView) inflate(mContext, 8156 com.android.internal.R.layout.text_drag_thumbnail, null); 8157 8158 if (shadowView == null) { 8159 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 8160 } 8161 8162 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 8163 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 8164 } 8165 shadowView.setText(text); 8166 shadowView.setTextColor(getTextColors()); 8167 8168 shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 8169 shadowView.setGravity(Gravity.CENTER); 8170 8171 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8172 ViewGroup.LayoutParams.WRAP_CONTENT)); 8173 8174 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8175 shadowView.measure(size, size); 8176 8177 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 8178 shadowView.invalidate(); 8179 return new DragShadowBuilder(shadowView); 8180 } 8181 8182 private static class DragLocalState { 8183 public TextView sourceTextView; 8184 public int start, end; 8185 8186 public DragLocalState(TextView sourceTextView, int start, int end) { 8187 this.sourceTextView = sourceTextView; 8188 this.start = start; 8189 this.end = end; 8190 } 8191 } 8192 8193 @Override 8194 public boolean performLongClick() { 8195 if (super.performLongClick()) { 8196 mDiscardNextActionUp = true; 8197 return true; 8198 } 8199 8200 boolean handled = false; 8201 8202 // Long press in empty space moves cursor and shows the Paste affordance if available. 8203 if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 8204 mInsertionControllerEnabled) { 8205 final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY); 8206 stopSelectionActionMode(); 8207 Selection.setSelection((Spannable) mText, offset); 8208 getInsertionController().showWithPaste(); 8209 handled = true; 8210 } 8211 8212 if (!handled && mSelectionActionMode != null) { 8213 if (touchPositionIsInSelection()) { 8214 // Start a drag 8215 final int start = getSelectionStart(); 8216 final int end = getSelectionEnd(); 8217 CharSequence selectedText = mTransformed.subSequence(start, end); 8218 ClipData data = ClipData.newPlainText(null, selectedText); 8219 DragLocalState localState = new DragLocalState(this, start, end); 8220 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 8221 stopSelectionActionMode(); 8222 } else { 8223 selectCurrentWord(); 8224 } 8225 handled = true; 8226 } 8227 8228 // Start a new selection 8229 handled |= !handled && startSelectionActionMode(); 8230 8231 if (handled) { 8232 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 8233 mDiscardNextActionUp = true; 8234 } 8235 8236 return handled; 8237 } 8238 8239 private boolean touchPositionIsInSelection() { 8240 int selectionStart = getSelectionStart(); 8241 int selectionEnd = getSelectionEnd(); 8242 8243 if (selectionStart == selectionEnd) { 8244 return false; 8245 } 8246 8247 if (selectionStart > selectionEnd) { 8248 int tmp = selectionStart; 8249 selectionStart = selectionEnd; 8250 selectionEnd = tmp; 8251 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8252 } 8253 8254 SelectionModifierCursorController selectionController = getSelectionController(); 8255 int minOffset = selectionController.getMinTouchOffset(); 8256 int maxOffset = selectionController.getMaxTouchOffset(); 8257 8258 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 8259 } 8260 8261 private static class SuggestionRangeSpan extends UnderlineSpan { 8262 // TODO themable, would be nice to make it a child class of TextAppearanceSpan, but 8263 // there is no way to have underline and TextAppearanceSpan. 8264 } 8265 8266 private class SuggestionsPopupWindow implements OnClickListener { 8267 private static final int MAX_NUMBER_SUGGESTIONS = 5; 8268 private static final int NO_SUGGESTIONS = -1; 8269 private final PopupWindow mContainer; 8270 private final ViewGroup[] mSuggestionViews = new ViewGroup[2]; 8271 private final int[] mSuggestionViewLayouts = new int[] { 8272 mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout}; 8273 private WordIterator mSuggestionWordIterator; 8274 private TextAppearanceSpan[] mHighlightSpans = new TextAppearanceSpan[0]; 8275 8276 public SuggestionsPopupWindow() { 8277 mContainer = new PopupWindow(TextView.this.mContext, null, 8278 com.android.internal.R.attr.textSuggestionsWindowStyle); 8279 mContainer.setSplitTouchEnabled(true); 8280 mContainer.setClippingEnabled(false); 8281 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8282 8283 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 8284 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 8285 } 8286 8287 private class SuggestionInfo { 8288 int suggestionStart, suggestionEnd; // range of suggestion item with replacement text 8289 int spanStart, spanEnd; // range in TextView where text should be inserted 8290 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 8291 int suggestionIndex; // the index of the suggestion inside suggestionSpan 8292 } 8293 8294 private ViewGroup getViewGroup(boolean under) { 8295 final int viewIndex = under ? 0 : 1; 8296 ViewGroup viewGroup = mSuggestionViews[viewIndex]; 8297 8298 if (viewGroup == null) { 8299 final int layout = mSuggestionViewLayouts[viewIndex]; 8300 LayoutInflater inflater = (LayoutInflater) TextView.this.mContext. 8301 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 8302 8303 if (inflater == null) { 8304 throw new IllegalArgumentException( 8305 "Unable to create TextEdit suggestion window inflater"); 8306 } 8307 8308 View view = inflater.inflate(layout, null); 8309 8310 if (! (view instanceof ViewGroup)) { 8311 throw new IllegalArgumentException( 8312 "Inflated TextEdit suggestion window is not a ViewGroup: " + view); 8313 } 8314 8315 viewGroup = (ViewGroup) view; 8316 8317 // Inflate the suggestion items once and for all. 8318 for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { 8319 View childView = inflater.inflate(mTextEditSuggestionItemLayout, viewGroup, 8320 false); 8321 8322 if (! (childView instanceof TextView)) { 8323 throw new IllegalArgumentException( 8324 "Inflated TextEdit suggestion item is not a TextView: " + childView); 8325 } 8326 8327 childView.setTag(new SuggestionInfo()); 8328 viewGroup.addView(childView); 8329 childView.setOnClickListener(this); 8330 } 8331 8332 mSuggestionViews[viewIndex] = viewGroup; 8333 } 8334 8335 return viewGroup; 8336 } 8337 8338 public void show() { 8339 if (!(mText instanceof Editable)) return; 8340 8341 final int pos = TextView.this.getSelectionStart(); 8342 Spannable spannable = (Spannable)TextView.this.mText; 8343 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 8344 final int nbSpans = suggestionSpans.length; 8345 8346 ViewGroup viewGroup = getViewGroup(true); 8347 mContainer.setContentView(viewGroup); 8348 8349 int totalNbSuggestions = 0; 8350 int spanUnionStart = mText.length(); 8351 int spanUnionEnd = 0; 8352 8353 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 8354 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 8355 final int spanStart = spannable.getSpanStart(suggestionSpan); 8356 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 8357 spanUnionStart = Math.min(spanStart, spanUnionStart); 8358 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 8359 8360 String[] suggestions = suggestionSpan.getSuggestions(); 8361 int nbSuggestions = suggestions.length; 8362 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 8363 TextView textView = (TextView) viewGroup.getChildAt(totalNbSuggestions); 8364 textView.setText(suggestions[suggestionIndex]); 8365 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8366 suggestionInfo.spanStart = spanStart; 8367 suggestionInfo.spanEnd = spanEnd; 8368 suggestionInfo.suggestionSpan = suggestionSpan; 8369 suggestionInfo.suggestionIndex = suggestionIndex; 8370 8371 totalNbSuggestions++; 8372 if (totalNbSuggestions == MAX_NUMBER_SUGGESTIONS) { 8373 // Also end outer for loop 8374 spanIndex = nbSpans; 8375 break; 8376 } 8377 } 8378 } 8379 8380 if (totalNbSuggestions == 0) { 8381 // TODO Replace by final text, use a dedicated layout, add a fade out timer... 8382 TextView textView = (TextView) viewGroup.getChildAt(0); 8383 textView.setText("No suggestions available"); 8384 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8385 suggestionInfo.spanStart = NO_SUGGESTIONS; 8386 totalNbSuggestions++; 8387 } else { 8388 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 8389 ((Editable) mText).setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 8390 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8391 8392 for (int i = 0; i < totalNbSuggestions; i++) { 8393 final TextView textView = (TextView) viewGroup.getChildAt(i); 8394 highlightTextDifferences(textView, spanUnionStart, spanUnionEnd); 8395 } 8396 } 8397 8398 for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { 8399 viewGroup.getChildAt(i).setVisibility(i < totalNbSuggestions ? VISIBLE : GONE); 8400 } 8401 8402 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8403 viewGroup.measure(size, size); 8404 8405 positionAtCursor(); 8406 } 8407 8408 private long[] getWordLimits(CharSequence text) { 8409 // TODO locale for mSuggestionWordIterator 8410 if (mSuggestionWordIterator == null) mSuggestionWordIterator = new WordIterator(); 8411 mSuggestionWordIterator.setCharSequence(text); 8412 8413 // First pass will simply count the number of words to be able to create an array 8414 // Not too expensive since previous break positions are cached by the BreakIterator 8415 int nbWords = 0; 8416 int position = mSuggestionWordIterator.following(0); 8417 while (position != BreakIterator.DONE) { 8418 nbWords++; 8419 position = mSuggestionWordIterator.following(position); 8420 } 8421 8422 int index = 0; 8423 long[] result = new long[nbWords]; 8424 8425 position = mSuggestionWordIterator.following(0); 8426 while (position != BreakIterator.DONE) { 8427 int wordStart = mSuggestionWordIterator.getBeginning(position); 8428 result[index++] = packRangeInLong(wordStart, position); 8429 position = mSuggestionWordIterator.following(position); 8430 } 8431 8432 return result; 8433 } 8434 8435 private TextAppearanceSpan highlightSpan(int index) { 8436 final int length = mHighlightSpans.length; 8437 if (index < length) { 8438 return mHighlightSpans[index]; 8439 } 8440 8441 // Assumes indexes are requested in sequence: simply append one more item 8442 TextAppearanceSpan[] newArray = new TextAppearanceSpan[length + 1]; 8443 System.arraycopy(mHighlightSpans, 0, newArray, 0, length); 8444 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext, 8445 android.R.style.TextAppearance_SuggestionHighlight); 8446 newArray[length] = highlightSpan; 8447 mHighlightSpans = newArray; 8448 return highlightSpan; 8449 } 8450 8451 private void highlightTextDifferences(TextView textView, int unionStart, int unionEnd) { 8452 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8453 final int spanStart = suggestionInfo.spanStart; 8454 final int spanEnd = suggestionInfo.spanEnd; 8455 8456 // Remove all text formating by converting to Strings 8457 final String text = textView.getText().toString(); 8458 final String sourceText = mText.subSequence(spanStart, spanEnd).toString(); 8459 8460 long[] sourceWordLimits = getWordLimits(sourceText); 8461 long[] wordLimits = getWordLimits(text); 8462 8463 SpannableStringBuilder ssb = new SpannableStringBuilder(); 8464 // span [spanStart, spanEnd] is included in union [spanUnionStart, int spanUnionEnd] 8465 // The final result is made of 3 parts: the text before, between and after the span 8466 // This is the text before, provided for context 8467 ssb.append(mText.subSequence(unionStart, spanStart).toString()); 8468 8469 // shift is used to offset spans positions wrt span's beginning 8470 final int shift = spanStart - unionStart; 8471 suggestionInfo.suggestionStart = shift; 8472 suggestionInfo.suggestionEnd = shift + text.length(); 8473 8474 // This is the actual suggestion text, which will be highlighted by the following code 8475 ssb.append(text); 8476 8477 String[] words = new String[wordLimits.length]; 8478 for (int i = 0; i < wordLimits.length; i++) { 8479 int wordStart = extractRangeStartFromLong(wordLimits[i]); 8480 int wordEnd = extractRangeEndFromLong(wordLimits[i]); 8481 words[i] = text.substring(wordStart, wordEnd); 8482 } 8483 8484 // Highlighted word algorithm is based on word matching between source and text 8485 // Matching words are found from left to right. TODO: change for RTL languages 8486 // Characters between matching words are highlighted 8487 int previousCommonWordIndex = -1; 8488 int nbHighlightSpans = 0; 8489 for (int i = 0; i < sourceWordLimits.length; i++) { 8490 int wordStart = extractRangeStartFromLong(sourceWordLimits[i]); 8491 int wordEnd = extractRangeEndFromLong(sourceWordLimits[i]); 8492 String sourceWord = sourceText.substring(wordStart, wordEnd); 8493 8494 for (int j = previousCommonWordIndex + 1; j < words.length; j++) { 8495 if (sourceWord.equals(words[j])) { 8496 if (j != previousCommonWordIndex + 1) { 8497 int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 : 8498 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 8499 int lastDifferentPosition = extractRangeStartFromLong(wordLimits[j]); 8500 ssb.setSpan(highlightSpan(nbHighlightSpans++), 8501 shift + firstDifferentPosition, shift + lastDifferentPosition, 8502 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8503 } else { 8504 // Compare characters between words 8505 int previousSourceWordEnd = i == 0 ? 0 : 8506 extractRangeEndFromLong(sourceWordLimits[i - 1]); 8507 int sourceWordStart = extractRangeStartFromLong(sourceWordLimits[i]); 8508 String sourceSpaces = sourceText.substring(previousSourceWordEnd, 8509 sourceWordStart); 8510 8511 int previousWordEnd = j == 0 ? 0 : 8512 extractRangeEndFromLong(wordLimits[j - 1]); 8513 int currentWordStart = extractRangeStartFromLong(wordLimits[j]); 8514 String textSpaces = text.substring(previousWordEnd, currentWordStart); 8515 8516 if (!sourceSpaces.equals(textSpaces)) { 8517 ssb.setSpan(highlightSpan(nbHighlightSpans++), 8518 shift + previousWordEnd, shift + currentWordStart, 8519 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8520 } 8521 } 8522 previousCommonWordIndex = j; 8523 break; 8524 } 8525 } 8526 } 8527 8528 // Finally, compare ends of Strings 8529 if (previousCommonWordIndex < words.length - 1) { 8530 int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 : 8531 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 8532 int lastDifferentPosition = textView.length(); 8533 ssb.setSpan(highlightSpan(nbHighlightSpans++), 8534 shift + firstDifferentPosition, shift + lastDifferentPosition, 8535 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8536 } else { 8537 int lastSourceWordEnd = sourceWordLimits.length == 0 ? 0 : 8538 extractRangeEndFromLong(sourceWordLimits[sourceWordLimits.length - 1]); 8539 String sourceSpaces = sourceText.substring(lastSourceWordEnd, sourceText.length()); 8540 8541 int lastCommonTextWordEnd = previousCommonWordIndex < 0 ? 0 : 8542 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 8543 String textSpaces = text.substring(lastCommonTextWordEnd, textView.length()); 8544 8545 if (!sourceSpaces.equals(textSpaces) && textSpaces.length() > 0) { 8546 ssb.setSpan(highlightSpan(nbHighlightSpans++), 8547 shift + lastCommonTextWordEnd, shift + textView.length(), 8548 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8549 } 8550 } 8551 8552 // Final part, text after the current suggestion range. 8553 ssb.append(mText.subSequence(spanEnd, unionEnd).toString()); 8554 textView.setText(ssb); 8555 } 8556 8557 public void hide() { 8558 if ((mText instanceof Editable) && mSuggestionRangeSpan != null) { 8559 ((Editable) mText).removeSpan(mSuggestionRangeSpan); 8560 } 8561 mContainer.dismiss(); 8562 } 8563 8564 @Override 8565 public void onClick(View view) { 8566 if (view instanceof TextView) { 8567 TextView textView = (TextView) view; 8568 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8569 final int spanStart = suggestionInfo.spanStart; 8570 final int spanEnd = suggestionInfo.spanEnd; 8571 if (spanStart != NO_SUGGESTIONS) { 8572 // SuggestionSpans are removed by replace: save them before 8573 Editable editable = ((Editable) mText); 8574 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 8575 SuggestionSpan.class); 8576 final int length = suggestionSpans.length; 8577 int[] suggestionSpansStarts = new int[length]; 8578 int[] suggestionSpansEnds = new int[length]; 8579 int[] suggestionSpansFlags = new int[length]; 8580 for (int i = 0; i < length; i++) { 8581 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 8582 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 8583 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 8584 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 8585 } 8586 8587 final int suggestionStart = suggestionInfo.suggestionStart; 8588 final int suggestionEnd = suggestionInfo.suggestionEnd; 8589 final String suggestion = textView.getText().subSequence( 8590 suggestionStart, suggestionEnd).toString(); 8591 final String originalText = mText.subSequence(spanStart, spanEnd).toString(); 8592 ((Editable) mText).replace(spanStart, spanEnd, suggestion); 8593 8594 // Notify source IME of the suggestion pick. Do this before swaping texts. 8595 if (!TextUtils.isEmpty( 8596 suggestionInfo.suggestionSpan.getNotificationTargetClassName())) { 8597 InputMethodManager imm = InputMethodManager.peekInstance(); 8598 imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText, 8599 suggestionInfo.suggestionIndex); 8600 } 8601 8602 // Swap text content between actual text and Suggestion span 8603 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 8604 suggestions[suggestionInfo.suggestionIndex] = originalText; 8605 8606 // Restore previous SuggestionSpans 8607 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 8608 for (int i = 0; i < length; i++) { 8609 // Only spans that include the modified region make sense after replacement 8610 // Spans partially included in the replaced region are removed, there is no 8611 // way to assign them a valid range after replacement 8612 if (suggestionSpansStarts[i] <= spanStart && 8613 suggestionSpansEnds[i] >= spanEnd) { 8614 editable.setSpan(suggestionSpans[i], suggestionSpansStarts[i], 8615 suggestionSpansEnds[i] + lengthDifference, 8616 suggestionSpansFlags[i]); 8617 } 8618 } 8619 } 8620 } 8621 hide(); 8622 } 8623 8624 void positionAtCursor() { 8625 View contentView = mContainer.getContentView(); 8626 int width = contentView.getMeasuredWidth(); 8627 int height = contentView.getMeasuredHeight(); 8628 final int offset = TextView.this.getSelectionStart(); 8629 final int line = mLayout.getLineForOffset(offset); 8630 final int lineBottom = mLayout.getLineBottom(line); 8631 float primaryHorizontal = mLayout.getPrimaryHorizontal(offset); 8632 8633 final Rect bounds = sCursorControllerTempRect; 8634 bounds.left = (int) (primaryHorizontal - width / 2.0f); 8635 bounds.top = lineBottom; 8636 8637 bounds.right = bounds.left + width; 8638 bounds.bottom = bounds.top + height; 8639 8640 convertFromViewportToContentCoordinates(bounds); 8641 8642 final int[] coords = mTempCoords; 8643 TextView.this.getLocationInWindow(coords); 8644 coords[0] += bounds.left; 8645 coords[1] += bounds.top; 8646 8647 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 8648 final int screenHeight = displayMetrics.heightPixels; 8649 8650 // Vertical clipping 8651 if (coords[1] + height > screenHeight) { 8652 // Try to position above current line instead 8653 // TODO use top layout instead, reverse suggestion order, 8654 // try full screen vertical down if it still does not fit. TBD with designers. 8655 8656 // Update dimensions from new view 8657 contentView = mContainer.getContentView(); 8658 width = contentView.getMeasuredWidth(); 8659 height = contentView.getMeasuredHeight(); 8660 8661 final int lineTop = mLayout.getLineTop(line); 8662 final int lineHeight = lineBottom - lineTop; 8663 coords[1] -= height + lineHeight; 8664 } 8665 8666 // Horizontal clipping 8667 coords[0] = Math.max(0, coords[0]); 8668 coords[0] = Math.min(displayMetrics.widthPixels - width, coords[0]); 8669 8670 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); 8671 } 8672 } 8673 8674 void showSuggestions() { 8675 if (!mSuggestionsEnabled || !isTextEditable()) return; 8676 8677 if (mSuggestionsPopupWindow == null) { 8678 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 8679 } 8680 hideControllers(); 8681 mSuggestionsPopupWindow.show(); 8682 } 8683 8684 void hideSuggestions() { 8685 if (mSuggestionsPopupWindow != null) { 8686 mSuggestionsPopupWindow.hide(); 8687 } 8688 } 8689 8690 /** 8691 * Some parts of the text can have alternate suggestion text attached. This is typically done by 8692 * the IME by adding {@link SuggestionSpan}s to the text. 8693 * 8694 * When suggestions are enabled (default), this list of suggestions will be displayed when the 8695 * user double taps on these parts of the text. No suggestions are displayed when this value is 8696 * false. Use {@link #setSuggestionsEnabled(boolean)} to change this value. 8697 * 8698 * @return true if the suggestions popup window is enabled. 8699 * 8700 * @attr ref android.R.styleable#TextView_suggestionsEnabled 8701 */ 8702 public boolean isSuggestionsEnabled() { 8703 return mSuggestionsEnabled; 8704 } 8705 8706 /** 8707 * Enables or disables the suggestion popup. See {@link #isSuggestionsEnabled()}. 8708 * 8709 * @param enabled Whether or not suggestions are enabled. 8710 */ 8711 public void setSuggestionsEnabled(boolean enabled) { 8712 mSuggestionsEnabled = enabled; 8713 } 8714 8715 /** 8716 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 8717 * selection is initiated in this View. 8718 * 8719 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 8720 * Paste actions, depending on what this View supports. 8721 * 8722 * A custom implementation can add new entries in the default menu in its 8723 * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions 8724 * can also be removed from the menu using {@link Menu#removeItem(int)} and passing 8725 * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or 8726 * {@link android.R.id#paste} ids as parameters. 8727 * 8728 * Returning false from {@link ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will 8729 * prevent the action mode from being started. 8730 * 8731 * Action click events should be handled by the custom implementation of 8732 * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 8733 * 8734 * Note that text selection mode is not started when a TextView receives focus and the 8735 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 8736 * that case, to allow for quick replacement. 8737 */ 8738 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 8739 mCustomSelectionActionModeCallback = actionModeCallback; 8740 } 8741 8742 /** 8743 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 8744 * 8745 * @return The current custom selection callback. 8746 */ 8747 public ActionMode.Callback getCustomSelectionActionModeCallback() { 8748 return mCustomSelectionActionModeCallback; 8749 } 8750 8751 /** 8752 * 8753 * @return true if the selection mode was actually started. 8754 */ 8755 private boolean startSelectionActionMode() { 8756 if (mSelectionActionMode != null) { 8757 // Selection action mode is already started 8758 return false; 8759 } 8760 8761 if (!canSelectText() || !requestFocus()) { 8762 Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled."); 8763 return false; 8764 } 8765 8766 if (!hasSelection()) { 8767 // There may already be a selection on device rotation 8768 boolean currentWordSelected = selectCurrentWord(); 8769 if (!currentWordSelected) { 8770 // No word found under cursor or text selection not permitted. 8771 return false; 8772 } 8773 } 8774 8775 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 8776 mSelectionActionMode = startActionMode(actionModeCallback); 8777 final boolean selectionStarted = mSelectionActionMode != null; 8778 8779 if (selectionStarted && !mTextIsSelectable) { 8780 // Show the IME to be able to replace text, except when selecting non editable text. 8781 final InputMethodManager imm = InputMethodManager.peekInstance(); 8782 if (imm != null) imm.showSoftInput(this, 0, null); 8783 } 8784 8785 return selectionStarted; 8786 } 8787 8788 private void stopSelectionActionMode() { 8789 if (mSelectionActionMode != null) { 8790 // This will hide the mSelectionModifierCursorController 8791 mSelectionActionMode.finish(); 8792 } 8793 } 8794 8795 /** 8796 * Paste clipboard content between min and max positions. 8797 */ 8798 private void paste(int min, int max) { 8799 ClipboardManager clipboard = 8800 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 8801 ClipData clip = clipboard.getPrimaryClip(); 8802 if (clip != null) { 8803 boolean didFirst = false; 8804 for (int i=0; i<clip.getItemCount(); i++) { 8805 CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); 8806 if (paste != null) { 8807 if (!didFirst) { 8808 long minMax = prepareSpacesAroundPaste(min, max, paste); 8809 min = extractRangeStartFromLong(minMax); 8810 max = extractRangeEndFromLong(minMax); 8811 Selection.setSelection((Spannable) mText, max); 8812 ((Editable) mText).replace(min, max, paste); 8813 didFirst = true; 8814 } else { 8815 ((Editable) mText).insert(getSelectionEnd(), "\n"); 8816 ((Editable) mText).insert(getSelectionEnd(), paste); 8817 } 8818 } 8819 } 8820 stopSelectionActionMode(); 8821 sLastCutOrCopyTime = 0; 8822 } 8823 } 8824 8825 private void setPrimaryClip(ClipData clip) { 8826 ClipboardManager clipboard = (ClipboardManager) getContext(). 8827 getSystemService(Context.CLIPBOARD_SERVICE); 8828 clipboard.setPrimaryClip(clip); 8829 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 8830 } 8831 8832 /** 8833 * An ActionMode Callback class that is used to provide actions while in text selection mode. 8834 * 8835 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 8836 * on which of these this TextView supports. 8837 */ 8838 private class SelectionActionModeCallback implements ActionMode.Callback { 8839 8840 @Override 8841 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 8842 TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme); 8843 8844 boolean allowText = getContext().getResources().getBoolean( 8845 com.android.internal.R.bool.allow_action_menu_item_text_with_icon); 8846 8847 mode.setTitle(allowText ? 8848 mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null); 8849 mode.setSubtitle(null); 8850 8851 int selectAllIconId = 0; // No icon by default 8852 if (!allowText) { 8853 // Provide an icon, text will not be displayed on smaller screens. 8854 selectAllIconId = styledAttributes.getResourceId( 8855 R.styleable.Theme_actionModeSelectAllDrawable, 0); 8856 } 8857 8858 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 8859 setIcon(selectAllIconId). 8860 setAlphabeticShortcut('a'). 8861 setShowAsAction( 8862 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8863 8864 if (canCut()) { 8865 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 8866 setIcon(styledAttributes.getResourceId( 8867 R.styleable.Theme_actionModeCutDrawable, 0)). 8868 setAlphabeticShortcut('x'). 8869 setShowAsAction( 8870 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8871 } 8872 8873 if (canCopy()) { 8874 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 8875 setIcon(styledAttributes.getResourceId( 8876 R.styleable.Theme_actionModeCopyDrawable, 0)). 8877 setAlphabeticShortcut('c'). 8878 setShowAsAction( 8879 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8880 } 8881 8882 if (canPaste()) { 8883 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 8884 setIcon(styledAttributes.getResourceId( 8885 R.styleable.Theme_actionModePasteDrawable, 0)). 8886 setAlphabeticShortcut('v'). 8887 setShowAsAction( 8888 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 8889 } 8890 8891 styledAttributes.recycle(); 8892 8893 if (mCustomSelectionActionModeCallback != null) { 8894 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 8895 // The custom mode can choose to cancel the action mode 8896 return false; 8897 } 8898 } 8899 8900 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 8901 getSelectionController().show(); 8902 return true; 8903 } else { 8904 return false; 8905 } 8906 } 8907 8908 @Override 8909 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 8910 if (mCustomSelectionActionModeCallback != null) { 8911 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 8912 } 8913 return true; 8914 } 8915 8916 @Override 8917 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 8918 if (mCustomSelectionActionModeCallback != null && 8919 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 8920 return true; 8921 } 8922 return onTextContextMenuItem(item.getItemId()); 8923 } 8924 8925 @Override 8926 public void onDestroyActionMode(ActionMode mode) { 8927 if (mCustomSelectionActionModeCallback != null) { 8928 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 8929 } 8930 Selection.setSelection((Spannable) mText, getSelectionEnd()); 8931 8932 if (mSelectionModifierCursorController != null) { 8933 mSelectionModifierCursorController.hide(); 8934 } 8935 8936 mSelectionActionMode = null; 8937 } 8938 } 8939 8940 private class PastePopupWindow implements OnClickListener { 8941 private final PopupWindow mContainer; 8942 private final View[] mPasteViews = new View[4]; 8943 private final int[] mPasteViewLayouts = new int[] { 8944 mTextEditPasteWindowLayout, mTextEditNoPasteWindowLayout, 8945 mTextEditSidePasteWindowLayout, mTextEditSideNoPasteWindowLayout }; 8946 8947 public PastePopupWindow() { 8948 mContainer = new PopupWindow(TextView.this.mContext, null, 8949 com.android.internal.R.attr.textSelectHandleWindowStyle); 8950 mContainer.setSplitTouchEnabled(true); 8951 mContainer.setClippingEnabled(false); 8952 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8953 8954 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 8955 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 8956 } 8957 8958 private int viewIndex(boolean onTop) { 8959 return (onTop ? 0 : 1<<1) + (canPaste() ? 0 : 1<<0); 8960 } 8961 8962 private void updateContent(boolean onTop) { 8963 final int viewIndex = viewIndex(onTop); 8964 View view = mPasteViews[viewIndex]; 8965 8966 if (view == null) { 8967 final int layout = mPasteViewLayouts[viewIndex]; 8968 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 8969 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 8970 if (inflater != null) { 8971 view = inflater.inflate(layout, null); 8972 } 8973 8974 if (view == null) { 8975 throw new IllegalArgumentException("Unable to inflate TextEdit paste window"); 8976 } 8977 8978 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8979 view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8980 ViewGroup.LayoutParams.WRAP_CONTENT)); 8981 view.measure(size, size); 8982 8983 view.setOnClickListener(this); 8984 8985 mPasteViews[viewIndex] = view; 8986 } 8987 8988 mContainer.setContentView(view); 8989 } 8990 8991 public void show() { 8992 updateContent(true); 8993 positionAtCursor(); 8994 } 8995 8996 public void hide() { 8997 mContainer.dismiss(); 8998 } 8999 9000 public boolean isShowing() { 9001 return mContainer.isShowing(); 9002 } 9003 9004 @Override 9005 public void onClick(View v) { 9006 if (canPaste()) { 9007 paste(getSelectionStart(), getSelectionEnd()); 9008 } 9009 hide(); 9010 } 9011 9012 void positionAtCursor() { 9013 View contentView = mContainer.getContentView(); 9014 int width = contentView.getMeasuredWidth(); 9015 int height = contentView.getMeasuredHeight(); 9016 final int offset = TextView.this.getSelectionStart(); 9017 final int line = mLayout.getLineForOffset(offset); 9018 final int lineTop = mLayout.getLineTop(line); 9019 float primaryHorizontal = mLayout.getPrimaryHorizontal(offset); 9020 9021 final Rect bounds = sCursorControllerTempRect; 9022 bounds.left = (int) (primaryHorizontal - width / 2.0f); 9023 bounds.top = lineTop - height; 9024 9025 bounds.right = bounds.left + width; 9026 bounds.bottom = bounds.top + height; 9027 9028 convertFromViewportToContentCoordinates(bounds); 9029 9030 final int[] coords = mTempCoords; 9031 TextView.this.getLocationInWindow(coords); 9032 coords[0] += bounds.left; 9033 coords[1] += bounds.top; 9034 9035 final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels; 9036 if (coords[1] < 0) { 9037 updateContent(false); 9038 // Update dimensions from new view 9039 contentView = mContainer.getContentView(); 9040 width = contentView.getMeasuredWidth(); 9041 height = contentView.getMeasuredHeight(); 9042 9043 // Vertical clipping, move under edited line and to the side of insertion cursor 9044 // TODO bottom clipping in case there is no system bar 9045 coords[1] += height; 9046 final int lineBottom = mLayout.getLineBottom(line); 9047 final int lineHeight = lineBottom - lineTop; 9048 coords[1] += lineHeight; 9049 9050 // Move to right hand side of insertion cursor by default. TODO RTL text. 9051 final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes); 9052 final int handleHalfWidth = handle.getIntrinsicWidth() / 2; 9053 9054 if (primaryHorizontal + handleHalfWidth + width < screenWidth) { 9055 coords[0] += handleHalfWidth + width / 2; 9056 } else { 9057 coords[0] -= handleHalfWidth + width / 2; 9058 } 9059 } else { 9060 // Horizontal clipping 9061 coords[0] = Math.max(0, coords[0]); 9062 coords[0] = Math.min(screenWidth - width, coords[0]); 9063 } 9064 9065 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); 9066 } 9067 } 9068 9069 private abstract class HandleView extends View implements ViewTreeObserver.OnPreDrawListener { 9070 protected Drawable mDrawable; 9071 private final PopupWindow mContainer; 9072 // Position with respect to the parent TextView 9073 private int mPositionX, mPositionY; 9074 private boolean mIsDragging; 9075 // Offset from touch position to mPosition 9076 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 9077 protected float mHotspotX; 9078 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 9079 private float mTouchOffsetY; 9080 // Where the touch position should be on the handle to ensure a maximum cursor visibility 9081 private float mIdealVerticalOffset; 9082 // Parent's (TextView) previous position in window 9083 private int mLastParentX, mLastParentY; 9084 // PopupWindow container absolute position with respect to the enclosing window 9085 private int mContainerPositionX, mContainerPositionY; 9086 // Visible or not (scrolled off screen), whether or not this handle should be visible 9087 private boolean mIsActive = false; 9088 // Used to detect that setFrame was called 9089 private boolean mNeedsUpdate = true; 9090 9091 public HandleView() { 9092 super(TextView.this.mContext); 9093 mContainer = new PopupWindow(TextView.this.mContext, null, 9094 com.android.internal.R.attr.textSelectHandleWindowStyle); 9095 mContainer.setSplitTouchEnabled(true); 9096 mContainer.setClippingEnabled(false); 9097 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 9098 mContainer.setContentView(this); 9099 9100 initDrawable(); 9101 9102 final int handleHeight = mDrawable.getIntrinsicHeight(); 9103 mTouchOffsetY = -0.3f * handleHeight; 9104 mIdealVerticalOffset = 0.7f * handleHeight; 9105 } 9106 9107 @Override 9108 protected boolean setFrame(int left, int top, int right, int bottom) { 9109 boolean changed = super.setFrame(left, top, right, bottom); 9110 // onPreDraw is called for PhoneWindow before the layout of this view is 9111 // performed. Make sure to update position, even if container didn't move. 9112 if (changed) mNeedsUpdate = true; 9113 return changed; 9114 } 9115 9116 protected abstract void initDrawable(); 9117 9118 // Touch-up filter: number of previous positions remembered 9119 private static final int HISTORY_SIZE = 5; 9120 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 9121 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 9122 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 9123 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 9124 private int mPreviousOffsetIndex = 0; 9125 private int mNumberPreviousOffsets = 0; 9126 9127 private void startTouchUpFilter(int offset) { 9128 mNumberPreviousOffsets = 0; 9129 addPositionToTouchUpFilter(offset); 9130 } 9131 9132 private void addPositionToTouchUpFilter(int offset) { 9133 if (mNumberPreviousOffsets > 0 && 9134 mPreviousOffsets[mPreviousOffsetIndex] == offset) { 9135 // Make sure only actual changes of position are recorded. 9136 return; 9137 } 9138 9139 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 9140 mPreviousOffsets[mPreviousOffsetIndex] = offset; 9141 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 9142 mNumberPreviousOffsets++; 9143 } 9144 9145 private void filterOnTouchUp() { 9146 final long now = SystemClock.uptimeMillis(); 9147 int i = 0; 9148 int index = mPreviousOffsetIndex; 9149 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 9150 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 9151 i++; 9152 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 9153 } 9154 9155 if (i > 0 && i < iMax && 9156 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 9157 updateOffset(mPreviousOffsets[index]); 9158 } 9159 } 9160 9161 @Override 9162 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 9163 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 9164 } 9165 9166 public void show() { 9167 if (isShowing()) { 9168 mContainer.update(mContainerPositionX, mContainerPositionY, 9169 mRight - mLeft, mBottom - mTop); 9170 } else { 9171 mContainer.showAtLocation(TextView.this, 0, 9172 mContainerPositionX, mContainerPositionY); 9173 9174 mIsActive = true; 9175 9176 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9177 vto.addOnPreDrawListener(this); 9178 } 9179 } 9180 9181 protected void dismiss() { 9182 mIsDragging = false; 9183 mContainer.dismiss(); 9184 } 9185 9186 public void hide() { 9187 dismiss(); 9188 9189 mIsActive = false; 9190 9191 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9192 vto.removeOnPreDrawListener(this); 9193 } 9194 9195 public boolean isShowing() { 9196 return mContainer.isShowing(); 9197 } 9198 9199 private boolean isPositionVisible() { 9200 // Always show a dragging handle. 9201 if (mIsDragging) { 9202 return true; 9203 } 9204 9205 if (isInBatchEditMode()) { 9206 return false; 9207 } 9208 9209 final int extendedPaddingTop = getExtendedPaddingTop(); 9210 final int extendedPaddingBottom = getExtendedPaddingBottom(); 9211 final int compoundPaddingLeft = getCompoundPaddingLeft(); 9212 final int compoundPaddingRight = getCompoundPaddingRight(); 9213 9214 final TextView textView = TextView.this; 9215 9216 if (mTempRect == null) mTempRect = new Rect(); 9217 final Rect clip = mTempRect; 9218 clip.left = compoundPaddingLeft; 9219 clip.top = extendedPaddingTop; 9220 clip.right = textView.getWidth() - compoundPaddingRight; 9221 clip.bottom = textView.getHeight() - extendedPaddingBottom; 9222 9223 final ViewParent parent = textView.getParent(); 9224 if (parent == null || !parent.getChildVisibleRect(textView, clip, null)) { 9225 return false; 9226 } 9227 9228 final int[] coords = mTempCoords; 9229 textView.getLocationInWindow(coords); 9230 final int posX = coords[0] + mPositionX + (int) mHotspotX; 9231 final int posY = coords[1] + mPositionY; 9232 9233 // Offset by 1 to take into account 0.5 and int rounding around getPrimaryHorizontal. 9234 return posX >= clip.left - 1 && posX <= clip.right + 1 && 9235 posY >= clip.top && posY <= clip.bottom; 9236 } 9237 9238 public abstract int getCurrentCursorOffset(); 9239 9240 public abstract void updateOffset(int offset); 9241 9242 public abstract void updatePosition(float x, float y); 9243 9244 protected void positionAtCursorOffset(int offset) { 9245 // A HandleView relies on the layout, which may be nulled by external methods. 9246 if (mLayout == null) { 9247 // Will update controllers' state, hiding them and stopping selection mode if needed 9248 prepareCursorControllers(); 9249 return; 9250 } 9251 9252 addPositionToTouchUpFilter(offset); 9253 final int line = mLayout.getLineForOffset(offset); 9254 final int lineBottom = mLayout.getLineBottom(line); 9255 9256 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 9257 mPositionY = lineBottom; 9258 9259 // Take TextView's padding into account. 9260 mPositionX += viewportToContentHorizontalOffset(); 9261 mPositionY += viewportToContentVerticalOffset(); 9262 } 9263 9264 private void checkForContainerPositionChange() { 9265 positionAtCursorOffset(getCurrentCursorOffset()); 9266 9267 final int previousContainerPositionX = mContainerPositionX; 9268 final int previousContainerPositionY = mContainerPositionY; 9269 9270 TextView.this.getLocationInWindow(mTempCoords); 9271 mContainerPositionX = mTempCoords[0] + mPositionX; 9272 mContainerPositionY = mTempCoords[1] + mPositionY; 9273 9274 mNeedsUpdate |= previousContainerPositionX != mContainerPositionX; 9275 mNeedsUpdate |= previousContainerPositionY != mContainerPositionY; 9276 } 9277 9278 public boolean onPreDraw() { 9279 checkForContainerPositionChange(); 9280 if (mNeedsUpdate) { 9281 if (mIsDragging) { 9282 if (mTempCoords[0] != mLastParentX || mTempCoords[1] != mLastParentY) { 9283 mTouchToWindowOffsetX += mTempCoords[0] - mLastParentX; 9284 mTouchToWindowOffsetY += mTempCoords[1] - mLastParentY; 9285 mLastParentX = mTempCoords[0]; 9286 mLastParentY = mTempCoords[1]; 9287 } 9288 } 9289 9290 onHandleMoved(); 9291 9292 if (isPositionVisible()) { 9293 mContainer.update(mContainerPositionX, mContainerPositionY, 9294 mRight - mLeft, mBottom - mTop); 9295 9296 if (mIsActive && !isShowing()) { 9297 show(); 9298 } 9299 } else { 9300 if (isShowing()) { 9301 dismiss(); 9302 } 9303 } 9304 mNeedsUpdate = false; 9305 } 9306 return true; 9307 } 9308 9309 @Override 9310 protected void onDraw(Canvas c) { 9311 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 9312 mDrawable.draw(c); 9313 } 9314 9315 @Override 9316 public boolean onTouchEvent(MotionEvent ev) { 9317 switch (ev.getActionMasked()) { 9318 case MotionEvent.ACTION_DOWN: { 9319 startTouchUpFilter(getCurrentCursorOffset()); 9320 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 9321 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 9322 9323 final int[] coords = mTempCoords; 9324 TextView.this.getLocationInWindow(coords); 9325 mLastParentX = coords[0]; 9326 mLastParentY = coords[1]; 9327 mIsDragging = true; 9328 break; 9329 } 9330 9331 case MotionEvent.ACTION_MOVE: { 9332 final float rawX = ev.getRawX(); 9333 final float rawY = ev.getRawY(); 9334 9335 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 9336 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 9337 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 9338 float newVerticalOffset; 9339 if (previousVerticalOffset < mIdealVerticalOffset) { 9340 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 9341 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 9342 } else { 9343 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 9344 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 9345 } 9346 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 9347 9348 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 9349 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 9350 9351 updatePosition(newPosX, newPosY); 9352 break; 9353 } 9354 9355 case MotionEvent.ACTION_UP: 9356 filterOnTouchUp(); 9357 mIsDragging = false; 9358 break; 9359 9360 case MotionEvent.ACTION_CANCEL: 9361 mIsDragging = false; 9362 break; 9363 } 9364 return true; 9365 } 9366 9367 public boolean isDragging() { 9368 return mIsDragging; 9369 } 9370 9371 void onHandleMoved() { 9372 // Does nothing by default 9373 } 9374 9375 public void onDetached() { 9376 // Should be overriden to clean possible Runnable 9377 } 9378 } 9379 9380 private class InsertionHandleView extends HandleView { 9381 private static final int DELAY_BEFORE_FADE_OUT = 4000; 9382 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 9383 9384 // Used to detect taps on the insertion handle, which will affect the PastePopupWindow 9385 private float mDownPositionX, mDownPositionY; 9386 private PastePopupWindow mPastePopupWindow; 9387 private Runnable mHider; 9388 private Runnable mPastePopupShower; 9389 9390 @Override 9391 public void show() { 9392 super.show(); 9393 hideDelayed(); 9394 hidePastePopupWindow(); 9395 } 9396 9397 public void show(int delayBeforePaste) { 9398 show(); 9399 9400 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 9401 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 9402 delayBeforePaste = 0; 9403 } 9404 if (delayBeforePaste == 0 || canPaste()) { 9405 if (mPastePopupShower == null) { 9406 mPastePopupShower = new Runnable() { 9407 public void run() { 9408 showPastePopupWindow(); 9409 } 9410 }; 9411 } 9412 TextView.this.postDelayed(mPastePopupShower, delayBeforePaste); 9413 } 9414 } 9415 9416 @Override 9417 protected void dismiss() { 9418 super.dismiss(); 9419 onDetached(); 9420 } 9421 9422 private void hideDelayed() { 9423 removeHiderCallback(); 9424 if (mHider == null) { 9425 mHider = new Runnable() { 9426 public void run() { 9427 hide(); 9428 } 9429 }; 9430 } 9431 TextView.this.postDelayed(mHider, DELAY_BEFORE_FADE_OUT); 9432 } 9433 9434 private void removeHiderCallback() { 9435 if (mHider != null) { 9436 TextView.this.removeCallbacks(mHider); 9437 } 9438 } 9439 9440 @Override 9441 protected void initDrawable() { 9442 if (mSelectHandleCenter == null) { 9443 mSelectHandleCenter = mContext.getResources().getDrawable( 9444 mTextSelectHandleRes); 9445 } 9446 mDrawable = mSelectHandleCenter; 9447 mHotspotX = mDrawable.getIntrinsicWidth() / 2.0f; 9448 } 9449 9450 @Override 9451 public boolean onTouchEvent(MotionEvent ev) { 9452 final boolean result = super.onTouchEvent(ev); 9453 9454 switch (ev.getActionMasked()) { 9455 case MotionEvent.ACTION_DOWN: 9456 mDownPositionX = ev.getRawX(); 9457 mDownPositionY = ev.getRawY(); 9458 break; 9459 9460 case MotionEvent.ACTION_UP: 9461 final float deltaX = mDownPositionX - ev.getRawX(); 9462 final float deltaY = mDownPositionY - ev.getRawY(); 9463 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 9464 if (distanceSquared < mSquaredTouchSlopDistance) { 9465 if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) { 9466 // Tapping on the handle dismisses the displayed paste view, 9467 mPastePopupWindow.hide(); 9468 } else { 9469 show(0); 9470 } 9471 } 9472 hideDelayed(); 9473 break; 9474 9475 case MotionEvent.ACTION_CANCEL: 9476 hideDelayed(); 9477 break; 9478 9479 default: 9480 break; 9481 } 9482 9483 return result; 9484 } 9485 9486 @Override 9487 public int getCurrentCursorOffset() { 9488 return TextView.this.getSelectionStart(); 9489 } 9490 9491 @Override 9492 public void updateOffset(int offset) { 9493 Selection.setSelection((Spannable) mText, offset); 9494 } 9495 9496 @Override 9497 public void updatePosition(float x, float y) { 9498 updateOffset(getOffsetForPosition(x, y)); 9499 } 9500 9501 void showPastePopupWindow() { 9502 if (mPastePopupWindow == null) { 9503 mPastePopupWindow = new PastePopupWindow(); 9504 } 9505 mPastePopupWindow.show(); 9506 } 9507 9508 @Override 9509 void onHandleMoved() { 9510 removeHiderCallback(); 9511 hidePastePopupWindow(); 9512 } 9513 9514 void hidePastePopupWindow() { 9515 if (mPastePopupShower != null) { 9516 TextView.this.removeCallbacks(mPastePopupShower); 9517 } 9518 if (mPastePopupWindow != null) { 9519 mPastePopupWindow.hide(); 9520 } 9521 } 9522 9523 @Override 9524 public void onDetached() { 9525 removeHiderCallback(); 9526 hidePastePopupWindow(); 9527 } 9528 } 9529 9530 private class SelectionStartHandleView extends HandleView { 9531 @Override 9532 protected void initDrawable() { 9533 if (mSelectHandleLeft == null) { 9534 mSelectHandleLeft = mContext.getResources().getDrawable( 9535 mTextSelectHandleLeftRes); 9536 } 9537 mDrawable = mSelectHandleLeft; 9538 mHotspotX = mDrawable.getIntrinsicWidth() * 3.0f / 4.0f; 9539 } 9540 9541 @Override 9542 public int getCurrentCursorOffset() { 9543 return TextView.this.getSelectionStart(); 9544 } 9545 9546 @Override 9547 public void updateOffset(int offset) { 9548 Selection.setSelection((Spannable) mText, offset, getSelectionEnd()); 9549 } 9550 9551 @Override 9552 public void updatePosition(float x, float y) { 9553 final int selectionStart = getSelectionStart(); 9554 final int selectionEnd = getSelectionEnd(); 9555 9556 int offset = getOffsetForPosition(x, y); 9557 9558 // No need to redraw when the offset is unchanged 9559 if (offset == selectionStart) return; 9560 // Handles can not cross and selection is at least one character 9561 if (offset >= selectionEnd) offset = selectionEnd - 1; 9562 9563 Selection.setSelection((Spannable) mText, offset, selectionEnd); 9564 } 9565 } 9566 9567 private class SelectionEndHandleView extends HandleView { 9568 @Override 9569 protected void initDrawable() { 9570 if (mSelectHandleRight == null) { 9571 mSelectHandleRight = mContext.getResources().getDrawable( 9572 mTextSelectHandleRightRes); 9573 } 9574 mDrawable = mSelectHandleRight; 9575 mHotspotX = mDrawable.getIntrinsicWidth() / 4.0f; 9576 } 9577 9578 @Override 9579 public int getCurrentCursorOffset() { 9580 return TextView.this.getSelectionEnd(); 9581 } 9582 9583 @Override 9584 public void updateOffset(int offset) { 9585 Selection.setSelection((Spannable) mText, getSelectionStart(), offset); 9586 } 9587 9588 @Override 9589 public void updatePosition(float x, float y) { 9590 final int selectionStart = getSelectionStart(); 9591 final int selectionEnd = getSelectionEnd(); 9592 9593 int offset = getOffsetForPosition(x, y); 9594 9595 // No need to redraw when the offset is unchanged 9596 if (offset == selectionEnd) return; 9597 // Handles can not cross and selection is at least one character 9598 if (offset <= selectionStart) offset = selectionStart + 1; 9599 9600 Selection.setSelection((Spannable) mText, selectionStart, offset); 9601 } 9602 } 9603 9604 /** 9605 * A CursorController instance can be used to control a cursor in the text. 9606 * It is not used outside of {@link TextView}. 9607 * @hide 9608 */ 9609 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 9610 /** 9611 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 9612 * See also {@link #hide()}. 9613 */ 9614 public void show(); 9615 9616 /** 9617 * Hide the cursor controller from screen. 9618 * See also {@link #show()}. 9619 */ 9620 public void hide(); 9621 9622 /** 9623 * This method is called by {@link #onTouchEvent(MotionEvent)} and gives the controller 9624 * a chance to become active and/or visible. 9625 * @param event The touch event 9626 */ 9627 public boolean onTouchEvent(MotionEvent event); 9628 9629 /** 9630 * Called when the view is detached from window. Perform house keeping task, such as 9631 * stopping Runnable thread that would otherwise keep a reference on the context, thus 9632 * preventing the activity from being recycled. 9633 */ 9634 public void onDetached(); 9635 } 9636 9637 private class InsertionPointCursorController implements CursorController { 9638 private static final int DELAY_BEFORE_PASTE = 2000; 9639 9640 private InsertionHandleView mHandle; 9641 9642 public void show() { 9643 ((InsertionHandleView) getHandle()).show(DELAY_BEFORE_PASTE); 9644 } 9645 9646 public void showWithPaste() { 9647 ((InsertionHandleView) getHandle()).show(0); 9648 } 9649 9650 public void hide() { 9651 if (mHandle != null) { 9652 mHandle.hide(); 9653 } 9654 } 9655 9656 public boolean onTouchEvent(MotionEvent ev) { 9657 return false; 9658 } 9659 9660 public void onTouchModeChanged(boolean isInTouchMode) { 9661 if (!isInTouchMode) { 9662 hide(); 9663 } 9664 } 9665 9666 private HandleView getHandle() { 9667 if (mHandle == null) { 9668 mHandle = new InsertionHandleView(); 9669 } 9670 return mHandle; 9671 } 9672 9673 @Override 9674 public void onDetached() { 9675 final ViewTreeObserver observer = getViewTreeObserver(); 9676 observer.removeOnTouchModeChangeListener(this); 9677 9678 if (mHandle != null) mHandle.onDetached(); 9679 } 9680 } 9681 9682 private class SelectionModifierCursorController implements CursorController { 9683 // The cursor controller handles, lazily created when shown. 9684 private SelectionStartHandleView mStartHandle; 9685 private SelectionEndHandleView mEndHandle; 9686 // The offsets of that last touch down event. Remembered to start selection there. 9687 private int mMinTouchOffset, mMaxTouchOffset; 9688 9689 // Double tap detection 9690 private long mPreviousTapUpTime = 0; 9691 private float mPreviousTapPositionX, mPreviousTapPositionY; 9692 9693 SelectionModifierCursorController() { 9694 resetTouchOffsets(); 9695 } 9696 9697 public void show() { 9698 if (isInBatchEditMode()) { 9699 return; 9700 } 9701 9702 // Lazy object creation has to be done before updatePosition() is called. 9703 if (mStartHandle == null) mStartHandle = new SelectionStartHandleView(); 9704 if (mEndHandle == null) mEndHandle = new SelectionEndHandleView(); 9705 9706 mStartHandle.show(); 9707 mEndHandle.show(); 9708 9709 hideInsertionPointCursorController(); 9710 hideSuggestions(); 9711 } 9712 9713 public void hide() { 9714 if (mStartHandle != null) mStartHandle.hide(); 9715 if (mEndHandle != null) mEndHandle.hide(); 9716 } 9717 9718 public boolean onTouchEvent(MotionEvent event) { 9719 // This is done even when the View does not have focus, so that long presses can start 9720 // selection and tap can move cursor from this tap position. 9721 if (isTextEditable() || mTextIsSelectable) { 9722 switch (event.getActionMasked()) { 9723 case MotionEvent.ACTION_DOWN: 9724 final float x = event.getX(); 9725 final float y = event.getY(); 9726 9727 // Remember finger down position, to be able to start selection from there 9728 mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y); 9729 9730 // Double tap detection 9731 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 9732 if (duration <= ViewConfiguration.getDoubleTapTimeout() && 9733 isPositionOnText(x, y)) { 9734 final float deltaX = x - mPreviousTapPositionX; 9735 final float deltaY = y - mPreviousTapPositionY; 9736 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 9737 if (distanceSquared < mSquaredTouchSlopDistance) { 9738 showSuggestions(); 9739 mDiscardNextActionUp = true; 9740 } 9741 } 9742 9743 mPreviousTapPositionX = x; 9744 mPreviousTapPositionY = y; 9745 9746 break; 9747 9748 case MotionEvent.ACTION_POINTER_DOWN: 9749 case MotionEvent.ACTION_POINTER_UP: 9750 // Handle multi-point gestures. Keep min and max offset positions. 9751 // Only activated for devices that correctly handle multi-touch. 9752 if (mContext.getPackageManager().hasSystemFeature( 9753 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 9754 updateMinAndMaxOffsets(event); 9755 } 9756 break; 9757 9758 case MotionEvent.ACTION_UP: 9759 mPreviousTapUpTime = SystemClock.uptimeMillis(); 9760 break; 9761 } 9762 } 9763 return false; 9764 } 9765 9766 /** 9767 * @param event 9768 */ 9769 private void updateMinAndMaxOffsets(MotionEvent event) { 9770 int pointerCount = event.getPointerCount(); 9771 for (int index = 0; index < pointerCount; index++) { 9772 int offset = getOffsetForPosition(event.getX(index), event.getY(index)); 9773 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 9774 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 9775 } 9776 } 9777 9778 public int getMinTouchOffset() { 9779 return mMinTouchOffset; 9780 } 9781 9782 public int getMaxTouchOffset() { 9783 return mMaxTouchOffset; 9784 } 9785 9786 public void resetTouchOffsets() { 9787 mMinTouchOffset = mMaxTouchOffset = -1; 9788 } 9789 9790 /** 9791 * @return true iff this controller is currently used to move the selection start. 9792 */ 9793 public boolean isSelectionStartDragged() { 9794 return mStartHandle != null && mStartHandle.isDragging(); 9795 } 9796 9797 public void onTouchModeChanged(boolean isInTouchMode) { 9798 if (!isInTouchMode) { 9799 hide(); 9800 } 9801 } 9802 9803 @Override 9804 public void onDetached() { 9805 final ViewTreeObserver observer = getViewTreeObserver(); 9806 observer.removeOnTouchModeChangeListener(this); 9807 9808 if (mStartHandle != null) mStartHandle.onDetached(); 9809 if (mEndHandle != null) mEndHandle.onDetached(); 9810 } 9811 } 9812 9813 private void hideInsertionPointCursorController() { 9814 // No need to create the controller to hide it. 9815 if (mInsertionPointCursorController != null) { 9816 mInsertionPointCursorController.hide(); 9817 } 9818 } 9819 9820 /** 9821 * Hides the insertion controller and stops text selection mode, hiding the selection controller 9822 */ 9823 private void hideControllers() { 9824 hideInsertionPointCursorController(); 9825 stopSelectionActionMode(); 9826 hideSuggestions(); 9827 } 9828 9829 /** 9830 * Get the character offset closest to the specified absolute position. A typical use case is to 9831 * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. 9832 * 9833 * @param x The horizontal absolute position of a point on screen 9834 * @param y The vertical absolute position of a point on screen 9835 * @return the character offset for the character whose position is closest to the specified 9836 * position. Returns -1 if there is no layout. 9837 */ 9838 public int getOffsetForPosition(float x, float y) { 9839 if (getLayout() == null) return -1; 9840 final int line = getLineAtCoordinate(y); 9841 final int offset = getOffsetAtCoordinate(line, x); 9842 return offset; 9843 } 9844 9845 private float convertToLocalHorizontalCoordinate(float x) { 9846 x -= getTotalPaddingLeft(); 9847 // Clamp the position to inside of the view. 9848 x = Math.max(0.0f, x); 9849 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 9850 x += getScrollX(); 9851 return x; 9852 } 9853 9854 private int getLineAtCoordinate(float y) { 9855 y -= getTotalPaddingTop(); 9856 // Clamp the position to inside of the view. 9857 y = Math.max(0.0f, y); 9858 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 9859 y += getScrollY(); 9860 return getLayout().getLineForVertical((int) y); 9861 } 9862 9863 private int getOffsetAtCoordinate(int line, float x) { 9864 x = convertToLocalHorizontalCoordinate(x); 9865 return getLayout().getOffsetForHorizontal(line, x); 9866 } 9867 9868 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 9869 * in the view. Returns false when the position is in the empty space of left/right of text. 9870 */ 9871 private boolean isPositionOnText(float x, float y) { 9872 if (getLayout() == null) return false; 9873 9874 final int line = getLineAtCoordinate(y); 9875 x = convertToLocalHorizontalCoordinate(x); 9876 9877 if (x < getLayout().getLineLeft(line)) return false; 9878 if (x > getLayout().getLineRight(line)) return false; 9879 return true; 9880 } 9881 9882 @Override 9883 public boolean onDragEvent(DragEvent event) { 9884 switch (event.getAction()) { 9885 case DragEvent.ACTION_DRAG_STARTED: 9886 return hasInsertionController(); 9887 9888 case DragEvent.ACTION_DRAG_ENTERED: 9889 TextView.this.requestFocus(); 9890 return true; 9891 9892 case DragEvent.ACTION_DRAG_LOCATION: 9893 final int offset = getOffsetForPosition(event.getX(), event.getY()); 9894 Selection.setSelection((Spannable)mText, offset); 9895 return true; 9896 9897 case DragEvent.ACTION_DROP: 9898 onDrop(event); 9899 return true; 9900 9901 case DragEvent.ACTION_DRAG_ENDED: 9902 case DragEvent.ACTION_DRAG_EXITED: 9903 default: 9904 return true; 9905 } 9906 } 9907 9908 private void onDrop(DragEvent event) { 9909 StringBuilder content = new StringBuilder(""); 9910 ClipData clipData = event.getClipData(); 9911 final int itemCount = clipData.getItemCount(); 9912 for (int i=0; i < itemCount; i++) { 9913 Item item = clipData.getItemAt(i); 9914 content.append(item.coerceToText(TextView.this.mContext)); 9915 } 9916 9917 final int offset = getOffsetForPosition(event.getX(), event.getY()); 9918 9919 Object localState = event.getLocalState(); 9920 DragLocalState dragLocalState = null; 9921 if (localState instanceof DragLocalState) { 9922 dragLocalState = (DragLocalState) localState; 9923 } 9924 boolean dragDropIntoItself = dragLocalState != null && 9925 dragLocalState.sourceTextView == this; 9926 9927 if (dragDropIntoItself) { 9928 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 9929 // A drop inside the original selection discards the drop. 9930 return; 9931 } 9932 } 9933 9934 final int originalLength = mText.length(); 9935 long minMax = prepareSpacesAroundPaste(offset, offset, content); 9936 int min = extractRangeStartFromLong(minMax); 9937 int max = extractRangeEndFromLong(minMax); 9938 9939 Selection.setSelection((Spannable) mText, max); 9940 ((Editable) mText).replace(min, max, content); 9941 9942 if (dragDropIntoItself) { 9943 int dragSourceStart = dragLocalState.start; 9944 int dragSourceEnd = dragLocalState.end; 9945 if (max <= dragSourceStart) { 9946 // Inserting text before selection has shifted positions 9947 final int shift = mText.length() - originalLength; 9948 dragSourceStart += shift; 9949 dragSourceEnd += shift; 9950 } 9951 9952 // Delete original selection 9953 ((Editable) mText).delete(dragSourceStart, dragSourceEnd); 9954 9955 // Make sure we do not leave two adjacent spaces. 9956 if ((dragSourceStart == 0 || 9957 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 9958 (dragSourceStart == mText.length() || 9959 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 9960 final int pos = dragSourceStart == mText.length() ? 9961 dragSourceStart - 1 : dragSourceStart; 9962 ((Editable) mText).delete(pos, pos + 1); 9963 } 9964 } 9965 } 9966 9967 /** 9968 * @return True if this view supports insertion handles. 9969 */ 9970 boolean hasInsertionController() { 9971 return mInsertionControllerEnabled; 9972 } 9973 9974 /** 9975 * @return True if this view supports selection handles. 9976 */ 9977 boolean hasSelectionController() { 9978 return mSelectionControllerEnabled; 9979 } 9980 9981 InsertionPointCursorController getInsertionController() { 9982 if (!mInsertionControllerEnabled) { 9983 return null; 9984 } 9985 9986 if (mInsertionPointCursorController == null) { 9987 mInsertionPointCursorController = new InsertionPointCursorController(); 9988 9989 final ViewTreeObserver observer = getViewTreeObserver(); 9990 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 9991 } 9992 9993 return mInsertionPointCursorController; 9994 } 9995 9996 SelectionModifierCursorController getSelectionController() { 9997 if (!mSelectionControllerEnabled) { 9998 return null; 9999 } 10000 10001 if (mSelectionModifierCursorController == null) { 10002 mSelectionModifierCursorController = new SelectionModifierCursorController(); 10003 10004 final ViewTreeObserver observer = getViewTreeObserver(); 10005 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 10006 } 10007 10008 return mSelectionModifierCursorController; 10009 } 10010 10011 boolean isInBatchEditMode() { 10012 final InputMethodState ims = mInputMethodState; 10013 if (ims != null) { 10014 return ims.mBatchEditNesting > 0; 10015 } 10016 return mInBatchEditControllers; 10017 } 10018 10019 /** 10020 * Resolve the text direction. 10021 * 10022 * Text direction of paragraphs in a TextView is determined using a heuristic. If the correct 10023 * text direction cannot be determined by the heuristic, the view’s resolved layout direction 10024 * determines the direction. 10025 * 10026 * This heuristic and result is applied individually to each paragraph in a TextView, based on 10027 * the text and style content of that paragraph. Paragraph text styles can also be used to force 10028 * a particular direction. 10029 */ 10030 @Override 10031 protected void resolveTextDirection() { 10032 int resolvedTextDirection = TEXT_DIRECTION_UNDEFINED; 10033 switch(mTextDirection) { 10034 default: 10035 case TEXT_DIRECTION_INHERIT: 10036 // Try to the text direction from the parent layout. If not possible, then we will 10037 // use the default layout direction to decide later 10038 if (mParent != null && mParent instanceof ViewGroup) { 10039 resolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 10040 } 10041 break; 10042 case TEXT_DIRECTION_FIRST_STRONG: 10043 resolvedTextDirection = getTextDirectionFromFirstStrong(mText); 10044 break; 10045 case TEXT_DIRECTION_ANY_RTL: 10046 resolvedTextDirection = getTextDirectionFromAnyRtl(mText); 10047 break; 10048 case TEXT_DIRECTION_LTR: 10049 resolvedTextDirection = TEXT_DIRECTION_LTR; 10050 break; 10051 case TEXT_DIRECTION_RTL: 10052 resolvedTextDirection = TEXT_DIRECTION_RTL; 10053 break; 10054 } 10055 // if we have been so far unable to get the text direction from the heuristics, then we are 10056 // falling back using the layout direction 10057 if (resolvedTextDirection == TEXT_DIRECTION_UNDEFINED) { 10058 switch(getResolvedLayoutDirection()) { 10059 default: 10060 case LAYOUT_DIRECTION_LTR: 10061 resolvedTextDirection = TEXT_DIRECTION_LTR; 10062 break; 10063 case LAYOUT_DIRECTION_RTL: 10064 resolvedTextDirection = TEXT_DIRECTION_RTL; 10065 break; 10066 } 10067 } 10068 mResolvedTextDirection = resolvedTextDirection; 10069 } 10070 10071 /** 10072 * Get text direction following the "first strong" heuristic. 10073 * 10074 * @param cs the CharSequence used to get the text direction. 10075 * 10076 * @return {@link #TEXT_DIRECTION_RTL} if direction it RTL, {@link #TEXT_DIRECTION_LTR} if 10077 * direction it LTR or {@link #TEXT_DIRECTION_UNDEFINED} if direction cannot be found. 10078 */ 10079 private static int getTextDirectionFromFirstStrong(final CharSequence cs) { 10080 final int length = cs.length(); 10081 for(int i = 0; i < length; i++) { 10082 final char c = cs.charAt(i); 10083 final byte dir = Character.getDirectionality(c); 10084 if (isStrongLtrChar(dir)) { 10085 return TEXT_DIRECTION_LTR; 10086 } else if (isStrongRtlChar(dir)) { 10087 return TEXT_DIRECTION_RTL; 10088 } 10089 } 10090 return TEXT_DIRECTION_UNDEFINED; 10091 } 10092 10093 /** 10094 * Get text direction following the "any RTL" heuristic. 10095 * 10096 * @param cs the CharSequence used to get the text direction. 10097 * 10098 * @return {@link #TEXT_DIRECTION_RTL} if direction it RTL, {@link #TEXT_DIRECTION_LTR} if 10099 * direction it LTR or {@link #TEXT_DIRECTION_UNDEFINED} if direction cannot be found. 10100 */ 10101 private static int getTextDirectionFromAnyRtl(final CharSequence cs) { 10102 final int length = cs.length(); 10103 boolean foundStrongLtr = false; 10104 boolean foundStrongRtl = false; 10105 for(int i = 0; i < length; i++) { 10106 final char c = cs.charAt(i); 10107 final byte dir = Character.getDirectionality(c); 10108 if (isStrongLtrChar(dir)) { 10109 foundStrongLtr = true; 10110 } else if (isStrongRtlChar(dir)) { 10111 foundStrongRtl = true; 10112 } 10113 } 10114 if (foundStrongRtl) { 10115 return TEXT_DIRECTION_RTL; 10116 } 10117 if (foundStrongLtr) { 10118 return TEXT_DIRECTION_LTR; 10119 } 10120 return TEXT_DIRECTION_UNDEFINED; 10121 } 10122 10123 /** 10124 * Return true if the char direction is corresponding to a "strong RTL char" following the 10125 * Unicode Bidirectional Algorithm (UBA). 10126 */ 10127 private static boolean isStrongRtlChar(final byte dir) { 10128 return (dir == Character.DIRECTIONALITY_RIGHT_TO_LEFT || 10129 dir == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC); 10130 } 10131 10132 /** 10133 * Return true if the char direction is corresponding to a "strong LTR char" following the 10134 * Unicode Bidirectional Algorithm (UBA). 10135 */ 10136 private static boolean isStrongLtrChar(final byte dir) { 10137 return (dir == Character.DIRECTIONALITY_LEFT_TO_RIGHT); 10138 } 10139 10140 @ViewDebug.ExportedProperty(category = "text") 10141 private CharSequence mText; 10142 private CharSequence mTransformed; 10143 private BufferType mBufferType = BufferType.NORMAL; 10144 10145 private int mInputType = EditorInfo.TYPE_NULL; 10146 private CharSequence mHint; 10147 private Layout mHintLayout; 10148 10149 private KeyListener mInput; 10150 10151 private MovementMethod mMovement; 10152 private TransformationMethod mTransformation; 10153 private ChangeWatcher mChangeWatcher; 10154 10155 private ArrayList<TextWatcher> mListeners = null; 10156 10157 // display attributes 10158 private final TextPaint mTextPaint; 10159 private boolean mUserSetTextScaleX; 10160 private final Paint mHighlightPaint; 10161 private int mHighlightColor = 0xCC475925; 10162 /** 10163 * This is temporarily visible to fix bug 3085564 in webView. Do not rely on 10164 * this field being protected. Will be restored as private when lineHeight 10165 * feature request 3215097 is implemented 10166 * @hide 10167 */ 10168 protected Layout mLayout; 10169 10170 private long mShowCursor; 10171 private Blink mBlink; 10172 private boolean mCursorVisible = true; 10173 10174 // Cursor Controllers. 10175 private InsertionPointCursorController mInsertionPointCursorController; 10176 private SelectionModifierCursorController mSelectionModifierCursorController; 10177 private ActionMode mSelectionActionMode; 10178 private boolean mInsertionControllerEnabled; 10179 private boolean mSelectionControllerEnabled; 10180 private boolean mInBatchEditControllers; 10181 10182 // These are needed to desambiguate a long click. If the long click comes from ones of these, we 10183 // select from the current cursor position. Otherwise, select from long pressed position. 10184 private boolean mDPadCenterIsDown = false; 10185 private boolean mEnterKeyIsDown = false; 10186 private boolean mContextMenuTriggeredByKey = false; 10187 // Created once and shared by different CursorController helper methods. 10188 // Only one cursor controller is active at any time which prevent race conditions. 10189 private static Rect sCursorControllerTempRect = new Rect(); 10190 10191 private boolean mSelectAllOnFocus = false; 10192 10193 private int mGravity = Gravity.TOP | Gravity.START; 10194 private boolean mHorizontallyScrolling; 10195 10196 private int mAutoLinkMask; 10197 private boolean mLinksClickable = true; 10198 10199 private float mSpacingMult = 1; 10200 private float mSpacingAdd = 0; 10201 private boolean mTextIsSelectable = false; 10202 10203 private static final int LINES = 1; 10204 private static final int EMS = LINES; 10205 private static final int PIXELS = 2; 10206 10207 private int mMaximum = Integer.MAX_VALUE; 10208 private int mMaxMode = LINES; 10209 private int mMinimum = 0; 10210 private int mMinMode = LINES; 10211 10212 private int mMaxWidth = Integer.MAX_VALUE; 10213 private int mMaxWidthMode = PIXELS; 10214 private int mMinWidth = 0; 10215 private int mMinWidthMode = PIXELS; 10216 10217 private boolean mSingleLine; 10218 private int mDesiredHeightAtMeasure = -1; 10219 private boolean mIncludePad = true; 10220 10221 // tmp primitives, so we don't alloc them on each draw 10222 private Path mHighlightPath; 10223 private boolean mHighlightPathBogus = true; 10224 private static final RectF sTempRect = new RectF(); 10225 10226 // XXX should be much larger 10227 private static final int VERY_WIDE = 16384; 10228 10229 private static final int BLINK = 500; 10230 10231 private static final int ANIMATED_SCROLL_GAP = 250; 10232 private long mLastScroll; 10233 private Scroller mScroller = null; 10234 10235 private BoringLayout.Metrics mBoring; 10236 private BoringLayout.Metrics mHintBoring; 10237 10238 private BoringLayout mSavedLayout, mSavedHintLayout; 10239 10240 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 10241 private InputFilter[] mFilters = NO_FILTERS; 10242 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 10243 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 10244 // System wide time for last cut or copy action. 10245 private static long sLastCutOrCopyTime; 10246 // Used to highlight a word when it is corrected by the IME 10247 private CorrectionHighlighter mCorrectionHighlighter; 10248 // New state used to change background based on whether this TextView is multiline. 10249 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 10250} 10251