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