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