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