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