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