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