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