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