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