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