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