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