TextView.java revision c2d256b41587ff44efb6373885affe02e5df80b5
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 // Update "old" cached values 6067 mOldMaximum = mMaximum; 6068 mOldMaxMode = mMaxMode; 6069 6070 mHighlightPathBogus = true; 6071 6072 if (w < 0) { 6073 w = 0; 6074 } 6075 if (hintWidth < 0) { 6076 hintWidth = 0; 6077 } 6078 6079 Layout.Alignment alignment = getLayoutAlignment(); 6080 boolean shouldEllipsize = mEllipsize != null && mInput == null; 6081 6082 if (mTextDir == null) { 6083 resolveTextDirection(); 6084 } 6085 if (mText instanceof Spannable) { 6086 mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w, 6087 alignment, mTextDir, mSpacingMult, 6088 mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null, 6089 ellipsisWidth); 6090 } else { 6091 if (boring == UNKNOWN_BORING) { 6092 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6093 if (boring != null) { 6094 mBoring = boring; 6095 } 6096 } 6097 6098 if (boring != null) { 6099 if (boring.width <= w && 6100 (mEllipsize == null || boring.width <= ellipsisWidth)) { 6101 if (mSavedLayout != null) { 6102 mLayout = mSavedLayout. 6103 replaceOrMake(mTransformed, mTextPaint, 6104 w, alignment, mSpacingMult, mSpacingAdd, 6105 boring, mIncludePad); 6106 } else { 6107 mLayout = BoringLayout.make(mTransformed, mTextPaint, 6108 w, alignment, mSpacingMult, mSpacingAdd, 6109 boring, mIncludePad); 6110 } 6111 6112 mSavedLayout = (BoringLayout) mLayout; 6113 } else if (shouldEllipsize && boring.width <= w) { 6114 if (mSavedLayout != null) { 6115 mLayout = mSavedLayout. 6116 replaceOrMake(mTransformed, mTextPaint, 6117 w, alignment, mSpacingMult, mSpacingAdd, 6118 boring, mIncludePad, mEllipsize, 6119 ellipsisWidth); 6120 } else { 6121 mLayout = BoringLayout.make(mTransformed, mTextPaint, 6122 w, alignment, mSpacingMult, mSpacingAdd, 6123 boring, mIncludePad, mEllipsize, 6124 ellipsisWidth); 6125 } 6126 } else if (shouldEllipsize) { 6127 mLayout = new StaticLayout(mTransformed, 6128 0, mTransformed.length(), 6129 mTextPaint, w, alignment, mTextDir, mSpacingMult, 6130 mSpacingAdd, mIncludePad, mEllipsize, 6131 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6132 } else { 6133 mLayout = new StaticLayout(mTransformed, mTextPaint, 6134 w, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6135 mIncludePad); 6136 } 6137 } else if (shouldEllipsize) { 6138 mLayout = new StaticLayout(mTransformed, 6139 0, mTransformed.length(), 6140 mTextPaint, w, alignment, mTextDir, mSpacingMult, 6141 mSpacingAdd, mIncludePad, mEllipsize, 6142 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6143 } else { 6144 mLayout = new StaticLayout(mTransformed, mTextPaint, 6145 w, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6146 mIncludePad); 6147 } 6148 } 6149 6150 shouldEllipsize = mEllipsize != null; 6151 mHintLayout = null; 6152 6153 if (mHint != null) { 6154 if (shouldEllipsize) hintWidth = w; 6155 6156 if (hintBoring == UNKNOWN_BORING) { 6157 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, 6158 mHintBoring); 6159 if (hintBoring != null) { 6160 mHintBoring = hintBoring; 6161 } 6162 } 6163 6164 if (hintBoring != null) { 6165 if (hintBoring.width <= hintWidth && 6166 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 6167 if (mSavedHintLayout != null) { 6168 mHintLayout = mSavedHintLayout. 6169 replaceOrMake(mHint, mTextPaint, 6170 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6171 hintBoring, mIncludePad); 6172 } else { 6173 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6174 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6175 hintBoring, mIncludePad); 6176 } 6177 6178 mSavedHintLayout = (BoringLayout) mHintLayout; 6179 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 6180 if (mSavedHintLayout != null) { 6181 mHintLayout = mSavedHintLayout. 6182 replaceOrMake(mHint, mTextPaint, 6183 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6184 hintBoring, mIncludePad, mEllipsize, 6185 ellipsisWidth); 6186 } else { 6187 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6188 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6189 hintBoring, mIncludePad, mEllipsize, 6190 ellipsisWidth); 6191 } 6192 } else if (shouldEllipsize) { 6193 mHintLayout = new StaticLayout(mHint, 6194 0, mHint.length(), 6195 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6196 mSpacingAdd, mIncludePad, mEllipsize, 6197 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6198 } else { 6199 mHintLayout = new StaticLayout(mHint, mTextPaint, 6200 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6201 mIncludePad); 6202 } 6203 } else if (shouldEllipsize) { 6204 mHintLayout = new StaticLayout(mHint, 6205 0, mHint.length(), 6206 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6207 mSpacingAdd, mIncludePad, mEllipsize, 6208 ellipsisWidth, mMaxMode == LINES ? mMaximum : Integer.MAX_VALUE); 6209 } else { 6210 mHintLayout = new StaticLayout(mHint, mTextPaint, 6211 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6212 mIncludePad); 6213 } 6214 } 6215 6216 if (bringIntoView) { 6217 registerForPreDraw(); 6218 } 6219 6220 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6221 if (!compressText(ellipsisWidth)) { 6222 final int height = mLayoutParams.height; 6223 // If the size of the view does not depend on the size of the text, try to 6224 // start the marquee immediately 6225 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 6226 startMarquee(); 6227 } else { 6228 // Defer the start of the marquee until we know our width (see setFrame()) 6229 mRestartMarquee = true; 6230 } 6231 } 6232 } 6233 6234 // CursorControllers need a non-null mLayout 6235 prepareCursorControllers(); 6236 } 6237 6238 private boolean compressText(float width) { 6239 if (isHardwareAccelerated()) return false; 6240 6241 // Only compress the text if it hasn't been compressed by the previous pass 6242 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 6243 mTextPaint.getTextScaleX() == 1.0f) { 6244 final float textWidth = mLayout.getLineWidth(0); 6245 final float overflow = (textWidth + 1.0f - width) / width; 6246 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 6247 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 6248 post(new Runnable() { 6249 public void run() { 6250 requestLayout(); 6251 } 6252 }); 6253 return true; 6254 } 6255 } 6256 6257 return false; 6258 } 6259 6260 private static int desired(Layout layout) { 6261 int n = layout.getLineCount(); 6262 CharSequence text = layout.getText(); 6263 float max = 0; 6264 6265 // if any line was wrapped, we can't use it. 6266 // but it's ok for the last line not to have a newline 6267 6268 for (int i = 0; i < n - 1; i++) { 6269 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 6270 return -1; 6271 } 6272 6273 for (int i = 0; i < n; i++) { 6274 max = Math.max(max, layout.getLineWidth(i)); 6275 } 6276 6277 return (int) FloatMath.ceil(max); 6278 } 6279 6280 /** 6281 * Set whether the TextView includes extra top and bottom padding to make 6282 * room for accents that go above the normal ascent and descent. 6283 * The default is true. 6284 * 6285 * @attr ref android.R.styleable#TextView_includeFontPadding 6286 */ 6287 public void setIncludeFontPadding(boolean includepad) { 6288 if (mIncludePad != includepad) { 6289 mIncludePad = includepad; 6290 6291 if (mLayout != null) { 6292 nullLayouts(); 6293 requestLayout(); 6294 invalidate(); 6295 } 6296 } 6297 } 6298 6299 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 6300 6301 @Override 6302 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6303 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6304 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6305 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6306 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6307 6308 int width; 6309 int height; 6310 6311 BoringLayout.Metrics boring = UNKNOWN_BORING; 6312 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 6313 6314 if (mTextDir == null) { 6315 resolveTextDirection(); 6316 } 6317 6318 int des = -1; 6319 boolean fromexisting = false; 6320 6321 if (widthMode == MeasureSpec.EXACTLY) { 6322 // Parent has told us how big to be. So be it. 6323 width = widthSize; 6324 } else { 6325 if (mLayout != null && mEllipsize == null) { 6326 des = desired(mLayout); 6327 } 6328 6329 if (des < 0) { 6330 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6331 if (boring != null) { 6332 mBoring = boring; 6333 } 6334 } else { 6335 fromexisting = true; 6336 } 6337 6338 if (boring == null || boring == UNKNOWN_BORING) { 6339 if (des < 0) { 6340 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 6341 } 6342 6343 width = des; 6344 } else { 6345 width = boring.width; 6346 } 6347 6348 final Drawables dr = mDrawables; 6349 if (dr != null) { 6350 width = Math.max(width, dr.mDrawableWidthTop); 6351 width = Math.max(width, dr.mDrawableWidthBottom); 6352 } 6353 6354 if (mHint != null) { 6355 int hintDes = -1; 6356 int hintWidth; 6357 6358 if (mHintLayout != null && mEllipsize == null) { 6359 hintDes = desired(mHintLayout); 6360 } 6361 6362 if (hintDes < 0) { 6363 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 6364 if (hintBoring != null) { 6365 mHintBoring = hintBoring; 6366 } 6367 } 6368 6369 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 6370 if (hintDes < 0) { 6371 hintDes = (int) FloatMath.ceil( 6372 Layout.getDesiredWidth(mHint, mTextPaint)); 6373 } 6374 6375 hintWidth = hintDes; 6376 } else { 6377 hintWidth = hintBoring.width; 6378 } 6379 6380 if (hintWidth > width) { 6381 width = hintWidth; 6382 } 6383 } 6384 6385 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 6386 6387 if (mMaxWidthMode == EMS) { 6388 width = Math.min(width, mMaxWidth * getLineHeight()); 6389 } else { 6390 width = Math.min(width, mMaxWidth); 6391 } 6392 6393 if (mMinWidthMode == EMS) { 6394 width = Math.max(width, mMinWidth * getLineHeight()); 6395 } else { 6396 width = Math.max(width, mMinWidth); 6397 } 6398 6399 // Check against our minimum width 6400 width = Math.max(width, getSuggestedMinimumWidth()); 6401 6402 if (widthMode == MeasureSpec.AT_MOST) { 6403 width = Math.min(widthSize, width); 6404 } 6405 } 6406 6407 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6408 int unpaddedWidth = want; 6409 6410 if (mHorizontallyScrolling) want = VERY_WIDE; 6411 6412 int hintWant = want; 6413 int hintWidth = (mHintLayout == null) ? hintWant : mHintLayout.getWidth(); 6414 6415 if (mLayout == null) { 6416 makeNewLayout(want, hintWant, boring, hintBoring, 6417 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6418 } else { 6419 final boolean layoutChanged = (mLayout.getWidth() != want) || 6420 (hintWidth != hintWant) || 6421 (mLayout.getEllipsizedWidth() != 6422 width - getCompoundPaddingLeft() - getCompoundPaddingRight()); 6423 6424 final boolean widthChanged = (mHint == null) && 6425 (mEllipsize == null) && 6426 (want > mLayout.getWidth()) && 6427 (mLayout instanceof BoringLayout || (fromexisting && des >= 0 && des <= want)); 6428 6429 final boolean maximumChanged = (mMaxMode != mOldMaxMode) || (mMaximum != mOldMaximum); 6430 6431 if (layoutChanged || maximumChanged) { 6432 if (!maximumChanged && widthChanged) { 6433 mLayout.increaseWidthTo(want); 6434 } else { 6435 makeNewLayout(want, hintWant, boring, hintBoring, 6436 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6437 } 6438 } else { 6439 // Nothing has changed 6440 } 6441 } 6442 6443 if (heightMode == MeasureSpec.EXACTLY) { 6444 // Parent has told us how big to be. So be it. 6445 height = heightSize; 6446 mDesiredHeightAtMeasure = -1; 6447 } else { 6448 int desired = getDesiredHeight(); 6449 6450 height = desired; 6451 mDesiredHeightAtMeasure = desired; 6452 6453 if (heightMode == MeasureSpec.AT_MOST) { 6454 height = Math.min(desired, heightSize); 6455 } 6456 } 6457 6458 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 6459 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 6460 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 6461 } 6462 6463 /* 6464 * We didn't let makeNewLayout() register to bring the cursor into view, 6465 * so do it here if there is any possibility that it is needed. 6466 */ 6467 if (mMovement != null || 6468 mLayout.getWidth() > unpaddedWidth || 6469 mLayout.getHeight() > unpaddedHeight) { 6470 registerForPreDraw(); 6471 } else { 6472 scrollTo(0, 0); 6473 } 6474 6475 setMeasuredDimension(width, height); 6476 } 6477 6478 private int getDesiredHeight() { 6479 return Math.max( 6480 getDesiredHeight(mLayout, true), 6481 getDesiredHeight(mHintLayout, mEllipsize != null)); 6482 } 6483 6484 private int getDesiredHeight(Layout layout, boolean cap) { 6485 if (layout == null) { 6486 return 0; 6487 } 6488 6489 int linecount = layout.getLineCount(); 6490 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 6491 int desired = layout.getLineTop(linecount); 6492 6493 final Drawables dr = mDrawables; 6494 if (dr != null) { 6495 desired = Math.max(desired, dr.mDrawableHeightLeft); 6496 desired = Math.max(desired, dr.mDrawableHeightRight); 6497 } 6498 6499 desired += pad; 6500 6501 if (mMaxMode == LINES) { 6502 /* 6503 * Don't cap the hint to a certain number of lines. 6504 * (Do cap it, though, if we have a maximum pixel height.) 6505 */ 6506 if (cap) { 6507 if (linecount > mMaximum) { 6508 desired = layout.getLineTop(mMaximum); 6509 6510 if (dr != null) { 6511 desired = Math.max(desired, dr.mDrawableHeightLeft); 6512 desired = Math.max(desired, dr.mDrawableHeightRight); 6513 } 6514 6515 desired += pad; 6516 linecount = mMaximum; 6517 } 6518 } 6519 } else { 6520 desired = Math.min(desired, mMaximum); 6521 } 6522 6523 if (mMinMode == LINES) { 6524 if (linecount < mMinimum) { 6525 desired += getLineHeight() * (mMinimum - linecount); 6526 } 6527 } else { 6528 desired = Math.max(desired, mMinimum); 6529 } 6530 6531 // Check against our minimum height 6532 desired = Math.max(desired, getSuggestedMinimumHeight()); 6533 6534 return desired; 6535 } 6536 6537 /** 6538 * Check whether a change to the existing text layout requires a 6539 * new view layout. 6540 */ 6541 private void checkForResize() { 6542 boolean sizeChanged = false; 6543 6544 if (mLayout != null) { 6545 // Check if our width changed 6546 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 6547 sizeChanged = true; 6548 invalidate(); 6549 } 6550 6551 // Check if our height changed 6552 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 6553 int desiredHeight = getDesiredHeight(); 6554 6555 if (desiredHeight != this.getHeight()) { 6556 sizeChanged = true; 6557 } 6558 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 6559 if (mDesiredHeightAtMeasure >= 0) { 6560 int desiredHeight = getDesiredHeight(); 6561 6562 if (desiredHeight != mDesiredHeightAtMeasure) { 6563 sizeChanged = true; 6564 } 6565 } 6566 } 6567 } 6568 6569 if (sizeChanged) { 6570 requestLayout(); 6571 // caller will have already invalidated 6572 } 6573 } 6574 6575 /** 6576 * Check whether entirely new text requires a new view layout 6577 * or merely a new text layout. 6578 */ 6579 private void checkForRelayout() { 6580 // If we have a fixed width, we can just swap in a new text layout 6581 // if the text height stays the same or if the view height is fixed. 6582 6583 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 6584 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 6585 (mHint == null || mHintLayout != null) && 6586 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 6587 // Static width, so try making a new text layout. 6588 6589 int oldht = mLayout.getHeight(); 6590 int want = mLayout.getWidth(); 6591 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 6592 6593 /* 6594 * No need to bring the text into view, since the size is not 6595 * changing (unless we do the requestLayout(), in which case it 6596 * will happen at measure). 6597 */ 6598 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 6599 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 6600 false); 6601 6602 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 6603 // In a fixed-height view, so use our new text layout. 6604 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 6605 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 6606 invalidate(); 6607 return; 6608 } 6609 6610 // Dynamic height, but height has stayed the same, 6611 // so use our new text layout. 6612 if (mLayout.getHeight() == oldht && 6613 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 6614 invalidate(); 6615 return; 6616 } 6617 } 6618 6619 // We lose: the height has changed and we have a dynamic height. 6620 // Request a new view layout using our new text layout. 6621 requestLayout(); 6622 invalidate(); 6623 } else { 6624 // Dynamic width, so we have no choice but to request a new 6625 // view layout with a new text layout. 6626 nullLayouts(); 6627 requestLayout(); 6628 invalidate(); 6629 } 6630 } 6631 6632 /** 6633 * Returns true if anything changed. 6634 */ 6635 private boolean bringTextIntoView() { 6636 int line = 0; 6637 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6638 line = mLayout.getLineCount() - 1; 6639 } 6640 6641 Layout.Alignment a = mLayout.getParagraphAlignment(line); 6642 int dir = mLayout.getParagraphDirection(line); 6643 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6644 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6645 int ht = mLayout.getHeight(); 6646 6647 int scrollx, scrolly; 6648 6649 // Convert to left, center, or right alignment. 6650 if (a == Layout.Alignment.ALIGN_NORMAL) { 6651 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT : 6652 Layout.Alignment.ALIGN_RIGHT; 6653 } else if (a == Layout.Alignment.ALIGN_OPPOSITE){ 6654 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT : 6655 Layout.Alignment.ALIGN_LEFT; 6656 } 6657 6658 if (a == Layout.Alignment.ALIGN_CENTER) { 6659 /* 6660 * Keep centered if possible, or, if it is too wide to fit, 6661 * keep leading edge in view. 6662 */ 6663 6664 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6665 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6666 6667 if (right - left < hspace) { 6668 scrollx = (right + left) / 2 - hspace / 2; 6669 } else { 6670 if (dir < 0) { 6671 scrollx = right - hspace; 6672 } else { 6673 scrollx = left; 6674 } 6675 } 6676 } else if (a == Layout.Alignment.ALIGN_RIGHT) { 6677 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6678 scrollx = right - hspace; 6679 } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) 6680 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6681 } 6682 6683 if (ht < vspace) { 6684 scrolly = 0; 6685 } else { 6686 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6687 scrolly = ht - vspace; 6688 } else { 6689 scrolly = 0; 6690 } 6691 } 6692 6693 if (scrollx != mScrollX || scrolly != mScrollY) { 6694 scrollTo(scrollx, scrolly); 6695 return true; 6696 } else { 6697 return false; 6698 } 6699 } 6700 6701 /** 6702 * Move the point, specified by the offset, into the view if it is needed. 6703 * This has to be called after layout. Returns true if anything changed. 6704 */ 6705 public boolean bringPointIntoView(int offset) { 6706 boolean changed = false; 6707 6708 if (mLayout == null) return changed; 6709 6710 int line = mLayout.getLineForOffset(offset); 6711 6712 // FIXME: Is it okay to truncate this, or should we round? 6713 final int x = (int)mLayout.getPrimaryHorizontal(offset); 6714 final int top = mLayout.getLineTop(line); 6715 final int bottom = mLayout.getLineTop(line + 1); 6716 6717 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6718 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6719 int ht = mLayout.getHeight(); 6720 6721 int grav; 6722 6723 switch (mLayout.getParagraphAlignment(line)) { 6724 case ALIGN_LEFT: 6725 grav = 1; 6726 break; 6727 case ALIGN_RIGHT: 6728 grav = -1; 6729 break; 6730 case ALIGN_NORMAL: 6731 grav = mLayout.getParagraphDirection(line); 6732 break; 6733 case ALIGN_OPPOSITE: 6734 grav = -mLayout.getParagraphDirection(line); 6735 break; 6736 case ALIGN_CENTER: 6737 default: 6738 grav = 0; 6739 break; 6740 } 6741 6742 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6743 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6744 6745 int hslack = (bottom - top) / 2; 6746 int vslack = hslack; 6747 6748 if (vslack > vspace / 4) 6749 vslack = vspace / 4; 6750 if (hslack > hspace / 4) 6751 hslack = hspace / 4; 6752 6753 int hs = mScrollX; 6754 int vs = mScrollY; 6755 6756 if (top - vs < vslack) 6757 vs = top - vslack; 6758 if (bottom - vs > vspace - vslack) 6759 vs = bottom - (vspace - vslack); 6760 if (ht - vs < vspace) 6761 vs = ht - vspace; 6762 if (0 - vs > 0) 6763 vs = 0; 6764 6765 if (grav != 0) { 6766 if (x - hs < hslack) { 6767 hs = x - hslack; 6768 } 6769 if (x - hs > hspace - hslack) { 6770 hs = x - (hspace - hslack); 6771 } 6772 } 6773 6774 if (grav < 0) { 6775 if (left - hs > 0) 6776 hs = left; 6777 if (right - hs < hspace) 6778 hs = right - hspace; 6779 } else if (grav > 0) { 6780 if (right - hs < hspace) 6781 hs = right - hspace; 6782 if (left - hs > 0) 6783 hs = left; 6784 } else /* grav == 0 */ { 6785 if (right - left <= hspace) { 6786 /* 6787 * If the entire text fits, center it exactly. 6788 */ 6789 hs = left - (hspace - (right - left)) / 2; 6790 } else if (x > right - hslack) { 6791 /* 6792 * If we are near the right edge, keep the right edge 6793 * at the edge of the view. 6794 */ 6795 hs = right - hspace; 6796 } else if (x < left + hslack) { 6797 /* 6798 * If we are near the left edge, keep the left edge 6799 * at the edge of the view. 6800 */ 6801 hs = left; 6802 } else if (left > hs) { 6803 /* 6804 * Is there whitespace visible at the left? Fix it if so. 6805 */ 6806 hs = left; 6807 } else if (right < hs + hspace) { 6808 /* 6809 * Is there whitespace visible at the right? Fix it if so. 6810 */ 6811 hs = right - hspace; 6812 } else { 6813 /* 6814 * Otherwise, float as needed. 6815 */ 6816 if (x - hs < hslack) { 6817 hs = x - hslack; 6818 } 6819 if (x - hs > hspace - hslack) { 6820 hs = x - (hspace - hslack); 6821 } 6822 } 6823 } 6824 6825 if (hs != mScrollX || vs != mScrollY) { 6826 if (mScroller == null) { 6827 scrollTo(hs, vs); 6828 } else { 6829 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6830 int dx = hs - mScrollX; 6831 int dy = vs - mScrollY; 6832 6833 if (duration > ANIMATED_SCROLL_GAP) { 6834 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6835 awakenScrollBars(mScroller.getDuration()); 6836 invalidate(); 6837 } else { 6838 if (!mScroller.isFinished()) { 6839 mScroller.abortAnimation(); 6840 } 6841 6842 scrollBy(dx, dy); 6843 } 6844 6845 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6846 } 6847 6848 changed = true; 6849 } 6850 6851 if (isFocused()) { 6852 // This offsets because getInterestingRect() is in terms of viewport coordinates, but 6853 // requestRectangleOnScreen() is in terms of content coordinates. 6854 6855 if (mTempRect == null) mTempRect = new Rect(); 6856 // The offsets here are to ensure the rectangle we are using is 6857 // within our view bounds, in case the cursor is on the far left 6858 // or right. If it isn't withing the bounds, then this request 6859 // will be ignored. 6860 mTempRect.set(x - 2, top, x + 2, bottom); 6861 getInterestingRect(mTempRect, line); 6862 mTempRect.offset(mScrollX, mScrollY); 6863 6864 if (requestRectangleOnScreen(mTempRect)) { 6865 changed = true; 6866 } 6867 } 6868 6869 return changed; 6870 } 6871 6872 /** 6873 * Move the cursor, if needed, so that it is at an offset that is visible 6874 * to the user. This will not move the cursor if it represents more than 6875 * one character (a selection range). This will only work if the 6876 * TextView contains spannable text; otherwise it will do nothing. 6877 * 6878 * @return True if the cursor was actually moved, false otherwise. 6879 */ 6880 public boolean moveCursorToVisibleOffset() { 6881 if (!(mText instanceof Spannable)) { 6882 return false; 6883 } 6884 int start = getSelectionStart(); 6885 int end = getSelectionEnd(); 6886 if (start != end) { 6887 return false; 6888 } 6889 6890 // First: make sure the line is visible on screen: 6891 6892 int line = mLayout.getLineForOffset(start); 6893 6894 final int top = mLayout.getLineTop(line); 6895 final int bottom = mLayout.getLineTop(line + 1); 6896 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6897 int vslack = (bottom - top) / 2; 6898 if (vslack > vspace / 4) 6899 vslack = vspace / 4; 6900 final int vs = mScrollY; 6901 6902 if (top < (vs+vslack)) { 6903 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 6904 } else if (bottom > (vspace+vs-vslack)) { 6905 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 6906 } 6907 6908 // Next: make sure the character is visible on screen: 6909 6910 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6911 final int hs = mScrollX; 6912 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 6913 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 6914 6915 // line might contain bidirectional text 6916 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 6917 final int highChar = leftChar > rightChar ? leftChar : rightChar; 6918 6919 int newStart = start; 6920 if (newStart < lowChar) { 6921 newStart = lowChar; 6922 } else if (newStart > highChar) { 6923 newStart = highChar; 6924 } 6925 6926 if (newStart != start) { 6927 Selection.setSelection((Spannable)mText, newStart); 6928 return true; 6929 } 6930 6931 return false; 6932 } 6933 6934 @Override 6935 public void computeScroll() { 6936 if (mScroller != null) { 6937 if (mScroller.computeScrollOffset()) { 6938 mScrollX = mScroller.getCurrX(); 6939 mScrollY = mScroller.getCurrY(); 6940 invalidateParentCaches(); 6941 postInvalidate(); // So we draw again 6942 } 6943 } 6944 } 6945 6946 private void getInterestingRect(Rect r, int line) { 6947 convertFromViewportToContentCoordinates(r); 6948 6949 // Rectangle can can be expanded on first and last line to take 6950 // padding into account. 6951 // TODO Take left/right padding into account too? 6952 if (line == 0) r.top -= getExtendedPaddingTop(); 6953 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 6954 } 6955 6956 private void convertFromViewportToContentCoordinates(Rect r) { 6957 final int horizontalOffset = viewportToContentHorizontalOffset(); 6958 r.left += horizontalOffset; 6959 r.right += horizontalOffset; 6960 6961 final int verticalOffset = viewportToContentVerticalOffset(); 6962 r.top += verticalOffset; 6963 r.bottom += verticalOffset; 6964 } 6965 6966 private int viewportToContentHorizontalOffset() { 6967 return getCompoundPaddingLeft() - mScrollX; 6968 } 6969 6970 private int viewportToContentVerticalOffset() { 6971 int offset = getExtendedPaddingTop() - mScrollY; 6972 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 6973 offset += getVerticalOffset(false); 6974 } 6975 return offset; 6976 } 6977 6978 @Override 6979 public void debug(int depth) { 6980 super.debug(depth); 6981 6982 String output = debugIndent(depth); 6983 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 6984 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 6985 + "} "; 6986 6987 if (mText != null) { 6988 6989 output += "mText=\"" + mText + "\" "; 6990 if (mLayout != null) { 6991 output += "mLayout width=" + mLayout.getWidth() 6992 + " height=" + mLayout.getHeight(); 6993 } 6994 } else { 6995 output += "mText=NULL"; 6996 } 6997 Log.d(VIEW_LOG_TAG, output); 6998 } 6999 7000 /** 7001 * Convenience for {@link Selection#getSelectionStart}. 7002 */ 7003 @ViewDebug.ExportedProperty(category = "text") 7004 public int getSelectionStart() { 7005 return Selection.getSelectionStart(getText()); 7006 } 7007 7008 /** 7009 * Convenience for {@link Selection#getSelectionEnd}. 7010 */ 7011 @ViewDebug.ExportedProperty(category = "text") 7012 public int getSelectionEnd() { 7013 return Selection.getSelectionEnd(getText()); 7014 } 7015 7016 /** 7017 * Return true iff there is a selection inside this text view. 7018 */ 7019 public boolean hasSelection() { 7020 final int selectionStart = getSelectionStart(); 7021 final int selectionEnd = getSelectionEnd(); 7022 7023 return selectionStart >= 0 && selectionStart != selectionEnd; 7024 } 7025 7026 /** 7027 * Sets the properties of this field (lines, horizontally scrolling, 7028 * transformation method) to be for a single-line input. 7029 * 7030 * @attr ref android.R.styleable#TextView_singleLine 7031 */ 7032 public void setSingleLine() { 7033 setSingleLine(true); 7034 } 7035 7036 /** 7037 * Sets the properties of this field to transform input to ALL CAPS 7038 * display. This may use a "small caps" formatting if available. 7039 * This setting will be ignored if this field is editable or selectable. 7040 * 7041 * This call replaces the current transformation method. Disabling this 7042 * will not necessarily restore the previous behavior from before this 7043 * was enabled. 7044 * 7045 * @see #setTransformationMethod(TransformationMethod) 7046 * @attr ref android.R.styleable#TextView_textAllCaps 7047 */ 7048 public void setAllCaps(boolean allCaps) { 7049 if (allCaps) { 7050 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 7051 } else { 7052 setTransformationMethod(null); 7053 } 7054 } 7055 7056 /** 7057 * If true, sets the properties of this field (number of lines, horizontally scrolling, 7058 * transformation method) to be for a single-line input; if false, restores these to the default 7059 * conditions. 7060 * 7061 * Note that the default conditions are not necessarily those that were in effect prior this 7062 * method, and you may want to reset these properties to your custom values. 7063 * 7064 * @attr ref android.R.styleable#TextView_singleLine 7065 */ 7066 @android.view.RemotableViewMethod 7067 public void setSingleLine(boolean singleLine) { 7068 // Could be used, but may break backward compatibility. 7069 // if (mSingleLine == singleLine) return; 7070 setInputTypeSingleLine(singleLine); 7071 applySingleLine(singleLine, true, true); 7072 } 7073 7074 /** 7075 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 7076 * @param singleLine 7077 */ 7078 private void setInputTypeSingleLine(boolean singleLine) { 7079 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 7080 if (singleLine) { 7081 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7082 } else { 7083 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7084 } 7085 } 7086 } 7087 7088 private void applySingleLine(boolean singleLine, boolean applyTransformation, 7089 boolean changeMaxLines) { 7090 mSingleLine = singleLine; 7091 if (singleLine) { 7092 setLines(1); 7093 setHorizontallyScrolling(true); 7094 if (applyTransformation) { 7095 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 7096 } 7097 } else { 7098 if (changeMaxLines) { 7099 setMaxLines(Integer.MAX_VALUE); 7100 } 7101 setHorizontallyScrolling(false); 7102 if (applyTransformation) { 7103 setTransformationMethod(null); 7104 } 7105 } 7106 } 7107 7108 /** 7109 * Causes words in the text that are longer than the view is wide 7110 * to be ellipsized instead of broken in the middle. You may also 7111 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 7112 * to constrain the text to a single line. Use <code>null</code> 7113 * to turn off ellipsizing. 7114 * 7115 * If {@link #setMaxLines} has been used to set two or more lines, 7116 * {@link TextUtils.TruncateAt#END} and {@link TextUtils.TruncateAt#MARQUEE} 7117 * are only supported (other ellipsizing types will not do anything). 7118 * 7119 * @attr ref android.R.styleable#TextView_ellipsize 7120 */ 7121 public void setEllipsize(TextUtils.TruncateAt where) { 7122 // TruncateAt is an enum. != comparison is ok between these singleton objects. 7123 if (mEllipsize != where) { 7124 mEllipsize = where; 7125 7126 if (mLayout != null) { 7127 nullLayouts(); 7128 requestLayout(); 7129 invalidate(); 7130 } 7131 } 7132 } 7133 7134 /** 7135 * Sets how many times to repeat the marquee animation. Only applied if the 7136 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 7137 * 7138 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 7139 */ 7140 public void setMarqueeRepeatLimit(int marqueeLimit) { 7141 mMarqueeRepeatLimit = marqueeLimit; 7142 } 7143 7144 /** 7145 * Returns where, if anywhere, words that are longer than the view 7146 * is wide should be ellipsized. 7147 */ 7148 @ViewDebug.ExportedProperty 7149 public TextUtils.TruncateAt getEllipsize() { 7150 return mEllipsize; 7151 } 7152 7153 /** 7154 * Set the TextView so that when it takes focus, all the text is 7155 * selected. 7156 * 7157 * @attr ref android.R.styleable#TextView_selectAllOnFocus 7158 */ 7159 @android.view.RemotableViewMethod 7160 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 7161 mSelectAllOnFocus = selectAllOnFocus; 7162 7163 if (selectAllOnFocus && !(mText instanceof Spannable)) { 7164 setText(mText, BufferType.SPANNABLE); 7165 } 7166 } 7167 7168 /** 7169 * Set whether the cursor is visible. The default is true. 7170 * 7171 * @attr ref android.R.styleable#TextView_cursorVisible 7172 */ 7173 @android.view.RemotableViewMethod 7174 public void setCursorVisible(boolean visible) { 7175 if (mCursorVisible != visible) { 7176 mCursorVisible = visible; 7177 invalidate(); 7178 7179 makeBlink(); 7180 7181 // InsertionPointCursorController depends on mCursorVisible 7182 prepareCursorControllers(); 7183 } 7184 } 7185 7186 private boolean isCursorVisible() { 7187 return mCursorVisible && isTextEditable(); 7188 } 7189 7190 private boolean canMarquee() { 7191 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 7192 return width > 0 && mLayout.getLineWidth(0) > width; 7193 } 7194 7195 private void startMarquee() { 7196 // Do not ellipsize EditText 7197 if (mInput != null) return; 7198 7199 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 7200 return; 7201 } 7202 7203 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 7204 getLineCount() == 1 && canMarquee()) { 7205 7206 if (mMarquee == null) mMarquee = new Marquee(this); 7207 mMarquee.start(mMarqueeRepeatLimit); 7208 } 7209 } 7210 7211 private void stopMarquee() { 7212 if (mMarquee != null && !mMarquee.isStopped()) { 7213 mMarquee.stop(); 7214 } 7215 } 7216 7217 private void startStopMarquee(boolean start) { 7218 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7219 if (start) { 7220 startMarquee(); 7221 } else { 7222 stopMarquee(); 7223 } 7224 } 7225 } 7226 7227 private static final class Marquee extends Handler { 7228 // TODO: Add an option to configure this 7229 private static final float MARQUEE_DELTA_MAX = 0.07f; 7230 private static final int MARQUEE_DELAY = 1200; 7231 private static final int MARQUEE_RESTART_DELAY = 1200; 7232 private static final int MARQUEE_RESOLUTION = 1000 / 30; 7233 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 7234 7235 private static final byte MARQUEE_STOPPED = 0x0; 7236 private static final byte MARQUEE_STARTING = 0x1; 7237 private static final byte MARQUEE_RUNNING = 0x2; 7238 7239 private static final int MESSAGE_START = 0x1; 7240 private static final int MESSAGE_TICK = 0x2; 7241 private static final int MESSAGE_RESTART = 0x3; 7242 7243 private final WeakReference<TextView> mView; 7244 7245 private byte mStatus = MARQUEE_STOPPED; 7246 private final float mScrollUnit; 7247 private float mMaxScroll; 7248 float mMaxFadeScroll; 7249 private float mGhostStart; 7250 private float mGhostOffset; 7251 private float mFadeStop; 7252 private int mRepeatLimit; 7253 7254 float mScroll; 7255 7256 Marquee(TextView v) { 7257 final float density = v.getContext().getResources().getDisplayMetrics().density; 7258 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 7259 mView = new WeakReference<TextView>(v); 7260 } 7261 7262 @Override 7263 public void handleMessage(Message msg) { 7264 switch (msg.what) { 7265 case MESSAGE_START: 7266 mStatus = MARQUEE_RUNNING; 7267 tick(); 7268 break; 7269 case MESSAGE_TICK: 7270 tick(); 7271 break; 7272 case MESSAGE_RESTART: 7273 if (mStatus == MARQUEE_RUNNING) { 7274 if (mRepeatLimit >= 0) { 7275 mRepeatLimit--; 7276 } 7277 start(mRepeatLimit); 7278 } 7279 break; 7280 } 7281 } 7282 7283 void tick() { 7284 if (mStatus != MARQUEE_RUNNING) { 7285 return; 7286 } 7287 7288 removeMessages(MESSAGE_TICK); 7289 7290 final TextView textView = mView.get(); 7291 if (textView != null && (textView.isFocused() || textView.isSelected())) { 7292 mScroll += mScrollUnit; 7293 if (mScroll > mMaxScroll) { 7294 mScroll = mMaxScroll; 7295 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 7296 } else { 7297 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 7298 } 7299 textView.invalidate(); 7300 } 7301 } 7302 7303 void stop() { 7304 mStatus = MARQUEE_STOPPED; 7305 removeMessages(MESSAGE_START); 7306 removeMessages(MESSAGE_RESTART); 7307 removeMessages(MESSAGE_TICK); 7308 resetScroll(); 7309 } 7310 7311 private void resetScroll() { 7312 mScroll = 0.0f; 7313 final TextView textView = mView.get(); 7314 if (textView != null) textView.invalidate(); 7315 } 7316 7317 void start(int repeatLimit) { 7318 if (repeatLimit == 0) { 7319 stop(); 7320 return; 7321 } 7322 mRepeatLimit = repeatLimit; 7323 final TextView textView = mView.get(); 7324 if (textView != null && textView.mLayout != null) { 7325 mStatus = MARQUEE_STARTING; 7326 mScroll = 0.0f; 7327 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 7328 textView.getCompoundPaddingRight(); 7329 final float lineWidth = textView.mLayout.getLineWidth(0); 7330 final float gap = textWidth / 3.0f; 7331 mGhostStart = lineWidth - textWidth + gap; 7332 mMaxScroll = mGhostStart + textWidth; 7333 mGhostOffset = lineWidth + gap; 7334 mFadeStop = lineWidth + textWidth / 6.0f; 7335 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 7336 7337 textView.invalidate(); 7338 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 7339 } 7340 } 7341 7342 float getGhostOffset() { 7343 return mGhostOffset; 7344 } 7345 7346 boolean shouldDrawLeftFade() { 7347 return mScroll <= mFadeStop; 7348 } 7349 7350 boolean shouldDrawGhost() { 7351 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 7352 } 7353 7354 boolean isRunning() { 7355 return mStatus == MARQUEE_RUNNING; 7356 } 7357 7358 boolean isStopped() { 7359 return mStatus == MARQUEE_STOPPED; 7360 } 7361 } 7362 7363 /** 7364 * This method is called when the text is changed, in case any subclasses 7365 * would like to know. 7366 * 7367 * Within <code>text</code>, the <code>lengthAfter</code> characters 7368 * beginning at <code>start</code> have just replaced old text that had 7369 * length <code>lengthBefore</code>. It is an error to attempt to make 7370 * changes to <code>text</code> from this callback. 7371 * 7372 * @param text The text the TextView is displaying 7373 * @param start The offset of the start of the range of the text that was 7374 * modified 7375 * @param lengthBefore The length of the former text that has been replaced 7376 * @param lengthAfter The length of the replacement modified text 7377 */ 7378 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 7379 // intentionally empty 7380 } 7381 7382 /** 7383 * This method is called when the selection has changed, in case any 7384 * subclasses would like to know. 7385 * 7386 * @param selStart The new selection start location. 7387 * @param selEnd The new selection end location. 7388 */ 7389 protected void onSelectionChanged(int selStart, int selEnd) { 7390 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7391 } 7392 7393 /** 7394 * Adds a TextWatcher to the list of those whose methods are called 7395 * whenever this TextView's text changes. 7396 * <p> 7397 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 7398 * not called after {@link #setText} calls. Now, doing {@link #setText} 7399 * if there are any text changed listeners forces the buffer type to 7400 * Editable if it would not otherwise be and does call this method. 7401 */ 7402 public void addTextChangedListener(TextWatcher watcher) { 7403 if (mListeners == null) { 7404 mListeners = new ArrayList<TextWatcher>(); 7405 } 7406 7407 mListeners.add(watcher); 7408 } 7409 7410 /** 7411 * Removes the specified TextWatcher from the list of those whose 7412 * methods are called 7413 * whenever this TextView's text changes. 7414 */ 7415 public void removeTextChangedListener(TextWatcher watcher) { 7416 if (mListeners != null) { 7417 int i = mListeners.indexOf(watcher); 7418 7419 if (i >= 0) { 7420 mListeners.remove(i); 7421 } 7422 } 7423 } 7424 7425 private void sendBeforeTextChanged(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).beforeTextChanged(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 sendOnTextChanged(CharSequence text, int start, int before, 7441 int after) { 7442 if (mListeners != null) { 7443 final ArrayList<TextWatcher> list = mListeners; 7444 final int count = list.size(); 7445 for (int i = 0; i < count; i++) { 7446 list.get(i).onTextChanged(text, start, before, after); 7447 } 7448 } 7449 } 7450 7451 /** 7452 * Not private so it can be called from an inner class without going 7453 * through a thunk. 7454 */ 7455 void sendAfterTextChanged(Editable text) { 7456 if (mListeners != null) { 7457 final ArrayList<TextWatcher> list = mListeners; 7458 final int count = list.size(); 7459 for (int i = 0; i < count; i++) { 7460 list.get(i).afterTextChanged(text); 7461 } 7462 } 7463 } 7464 7465 /** 7466 * Not private so it can be called from an inner class without going 7467 * through a thunk. 7468 */ 7469 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 7470 final InputMethodState ims = mInputMethodState; 7471 if (ims == null || ims.mBatchEditNesting == 0) { 7472 updateAfterEdit(); 7473 } 7474 if (ims != null) { 7475 ims.mContentChanged = true; 7476 if (ims.mChangedStart < 0) { 7477 ims.mChangedStart = start; 7478 ims.mChangedEnd = start+before; 7479 } else { 7480 ims.mChangedStart = Math.min(ims.mChangedStart, start); 7481 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 7482 } 7483 ims.mChangedDelta += after-before; 7484 } 7485 7486 sendOnTextChanged(buffer, start, before, after); 7487 onTextChanged(buffer, start, before, after); 7488 7489 // Hide the controllers if the amount of content changed 7490 if (before != after) { 7491 hideControllers(); 7492 } 7493 } 7494 7495 /** 7496 * Not private so it can be called from an inner class without going 7497 * through a thunk. 7498 */ 7499 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 7500 // XXX Make the start and end move together if this ends up 7501 // spending too much time invalidating. 7502 7503 boolean selChanged = false; 7504 int newSelStart=-1, newSelEnd=-1; 7505 7506 final InputMethodState ims = mInputMethodState; 7507 7508 if (what == Selection.SELECTION_END) { 7509 mHighlightPathBogus = true; 7510 selChanged = true; 7511 newSelEnd = newStart; 7512 7513 if (!isFocused()) { 7514 mSelectionMoved = true; 7515 } 7516 7517 if (oldStart >= 0 || newStart >= 0) { 7518 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 7519 registerForPreDraw(); 7520 makeBlink(); 7521 } 7522 } 7523 7524 if (what == Selection.SELECTION_START) { 7525 mHighlightPathBogus = true; 7526 selChanged = true; 7527 newSelStart = newStart; 7528 7529 if (!isFocused()) { 7530 mSelectionMoved = true; 7531 } 7532 7533 if (oldStart >= 0 || newStart >= 0) { 7534 int end = Selection.getSelectionEnd(buf); 7535 invalidateCursor(end, oldStart, newStart); 7536 } 7537 } 7538 7539 if (selChanged) { 7540 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 7541 if (newSelStart < 0) { 7542 newSelStart = Selection.getSelectionStart(buf); 7543 } 7544 if (newSelEnd < 0) { 7545 newSelEnd = Selection.getSelectionEnd(buf); 7546 } 7547 onSelectionChanged(newSelStart, newSelEnd); 7548 } 7549 } 7550 7551 if (what instanceof UpdateAppearance || 7552 what instanceof ParagraphStyle) { 7553 if (ims == null || ims.mBatchEditNesting == 0) { 7554 invalidate(); 7555 mHighlightPathBogus = true; 7556 checkForResize(); 7557 } else { 7558 ims.mContentChanged = true; 7559 } 7560 } 7561 7562 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 7563 mHighlightPathBogus = true; 7564 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 7565 ims.mSelectionModeChanged = true; 7566 } 7567 7568 if (Selection.getSelectionStart(buf) >= 0) { 7569 if (ims == null || ims.mBatchEditNesting == 0) { 7570 invalidateCursor(); 7571 } else { 7572 ims.mCursorChanged = true; 7573 } 7574 } 7575 } 7576 7577 if (what instanceof ParcelableSpan) { 7578 // If this is a span that can be sent to a remote process, 7579 // the current extract editor would be interested in it. 7580 if (ims != null && ims.mExtracting != null) { 7581 if (ims.mBatchEditNesting != 0) { 7582 if (oldStart >= 0) { 7583 if (ims.mChangedStart > oldStart) { 7584 ims.mChangedStart = oldStart; 7585 } 7586 if (ims.mChangedStart > oldEnd) { 7587 ims.mChangedStart = oldEnd; 7588 } 7589 } 7590 if (newStart >= 0) { 7591 if (ims.mChangedStart > newStart) { 7592 ims.mChangedStart = newStart; 7593 } 7594 if (ims.mChangedStart > newEnd) { 7595 ims.mChangedStart = newEnd; 7596 } 7597 } 7598 } else { 7599 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 7600 + oldStart + "-" + oldEnd + "," 7601 + newStart + "-" + newEnd + what); 7602 ims.mContentChanged = true; 7603 } 7604 } 7605 } 7606 } 7607 7608 private class ChangeWatcher 7609 implements TextWatcher, SpanWatcher { 7610 7611 private CharSequence mBeforeText; 7612 7613 public void beforeTextChanged(CharSequence buffer, int start, 7614 int before, int after) { 7615 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 7616 + " before=" + before + " after=" + after + ": " + buffer); 7617 7618 if (AccessibilityManager.getInstance(mContext).isEnabled() 7619 && !isPasswordInputType(mInputType) 7620 && !hasPasswordTransformationMethod()) { 7621 mBeforeText = buffer.toString(); 7622 } 7623 7624 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 7625 } 7626 7627 public void onTextChanged(CharSequence buffer, int start, 7628 int before, int after) { 7629 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 7630 + " before=" + before + " after=" + after + ": " + buffer); 7631 TextView.this.handleTextChanged(buffer, start, before, after); 7632 7633 if (AccessibilityManager.getInstance(mContext).isEnabled() && 7634 (isFocused() || isSelected() && 7635 isShown())) { 7636 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 7637 mBeforeText = null; 7638 } 7639 } 7640 7641 public void afterTextChanged(Editable buffer) { 7642 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 7643 TextView.this.sendAfterTextChanged(buffer); 7644 7645 if (MetaKeyKeyListener.getMetaState(buffer, 7646 MetaKeyKeyListener.META_SELECTING) != 0) { 7647 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 7648 } 7649 } 7650 7651 public void onSpanChanged(Spannable buf, 7652 Object what, int s, int e, int st, int en) { 7653 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 7654 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 7655 TextView.this.spanChange(buf, what, s, st, e, en); 7656 } 7657 7658 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 7659 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 7660 + " what=" + what + ": " + buf); 7661 TextView.this.spanChange(buf, what, -1, s, -1, e); 7662 } 7663 7664 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 7665 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 7666 + " what=" + what + ": " + buf); 7667 TextView.this.spanChange(buf, what, s, -1, e, -1); 7668 } 7669 } 7670 7671 /** 7672 * @hide 7673 */ 7674 @Override 7675 public void dispatchFinishTemporaryDetach() { 7676 mDispatchTemporaryDetach = true; 7677 super.dispatchFinishTemporaryDetach(); 7678 mDispatchTemporaryDetach = false; 7679 } 7680 7681 @Override 7682 public void onStartTemporaryDetach() { 7683 super.onStartTemporaryDetach(); 7684 // Only track when onStartTemporaryDetach() is called directly, 7685 // usually because this instance is an editable field in a list 7686 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 7687 7688 // Because of View recycling in ListView, there is no easy way to know when a TextView with 7689 // selection becomes visible again. Until a better solution is found, stop text selection 7690 // mode (if any) as soon as this TextView is recycled. 7691 hideControllers(); 7692 } 7693 7694 @Override 7695 public void onFinishTemporaryDetach() { 7696 super.onFinishTemporaryDetach(); 7697 // Only track when onStartTemporaryDetach() is called directly, 7698 // usually because this instance is an editable field in a list 7699 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 7700 } 7701 7702 @Override 7703 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 7704 if (mTemporaryDetach) { 7705 // If we are temporarily in the detach state, then do nothing. 7706 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7707 return; 7708 } 7709 7710 mShowCursor = SystemClock.uptimeMillis(); 7711 7712 ensureEndedBatchEdit(); 7713 7714 if (focused) { 7715 int selStart = getSelectionStart(); 7716 int selEnd = getSelectionEnd(); 7717 7718 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 7719 // mode for these, unless there was a specific selection already started. 7720 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 7721 selEnd == mText.length(); 7722 mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted; 7723 7724 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 7725 // If a tap was used to give focus to that view, move cursor at tap position. 7726 // Has to be done before onTakeFocus, which can be overloaded. 7727 final int lastTapPosition = getLastTapPosition(); 7728 if (lastTapPosition >= 0) { 7729 Selection.setSelection((Spannable) mText, lastTapPosition); 7730 } 7731 7732 if (mMovement != null) { 7733 mMovement.onTakeFocus(this, (Spannable) mText, direction); 7734 } 7735 7736 // The DecorView does not have focus when the 'Done' ExtractEditText button is 7737 // pressed. Since it is the ViewAncestor's mView, it requests focus before 7738 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 7739 // This special case ensure that we keep current selection in that case. 7740 // It would be better to know why the DecorView does not have focus at that time. 7741 if (((this instanceof ExtractEditText) || mSelectionMoved) && 7742 selStart >= 0 && selEnd >= 0) { 7743 /* 7744 * Someone intentionally set the selection, so let them 7745 * do whatever it is that they wanted to do instead of 7746 * the default on-focus behavior. We reset the selection 7747 * here instead of just skipping the onTakeFocus() call 7748 * because some movement methods do something other than 7749 * just setting the selection in theirs and we still 7750 * need to go through that path. 7751 */ 7752 Selection.setSelection((Spannable) mText, selStart, selEnd); 7753 } 7754 7755 if (mSelectAllOnFocus) { 7756 selectAll(); 7757 } 7758 7759 mTouchFocusSelected = true; 7760 } 7761 7762 mFrozenWithFocus = false; 7763 mSelectionMoved = false; 7764 7765 if (mText instanceof Spannable) { 7766 Spannable sp = (Spannable) mText; 7767 MetaKeyKeyListener.resetMetaState(sp); 7768 } 7769 7770 makeBlink(); 7771 7772 if (mError != null) { 7773 showError(); 7774 } 7775 } else { 7776 if (mError != null) { 7777 hideError(); 7778 } 7779 // Don't leave us in the middle of a batch edit. 7780 onEndBatchEdit(); 7781 7782 if (this instanceof ExtractEditText) { 7783 // terminateTextSelectionMode removes selection, which we want to keep when 7784 // ExtractEditText goes out of focus. 7785 final int selStart = getSelectionStart(); 7786 final int selEnd = getSelectionEnd(); 7787 hideControllers(); 7788 Selection.setSelection((Spannable) mText, selStart, selEnd); 7789 } else { 7790 hideControllers(); 7791 } 7792 7793 // No need to create the controller 7794 if (mSelectionModifierCursorController != null) { 7795 mSelectionModifierCursorController.resetTouchOffsets(); 7796 } 7797 } 7798 7799 startStopMarquee(focused); 7800 7801 if (mTransformation != null) { 7802 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 7803 } 7804 7805 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7806 } 7807 7808 private int getLastTapPosition() { 7809 // No need to create the controller at that point, no last tap position saved 7810 if (mSelectionModifierCursorController != null) { 7811 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 7812 if (lastTapPosition >= 0) { 7813 // Safety check, should not be possible. 7814 if (lastTapPosition > mText.length()) { 7815 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 7816 + mText.length() + ")"); 7817 lastTapPosition = mText.length(); 7818 } 7819 return lastTapPosition; 7820 } 7821 } 7822 7823 return -1; 7824 } 7825 7826 @Override 7827 public void onWindowFocusChanged(boolean hasWindowFocus) { 7828 super.onWindowFocusChanged(hasWindowFocus); 7829 7830 if (hasWindowFocus) { 7831 if (mBlink != null) { 7832 mBlink.uncancel(); 7833 makeBlink(); 7834 } 7835 } else { 7836 if (mBlink != null) { 7837 mBlink.cancel(); 7838 } 7839 // Don't leave us in the middle of a batch edit. 7840 onEndBatchEdit(); 7841 if (mInputContentType != null) { 7842 mInputContentType.enterDown = false; 7843 } 7844 hideControllers(); 7845 removeAllSuggestionSpans(); 7846 } 7847 7848 startStopMarquee(hasWindowFocus); 7849 } 7850 7851 private void removeAllSuggestionSpans() { 7852 if (mText instanceof Editable) { 7853 Editable editable = ((Editable) mText); 7854 SuggestionSpan[] spans = editable.getSpans(0, mText.length(), SuggestionSpan.class); 7855 final int length = spans.length; 7856 for (int i = 0; i < length; i++) { 7857 editable.removeSpan(spans[i]); 7858 } 7859 } 7860 } 7861 7862 @Override 7863 protected void onVisibilityChanged(View changedView, int visibility) { 7864 super.onVisibilityChanged(changedView, visibility); 7865 if (visibility != VISIBLE) { 7866 hideControllers(); 7867 } 7868 } 7869 7870 /** 7871 * Use {@link BaseInputConnection#removeComposingSpans 7872 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 7873 * state from this text view. 7874 */ 7875 public void clearComposingText() { 7876 if (mText instanceof Spannable) { 7877 BaseInputConnection.removeComposingSpans((Spannable)mText); 7878 } 7879 } 7880 7881 @Override 7882 public void setSelected(boolean selected) { 7883 boolean wasSelected = isSelected(); 7884 7885 super.setSelected(selected); 7886 7887 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7888 if (selected) { 7889 startMarquee(); 7890 } else { 7891 stopMarquee(); 7892 } 7893 } 7894 } 7895 7896 @Override 7897 public boolean onTouchEvent(MotionEvent event) { 7898 final int action = event.getActionMasked(); 7899 7900 if (hasSelectionController()) { 7901 getSelectionController().onTouchEvent(event); 7902 } 7903 7904 if (action == MotionEvent.ACTION_DOWN) { 7905 mLastDownPositionX = event.getX(); 7906 mLastDownPositionY = event.getY(); 7907 7908 // Reset this state; it will be re-set if super.onTouchEvent 7909 // causes focus to move to the view. 7910 mTouchFocusSelected = false; 7911 mIgnoreActionUpEvent = false; 7912 } 7913 7914 final boolean superResult = super.onTouchEvent(event); 7915 7916 /* 7917 * Don't handle the release after a long press, because it will 7918 * move the selection away from whatever the menu action was 7919 * trying to affect. 7920 */ 7921 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 7922 mDiscardNextActionUp = false; 7923 return superResult; 7924 } 7925 7926 final boolean touchIsFinished = action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && 7927 isFocused(); 7928 7929 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 7930 && mText instanceof Spannable && mLayout != null) { 7931 boolean handled = false; 7932 7933 if (mMovement != null) { 7934 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 7935 } 7936 7937 if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable && touchIsFinished) { 7938 // The LinkMovementMethod which should handle taps on links has not been installed 7939 // to support text selection. We reproduce its behavior here to open links. 7940 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 7941 getSelectionEnd(), ClickableSpan.class); 7942 7943 if (links.length != 0) { 7944 links[0].onClick(this); 7945 handled = true; 7946 } 7947 } 7948 7949 if ((isTextEditable() || mTextIsSelectable) && touchIsFinished) { 7950 // Show the IME, except when selecting in read-only text. 7951 final InputMethodManager imm = InputMethodManager.peekInstance(); 7952 if (imm != null) { 7953 imm.viewClicked(this); 7954 } 7955 if (!mTextIsSelectable) { 7956 handled |= imm != null && imm.showSoftInput(this, 0); 7957 } 7958 7959 boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect(); 7960 if (!selectAllGotFocus && hasSelection()) { 7961 startSelectionActionMode(); 7962 } else { 7963 hideControllers(); 7964 if (!selectAllGotFocus && mText.length() > 0) { 7965 if (isCursorInsideEasyCorrectionSpan()) { 7966 showSuggestions(); 7967 } else if (hasInsertionController()) { 7968 getInsertionController().show(); 7969 } 7970 } 7971 } 7972 } 7973 7974 if (handled) { 7975 return true; 7976 } 7977 } 7978 7979 return superResult; 7980 } 7981 7982 /** 7983 * @return <code>true</code> if the cursor is inside an {@link SuggestionSpan} with 7984 * {@link SuggestionSpan#FLAG_EASY_CORRECT} set. 7985 */ 7986 private boolean isCursorInsideEasyCorrectionSpan() { 7987 Spannable spannable = (Spannable) TextView.this.mText; 7988 SuggestionSpan[] suggestionSpans = spannable.getSpans(getSelectionStart(), 7989 getSelectionEnd(), SuggestionSpan.class); 7990 for (int i = 0; i < suggestionSpans.length; i++) { 7991 if ((suggestionSpans[i].getFlags() & SuggestionSpan.FLAG_EASY_CORRECT) != 0) { 7992 return true; 7993 } 7994 } 7995 return false; 7996 } 7997 7998 @Override 7999 public boolean onGenericMotionEvent(MotionEvent event) { 8000 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 8001 try { 8002 if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { 8003 return true; 8004 } 8005 } catch (AbstractMethodError ex) { 8006 // onGenericMotionEvent was added to the MovementMethod interface in API 12. 8007 // Ignore its absence in case third party applications implemented the 8008 // interface directly. 8009 } 8010 } 8011 return super.onGenericMotionEvent(event); 8012 } 8013 8014 private void prepareCursorControllers() { 8015 boolean windowSupportsHandles = false; 8016 8017 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 8018 if (params instanceof WindowManager.LayoutParams) { 8019 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 8020 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 8021 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 8022 } 8023 8024 mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null; 8025 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 8026 mLayout != null; 8027 8028 if (!mInsertionControllerEnabled) { 8029 hideInsertionPointCursorController(); 8030 if (mInsertionPointCursorController != null) { 8031 mInsertionPointCursorController.onDetached(); 8032 mInsertionPointCursorController = null; 8033 } 8034 } 8035 8036 if (!mSelectionControllerEnabled) { 8037 stopSelectionActionMode(); 8038 if (mSelectionModifierCursorController != null) { 8039 mSelectionModifierCursorController.onDetached(); 8040 mSelectionModifierCursorController = null; 8041 } 8042 } 8043 } 8044 8045 /** 8046 * @return True iff this TextView contains a text that can be edited, or if this is 8047 * a selectable TextView. 8048 */ 8049 private boolean isTextEditable() { 8050 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 8051 } 8052 8053 /** 8054 * Returns true, only while processing a touch gesture, if the initial 8055 * touch down event caused focus to move to the text view and as a result 8056 * its selection changed. Only valid while processing the touch gesture 8057 * of interest. 8058 */ 8059 public boolean didTouchFocusSelect() { 8060 return mTouchFocusSelected; 8061 } 8062 8063 @Override 8064 public void cancelLongPress() { 8065 super.cancelLongPress(); 8066 mIgnoreActionUpEvent = true; 8067 } 8068 8069 @Override 8070 public boolean onTrackballEvent(MotionEvent event) { 8071 if (mMovement != null && mText instanceof Spannable && 8072 mLayout != null) { 8073 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 8074 return true; 8075 } 8076 } 8077 8078 return super.onTrackballEvent(event); 8079 } 8080 8081 public void setScroller(Scroller s) { 8082 mScroller = s; 8083 } 8084 8085 private static class Blink extends Handler implements Runnable { 8086 private final WeakReference<TextView> mView; 8087 private boolean mCancelled; 8088 8089 public Blink(TextView v) { 8090 mView = new WeakReference<TextView>(v); 8091 } 8092 8093 public void run() { 8094 if (mCancelled) { 8095 return; 8096 } 8097 8098 removeCallbacks(Blink.this); 8099 8100 TextView tv = mView.get(); 8101 8102 if (tv != null && tv.shouldBlink()) { 8103 if (tv.mLayout != null) { 8104 tv.invalidateCursorPath(); 8105 } 8106 8107 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 8108 } 8109 } 8110 8111 void cancel() { 8112 if (!mCancelled) { 8113 removeCallbacks(Blink.this); 8114 mCancelled = true; 8115 } 8116 } 8117 8118 void uncancel() { 8119 mCancelled = false; 8120 } 8121 } 8122 8123 /** 8124 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 8125 */ 8126 private boolean shouldBlink() { 8127 if (!isFocused()) return false; 8128 8129 final int start = getSelectionStart(); 8130 if (start < 0) return false; 8131 8132 final int end = getSelectionEnd(); 8133 if (end < 0) return false; 8134 8135 return start == end; 8136 } 8137 8138 private void makeBlink() { 8139 if (isCursorVisible()) { 8140 if (shouldBlink()) { 8141 mShowCursor = SystemClock.uptimeMillis(); 8142 if (mBlink == null) mBlink = new Blink(this); 8143 mBlink.removeCallbacks(mBlink); 8144 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 8145 } 8146 } else { 8147 if (mBlink != null) mBlink.removeCallbacks(mBlink); 8148 } 8149 } 8150 8151 @Override 8152 protected float getLeftFadingEdgeStrength() { 8153 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8154 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 8155 if (mMarquee != null && !mMarquee.isStopped()) { 8156 final Marquee marquee = mMarquee; 8157 if (marquee.shouldDrawLeftFade()) { 8158 return marquee.mScroll / getHorizontalFadingEdgeLength(); 8159 } else { 8160 return 0.0f; 8161 } 8162 } else if (getLineCount() == 1) { 8163 final int layoutDirection = getResolvedLayoutDirection(); 8164 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8165 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8166 case Gravity.LEFT: 8167 return 0.0f; 8168 case Gravity.RIGHT: 8169 return (mLayout.getLineRight(0) - (mRight - mLeft) - 8170 getCompoundPaddingLeft() - getCompoundPaddingRight() - 8171 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 8172 case Gravity.CENTER_HORIZONTAL: 8173 return 0.0f; 8174 } 8175 } 8176 } 8177 return super.getLeftFadingEdgeStrength(); 8178 } 8179 8180 @Override 8181 protected float getRightFadingEdgeStrength() { 8182 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8183 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 8184 if (mMarquee != null && !mMarquee.isStopped()) { 8185 final Marquee marquee = mMarquee; 8186 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 8187 } else if (getLineCount() == 1) { 8188 final int layoutDirection = getResolvedLayoutDirection(); 8189 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8190 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8191 case Gravity.LEFT: 8192 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 8193 getCompoundPaddingRight(); 8194 final float lineWidth = mLayout.getLineWidth(0); 8195 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 8196 case Gravity.RIGHT: 8197 return 0.0f; 8198 case Gravity.CENTER_HORIZONTAL: 8199 case Gravity.FILL_HORIZONTAL: 8200 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 8201 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 8202 getHorizontalFadingEdgeLength(); 8203 } 8204 } 8205 } 8206 return super.getRightFadingEdgeStrength(); 8207 } 8208 8209 @Override 8210 protected int computeHorizontalScrollRange() { 8211 if (mLayout != null) { 8212 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 8213 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 8214 } 8215 8216 return super.computeHorizontalScrollRange(); 8217 } 8218 8219 @Override 8220 protected int computeVerticalScrollRange() { 8221 if (mLayout != null) 8222 return mLayout.getHeight(); 8223 8224 return super.computeVerticalScrollRange(); 8225 } 8226 8227 @Override 8228 protected int computeVerticalScrollExtent() { 8229 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 8230 } 8231 8232 @Override 8233 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched) { 8234 if (TextUtils.isEmpty(searched)) { 8235 return; 8236 } 8237 CharSequence thisText = getText(); 8238 if (TextUtils.isEmpty(thisText)) { 8239 return; 8240 } 8241 String searchedLowerCase = searched.toString().toLowerCase(); 8242 String thisTextLowerCase = thisText.toString().toLowerCase(); 8243 if (thisTextLowerCase.contains(searchedLowerCase)) { 8244 outViews.add(this); 8245 } 8246 } 8247 8248 public enum BufferType { 8249 NORMAL, SPANNABLE, EDITABLE, 8250 } 8251 8252 /** 8253 * Returns the TextView_textColor attribute from the 8254 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 8255 * from the TextView_textAppearance attribute, if TextView_textColor 8256 * was not set directly. 8257 */ 8258 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 8259 ColorStateList colors; 8260 colors = attrs.getColorStateList(com.android.internal.R.styleable. 8261 TextView_textColor); 8262 8263 if (colors == null) { 8264 int ap = attrs.getResourceId(com.android.internal.R.styleable. 8265 TextView_textAppearance, -1); 8266 if (ap != -1) { 8267 TypedArray appearance; 8268 appearance = context.obtainStyledAttributes(ap, 8269 com.android.internal.R.styleable.TextAppearance); 8270 colors = appearance.getColorStateList(com.android.internal.R.styleable. 8271 TextAppearance_textColor); 8272 appearance.recycle(); 8273 } 8274 } 8275 8276 return colors; 8277 } 8278 8279 /** 8280 * Returns the default color from the TextView_textColor attribute 8281 * from the AttributeSet, if set, or the default color from the 8282 * TextAppearance_textColor from the TextView_textAppearance attribute, 8283 * if TextView_textColor was not set directly. 8284 */ 8285 public static int getTextColor(Context context, 8286 TypedArray attrs, 8287 int def) { 8288 ColorStateList colors = getTextColors(context, attrs); 8289 8290 if (colors == null) { 8291 return def; 8292 } else { 8293 return colors.getDefaultColor(); 8294 } 8295 } 8296 8297 @Override 8298 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8299 final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; 8300 if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { 8301 switch (keyCode) { 8302 case KeyEvent.KEYCODE_A: 8303 if (canSelectText()) { 8304 return onTextContextMenuItem(ID_SELECT_ALL); 8305 } 8306 break; 8307 case KeyEvent.KEYCODE_X: 8308 if (canCut()) { 8309 return onTextContextMenuItem(ID_CUT); 8310 } 8311 break; 8312 case KeyEvent.KEYCODE_C: 8313 if (canCopy()) { 8314 return onTextContextMenuItem(ID_COPY); 8315 } 8316 break; 8317 case KeyEvent.KEYCODE_V: 8318 if (canPaste()) { 8319 return onTextContextMenuItem(ID_PASTE); 8320 } 8321 break; 8322 } 8323 } 8324 return super.onKeyShortcut(keyCode, event); 8325 } 8326 8327 /** 8328 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 8329 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 8330 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 8331 */ 8332 private boolean canSelectText() { 8333 return hasSelectionController() && mText.length() != 0; 8334 } 8335 8336 /** 8337 * Test based on the <i>intrinsic</i> charateristics of the TextView. 8338 * The text must be spannable and the movement method must allow for arbitary selection. 8339 * 8340 * See also {@link #canSelectText()}. 8341 */ 8342 private boolean textCanBeSelected() { 8343 // prepareCursorController() relies on this method. 8344 // If you change this condition, make sure prepareCursorController is called anywhere 8345 // the value of this condition might be changed. 8346 if (mMovement == null || !mMovement.canSelectArbitrarily()) return false; 8347 return isTextEditable() || (mTextIsSelectable && mText instanceof Spannable && isEnabled()); 8348 } 8349 8350 private boolean canCut() { 8351 if (hasPasswordTransformationMethod()) { 8352 return false; 8353 } 8354 8355 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 8356 return true; 8357 } 8358 8359 return false; 8360 } 8361 8362 private boolean canCopy() { 8363 if (hasPasswordTransformationMethod()) { 8364 return false; 8365 } 8366 8367 if (mText.length() > 0 && hasSelection()) { 8368 return true; 8369 } 8370 8371 return false; 8372 } 8373 8374 private boolean canPaste() { 8375 return (mText instanceof Editable && 8376 mInput != null && 8377 getSelectionStart() >= 0 && 8378 getSelectionEnd() >= 0 && 8379 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 8380 hasPrimaryClip()); 8381 } 8382 8383 private static long packRangeInLong(int start, int end) { 8384 return (((long) start) << 32) | end; 8385 } 8386 8387 private static int extractRangeStartFromLong(long range) { 8388 return (int) (range >>> 32); 8389 } 8390 8391 private static int extractRangeEndFromLong(long range) { 8392 return (int) (range & 0x00000000FFFFFFFFL); 8393 } 8394 8395 private boolean selectAll() { 8396 final int length = mText.length(); 8397 Selection.setSelection((Spannable) mText, 0, length); 8398 return length > 0; 8399 } 8400 8401 /** 8402 * Adjusts selection to the word under last touch offset. 8403 * Return true if the operation was successfully performed. 8404 */ 8405 private boolean selectCurrentWord() { 8406 if (!canSelectText()) { 8407 return false; 8408 } 8409 8410 if (hasPasswordTransformationMethod()) { 8411 // Always select all on a password field. 8412 // Cut/copy menu entries are not available for passwords, but being able to select all 8413 // is however useful to delete or paste to replace the entire content. 8414 return selectAll(); 8415 } 8416 8417 int klass = mInputType & InputType.TYPE_MASK_CLASS; 8418 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 8419 8420 // Specific text field types: select the entire text for these 8421 if (klass == InputType.TYPE_CLASS_NUMBER || 8422 klass == InputType.TYPE_CLASS_PHONE || 8423 klass == InputType.TYPE_CLASS_DATETIME || 8424 variation == InputType.TYPE_TEXT_VARIATION_URI || 8425 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 8426 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 8427 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 8428 return selectAll(); 8429 } 8430 8431 long lastTouchOffsets = getLastTouchOffsets(); 8432 final int minOffset = extractRangeStartFromLong(lastTouchOffsets); 8433 final int maxOffset = extractRangeEndFromLong(lastTouchOffsets); 8434 8435 // Safety check in case standard touch event handling has been bypassed 8436 if (minOffset < 0 || minOffset >= mText.length()) return false; 8437 if (maxOffset < 0 || maxOffset >= mText.length()) return false; 8438 8439 int selectionStart, selectionEnd; 8440 8441 // If a URLSpan (web address, email, phone...) is found at that position, select it. 8442 URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class); 8443 if (urlSpans.length == 1) { 8444 URLSpan url = urlSpans[0]; 8445 selectionStart = ((Spanned) mText).getSpanStart(url); 8446 selectionEnd = ((Spanned) mText).getSpanEnd(url); 8447 } else { 8448 if (mWordIterator == null) { 8449 mWordIterator = new WordIterator(); 8450 } 8451 // WordIerator handles text changes, this is a no-op if text in unchanged. 8452 mWordIterator.setCharSequence(mText); 8453 8454 selectionStart = mWordIterator.getBeginning(minOffset); 8455 if (selectionStart == BreakIterator.DONE) return false; 8456 8457 selectionEnd = mWordIterator.getEnd(maxOffset); 8458 if (selectionEnd == BreakIterator.DONE) return false; 8459 } 8460 8461 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8462 return true; 8463 } 8464 8465 private long getLastTouchOffsets() { 8466 int minOffset, maxOffset; 8467 8468 if (mContextMenuTriggeredByKey) { 8469 minOffset = getSelectionStart(); 8470 maxOffset = getSelectionEnd(); 8471 } else { 8472 SelectionModifierCursorController selectionController = getSelectionController(); 8473 minOffset = selectionController.getMinTouchOffset(); 8474 maxOffset = selectionController.getMaxTouchOffset(); 8475 } 8476 8477 return packRangeInLong(minOffset, maxOffset); 8478 } 8479 8480 @Override 8481 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 8482 super.onPopulateAccessibilityEvent(event); 8483 8484 final boolean isPassword = hasPasswordTransformationMethod(); 8485 if (!isPassword) { 8486 CharSequence text = getText(); 8487 if (TextUtils.isEmpty(text)) { 8488 text = getHint(); 8489 } 8490 if (TextUtils.isEmpty(text)) { 8491 text = getContentDescription(); 8492 } 8493 if (!TextUtils.isEmpty(text)) { 8494 event.getText().add(text); 8495 } 8496 } 8497 } 8498 8499 @Override 8500 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 8501 super.onInitializeAccessibilityEvent(event); 8502 8503 final boolean isPassword = hasPasswordTransformationMethod(); 8504 event.setPassword(isPassword); 8505 8506 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { 8507 event.setFromIndex(Selection.getSelectionStart(mText)); 8508 event.setToIndex(Selection.getSelectionEnd(mText)); 8509 event.setItemCount(mText.length()); 8510 } 8511 } 8512 8513 @Override 8514 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 8515 super.onInitializeAccessibilityNodeInfo(info); 8516 8517 final boolean isPassword = hasPasswordTransformationMethod(); 8518 if (!isPassword) { 8519 info.setText(getText()); 8520 } 8521 info.setPassword(isPassword); 8522 } 8523 8524 @Override 8525 public void sendAccessibilityEvent(int eventType) { 8526 // Do not send scroll events since first they are not interesting for 8527 // accessibility and second such events a generated too frequently. 8528 // For details see the implementation of bringTextIntoView(). 8529 if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED) { 8530 return; 8531 } 8532 super.sendAccessibilityEvent(eventType); 8533 } 8534 8535 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 8536 int fromIndex, int removedCount, int addedCount) { 8537 AccessibilityEvent event = 8538 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 8539 event.setFromIndex(fromIndex); 8540 event.setRemovedCount(removedCount); 8541 event.setAddedCount(addedCount); 8542 event.setBeforeText(beforeText); 8543 sendAccessibilityEventUnchecked(event); 8544 } 8545 8546 @Override 8547 protected void onCreateContextMenu(ContextMenu menu) { 8548 super.onCreateContextMenu(menu); 8549 boolean added = false; 8550 mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown; 8551 // Problem with context menu on long press: the menu appears while the key in down and when 8552 // the key is released, the view does not receive the key_up event. 8553 // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up 8554 // events. We cannot simply clear these flags in onTextContextMenuItem since 8555 // it may not be called (if the user/ discards the context menu with the back key). 8556 // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is 8557 // available in onTextContextMenuItem. 8558 mDPadCenterIsDown = mEnterKeyIsDown = false; 8559 8560 MenuHandler handler = new MenuHandler(); 8561 8562 if (mText instanceof Spanned && hasSelectionController()) { 8563 long lastTouchOffset = getLastTouchOffsets(); 8564 final int selStart = extractRangeStartFromLong(lastTouchOffset); 8565 final int selEnd = extractRangeEndFromLong(lastTouchOffset); 8566 8567 URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class); 8568 if (urls.length > 0) { 8569 menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl). 8570 setOnMenuItemClickListener(handler); 8571 8572 added = true; 8573 } 8574 } 8575 8576 // The context menu is not empty, which will prevent the selection mode from starting. 8577 // Add a entry to start it in the context menu. 8578 // TODO Does not handle the case where a subclass does not call super.thisMethod or 8579 // populates the menu AFTER this call. 8580 if (menu.size() > 0) { 8581 menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode). 8582 setOnMenuItemClickListener(handler); 8583 added = true; 8584 } 8585 8586 if (added) { 8587 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 8588 } 8589 } 8590 8591 /** 8592 * Returns whether this text view is a current input method target. The 8593 * default implementation just checks with {@link InputMethodManager}. 8594 */ 8595 public boolean isInputMethodTarget() { 8596 InputMethodManager imm = InputMethodManager.peekInstance(); 8597 return imm != null && imm.isActive(this); 8598 } 8599 8600 // Selection context mode 8601 private static final int ID_SELECT_ALL = android.R.id.selectAll; 8602 private static final int ID_CUT = android.R.id.cut; 8603 private static final int ID_COPY = android.R.id.copy; 8604 private static final int ID_PASTE = android.R.id.paste; 8605 // Context menu entries 8606 private static final int ID_COPY_URL = android.R.id.copyUrl; 8607 private static final int ID_SELECTION_MODE = android.R.id.selectTextMode; 8608 8609 private class MenuHandler implements MenuItem.OnMenuItemClickListener { 8610 public boolean onMenuItemClick(MenuItem item) { 8611 return onTextContextMenuItem(item.getItemId()); 8612 } 8613 } 8614 8615 /** 8616 * Called when a context menu option for the text view is selected. Currently 8617 * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode}, 8618 * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut} 8619 * or {@link android.R.id#copy}. 8620 * 8621 * @return true if the context menu item action was performed. 8622 */ 8623 public boolean onTextContextMenuItem(int id) { 8624 int min = 0; 8625 int max = mText.length(); 8626 8627 if (isFocused()) { 8628 final int selStart = getSelectionStart(); 8629 final int selEnd = getSelectionEnd(); 8630 8631 min = Math.max(0, Math.min(selStart, selEnd)); 8632 max = Math.max(0, Math.max(selStart, selEnd)); 8633 } 8634 8635 switch (id) { 8636 case ID_COPY_URL: 8637 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class); 8638 if (urls.length >= 1) { 8639 ClipData clip = null; 8640 for (int i=0; i<urls.length; i++) { 8641 Uri uri = Uri.parse(urls[0].getURL()); 8642 if (clip == null) { 8643 clip = ClipData.newRawUri(null, uri); 8644 } else { 8645 clip.addItem(new ClipData.Item(uri)); 8646 } 8647 } 8648 if (clip != null) { 8649 setPrimaryClip(clip); 8650 } 8651 } 8652 stopSelectionActionMode(); 8653 return true; 8654 8655 case ID_SELECTION_MODE: 8656 if (mSelectionActionMode != null) { 8657 // Selection mode is already started, simply change selected part. 8658 selectCurrentWord(); 8659 } else { 8660 startSelectionActionMode(); 8661 } 8662 return true; 8663 8664 case ID_SELECT_ALL: 8665 // This does not enter text selection mode. Text is highlighted, so that it can be 8666 // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. 8667 selectAll(); 8668 return true; 8669 8670 case ID_PASTE: 8671 paste(min, max); 8672 return true; 8673 8674 case ID_CUT: 8675 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8676 ((Editable) mText).delete(min, max); 8677 stopSelectionActionMode(); 8678 return true; 8679 8680 case ID_COPY: 8681 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8682 stopSelectionActionMode(); 8683 return true; 8684 } 8685 return false; 8686 } 8687 8688 /** 8689 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 8690 * by [min, max] when replacing this region by paste. 8691 * Note that if there were two spaces (or more) at that position before, they are kept. We just 8692 * make sure we do not add an extra one from the paste content. 8693 */ 8694 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 8695 if (paste.length() > 0) { 8696 if (min > 0) { 8697 final char charBefore = mTransformed.charAt(min - 1); 8698 final char charAfter = paste.charAt(0); 8699 8700 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8701 // Two spaces at beginning of paste: remove one 8702 final int originalLength = mText.length(); 8703 ((Editable) mText).delete(min - 1, min); 8704 // Due to filters, there is no guarantee that exactly one character was 8705 // removed: count instead. 8706 final int delta = mText.length() - originalLength; 8707 min += delta; 8708 max += delta; 8709 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8710 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8711 // No space at beginning of paste: add one 8712 final int originalLength = mText.length(); 8713 ((Editable) mText).replace(min, min, " "); 8714 // Taking possible filters into account as above. 8715 final int delta = mText.length() - originalLength; 8716 min += delta; 8717 max += delta; 8718 } 8719 } 8720 8721 if (max < mText.length()) { 8722 final char charBefore = paste.charAt(paste.length() - 1); 8723 final char charAfter = mTransformed.charAt(max); 8724 8725 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8726 // Two spaces at end of paste: remove one 8727 ((Editable) mText).delete(max, max + 1); 8728 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8729 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8730 // No space at end of paste: add one 8731 ((Editable) mText).replace(max, max, " "); 8732 } 8733 } 8734 } 8735 8736 return packRangeInLong(min, max); 8737 } 8738 8739 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 8740 TextView shadowView = (TextView) inflate(mContext, 8741 com.android.internal.R.layout.text_drag_thumbnail, null); 8742 8743 if (shadowView == null) { 8744 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 8745 } 8746 8747 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 8748 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 8749 } 8750 shadowView.setText(text); 8751 shadowView.setTextColor(getTextColors()); 8752 8753 shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 8754 shadowView.setGravity(Gravity.CENTER); 8755 8756 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8757 ViewGroup.LayoutParams.WRAP_CONTENT)); 8758 8759 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8760 shadowView.measure(size, size); 8761 8762 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 8763 shadowView.invalidate(); 8764 return new DragShadowBuilder(shadowView); 8765 } 8766 8767 private static class DragLocalState { 8768 public TextView sourceTextView; 8769 public int start, end; 8770 8771 public DragLocalState(TextView sourceTextView, int start, int end) { 8772 this.sourceTextView = sourceTextView; 8773 this.start = start; 8774 this.end = end; 8775 } 8776 } 8777 8778 @Override 8779 public boolean performLongClick() { 8780 if (super.performLongClick()) { 8781 mDiscardNextActionUp = true; 8782 return true; 8783 } 8784 8785 boolean handled = false; 8786 8787 // Long press in empty space moves cursor and shows the Paste affordance if available. 8788 if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 8789 mInsertionControllerEnabled) { 8790 final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY); 8791 stopSelectionActionMode(); 8792 Selection.setSelection((Spannable) mText, offset); 8793 getInsertionController().showImmediately(); 8794 handled = true; 8795 } 8796 8797 if (!handled && mSelectionActionMode != null) { 8798 if (touchPositionIsInSelection()) { 8799 // Start a drag 8800 final int start = getSelectionStart(); 8801 final int end = getSelectionEnd(); 8802 CharSequence selectedText = mTransformed.subSequence(start, end); 8803 ClipData data = ClipData.newPlainText(null, selectedText); 8804 DragLocalState localState = new DragLocalState(this, start, end); 8805 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 8806 stopSelectionActionMode(); 8807 } else { 8808 selectCurrentWord(); 8809 } 8810 handled = true; 8811 } 8812 8813 // Start a new selection 8814 handled |= !handled && startSelectionActionMode(); 8815 8816 if (handled) { 8817 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 8818 mDiscardNextActionUp = true; 8819 } 8820 8821 return handled; 8822 } 8823 8824 private boolean touchPositionIsInSelection() { 8825 int selectionStart = getSelectionStart(); 8826 int selectionEnd = getSelectionEnd(); 8827 8828 if (selectionStart == selectionEnd) { 8829 return false; 8830 } 8831 8832 if (selectionStart > selectionEnd) { 8833 int tmp = selectionStart; 8834 selectionStart = selectionEnd; 8835 selectionEnd = tmp; 8836 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8837 } 8838 8839 SelectionModifierCursorController selectionController = getSelectionController(); 8840 int minOffset = selectionController.getMinTouchOffset(); 8841 int maxOffset = selectionController.getMaxTouchOffset(); 8842 8843 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 8844 } 8845 8846 private PositionListener getPositionListener() { 8847 if (mPositionListener == null) { 8848 mPositionListener = new PositionListener(); 8849 } 8850 return mPositionListener; 8851 } 8852 8853 private interface TextViewPositionListener { 8854 public void updatePosition(int parentPositionX, int parentPositionY, boolean modified); 8855 } 8856 8857 private class PositionListener implements ViewTreeObserver.OnPreDrawListener { 8858 // 3 handles, 2 ActionPopup (suggestionsPopup first hides the others) 8859 private final int MAXIMUM_NUMBER_OF_LISTENERS = 5; 8860 private TextViewPositionListener[] mPositionListeners = 8861 new TextViewPositionListener[MAXIMUM_NUMBER_OF_LISTENERS]; 8862 private boolean mCanMove[] = new boolean[MAXIMUM_NUMBER_OF_LISTENERS]; 8863 private boolean mPositionHasChanged = true; 8864 // Absolute position of the TextView with respect to its parent window 8865 private int mPositionX, mPositionY; 8866 private int mNumberOfListeners; 8867 8868 public void addSubscriber(TextViewPositionListener positionListener, boolean canMove) { 8869 if (mNumberOfListeners == 0) { 8870 updatePosition(); 8871 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 8872 vto.addOnPreDrawListener(this); 8873 } 8874 8875 int emptySlotIndex = -1; 8876 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 8877 TextViewPositionListener listener = mPositionListeners[i]; 8878 if (listener == positionListener) { 8879 return; 8880 } else if (emptySlotIndex < 0 && listener == null) { 8881 emptySlotIndex = i; 8882 } 8883 } 8884 8885 mPositionListeners[emptySlotIndex] = positionListener; 8886 mCanMove[emptySlotIndex] = canMove; 8887 mNumberOfListeners++; 8888 } 8889 8890 public void removeSubscriber(TextViewPositionListener positionListener) { 8891 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 8892 if (mPositionListeners[i] == positionListener) { 8893 mPositionListeners[i] = null; 8894 mNumberOfListeners--; 8895 break; 8896 } 8897 } 8898 8899 if (mNumberOfListeners == 0) { 8900 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 8901 vto.removeOnPreDrawListener(this); 8902 } 8903 } 8904 8905 public int getPositionX() { 8906 return mPositionX; 8907 } 8908 8909 public int getPositionY() { 8910 return mPositionY; 8911 } 8912 8913 @Override 8914 public boolean onPreDraw() { 8915 updatePosition(); 8916 8917 for (int i = 0; i < MAXIMUM_NUMBER_OF_LISTENERS; i++) { 8918 if (mPositionHasChanged || mCanMove[i]) { 8919 TextViewPositionListener positionListener = mPositionListeners[i]; 8920 if (positionListener != null) { 8921 positionListener.updatePosition(mPositionX, mPositionY, 8922 mPositionHasChanged); 8923 } 8924 } 8925 } 8926 8927 return true; 8928 } 8929 8930 private void updatePosition() { 8931 TextView.this.getLocationInWindow(mTempCoords); 8932 8933 mPositionHasChanged = mTempCoords[0] != mPositionX || mTempCoords[1] != mPositionY; 8934 8935 mPositionX = mTempCoords[0]; 8936 mPositionY = mTempCoords[1]; 8937 } 8938 8939 public boolean isVisible(int positionX, int positionY) { 8940 final TextView textView = TextView.this; 8941 8942 if (mTempRect == null) mTempRect = new Rect(); 8943 final Rect clip = mTempRect; 8944 clip.left = getCompoundPaddingLeft(); 8945 clip.top = getExtendedPaddingTop(); 8946 clip.right = textView.getWidth() - getCompoundPaddingRight(); 8947 clip.bottom = textView.getHeight() - getExtendedPaddingBottom(); 8948 8949 final ViewParent parent = textView.getParent(); 8950 if (parent == null || !parent.getChildVisibleRect(textView, clip, null)) { 8951 return false; 8952 } 8953 8954 int posX = mPositionX + positionX; 8955 int posY = mPositionY + positionY; 8956 8957 // Offset by 1 to take into account 0.5 and int rounding around getPrimaryHorizontal. 8958 return posX >= clip.left - 1 && posX <= clip.right + 1 && 8959 posY >= clip.top && posY <= clip.bottom; 8960 } 8961 8962 public boolean isOffsetVisible(int offset) { 8963 final int line = mLayout.getLineForOffset(offset); 8964 final int lineBottom = mLayout.getLineBottom(line); 8965 final int primaryHorizontal = (int) mLayout.getPrimaryHorizontal(offset); 8966 return isVisible(primaryHorizontal, lineBottom); 8967 } 8968 } 8969 8970 private abstract class PinnedPopupWindow implements TextViewPositionListener { 8971 protected PopupWindow mPopupWindow; 8972 protected LinearLayout mContentView; 8973 int mPositionX, mPositionY; 8974 8975 protected abstract void createPopupWindow(); 8976 protected abstract void initContentView(); 8977 protected abstract int getTextOffset(); 8978 protected abstract int getVerticalLocalPosition(int line); 8979 protected abstract int clipVertically(int positionY); 8980 8981 public PinnedPopupWindow() { 8982 createPopupWindow(); 8983 8984 mPopupWindow.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8985 mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 8986 mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 8987 8988 mContentView = new LinearLayout(TextView.this.getContext()); 8989 LayoutParams wrapContent = new LayoutParams( 8990 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 8991 mContentView.setLayoutParams(wrapContent); 8992 8993 initContentView(); 8994 mPopupWindow.setContentView(mContentView); 8995 } 8996 8997 public void show() { 8998 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 8999 mContentView.measure( 9000 View.MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, 9001 View.MeasureSpec.AT_MOST), 9002 View.MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, 9003 View.MeasureSpec.AT_MOST)); 9004 9005 TextView.this.getPositionListener().addSubscriber(this, false); 9006 9007 computeLocalPosition(); 9008 9009 final PositionListener positionListener = TextView.this.getPositionListener(); 9010 updatePosition(positionListener.getPositionX(), positionListener.getPositionY()); 9011 } 9012 9013 private void computeLocalPosition() { 9014 final int offset = getTextOffset(); 9015 9016 final int width = mContentView.getMeasuredWidth(); 9017 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - width / 2.0f); 9018 mPositionX += viewportToContentHorizontalOffset(); 9019 9020 final int line = mLayout.getLineForOffset(offset); 9021 mPositionY = getVerticalLocalPosition(line); 9022 mPositionY += viewportToContentVerticalOffset(); 9023 } 9024 9025 private void updatePosition(int parentPositionX, int parentPositionY) { 9026 int positionX = parentPositionX + mPositionX; 9027 int positionY = parentPositionY + mPositionY; 9028 9029 positionY = clipVertically(positionY); 9030 9031 // Horizontal clipping 9032 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9033 final int width = mContentView.getMeasuredWidth(); 9034 positionX = Math.min(displayMetrics.widthPixels - width, positionX); 9035 positionX = Math.max(0, positionX); 9036 9037 if (isShowing()) { 9038 mPopupWindow.update(positionX, positionY, -1, -1); 9039 } else { 9040 mPopupWindow.showAtLocation(TextView.this, Gravity.NO_GRAVITY, 9041 positionX, positionY); 9042 } 9043 } 9044 9045 public void hide() { 9046 mPopupWindow.dismiss(); 9047 TextView.this.getPositionListener().removeSubscriber(this); 9048 } 9049 9050 @Override 9051 public void updatePosition(int parentPositionX, int parentPositionY, boolean modified) { 9052 if (isShowing() && getPositionListener().isOffsetVisible(getTextOffset())) { 9053 updatePosition(parentPositionX, parentPositionY); 9054 } else { 9055 hide(); 9056 } 9057 } 9058 9059 public boolean isShowing() { 9060 return mPopupWindow.isShowing(); 9061 } 9062 } 9063 9064 private static class SuggestionRangeSpan extends UnderlineSpan { 9065 // TODO themable, would be nice to make it a child class of TextAppearanceSpan, but 9066 // there is no way to have underline and TextAppearanceSpan. 9067 } 9068 9069 private class SuggestionsPopupWindow extends PinnedPopupWindow implements OnClickListener { 9070 private static final int MAX_NUMBER_SUGGESTIONS = 5; 9071 private static final int NO_SUGGESTIONS = -1; 9072 private WordIterator mSuggestionWordIterator; 9073 private TextAppearanceSpan[] mHighlightSpans = new TextAppearanceSpan[0]; 9074 9075 @Override 9076 protected void createPopupWindow() { 9077 mPopupWindow = new PopupWindow(TextView.this.mContext, null, 9078 com.android.internal.R.attr.textSuggestionsWindowStyle); 9079 mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); 9080 mPopupWindow.setOutsideTouchable(true); 9081 mPopupWindow.setClippingEnabled(false); 9082 } 9083 9084 @Override 9085 protected void initContentView() { 9086 mContentView.setOrientation(LinearLayout.VERTICAL); 9087 9088 LayoutInflater inflater = (LayoutInflater) TextView.this.mContext. 9089 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 9090 9091 if (inflater == null) { 9092 throw new IllegalArgumentException( 9093 "Unable to create inflater for TextEdit suggestions"); 9094 } 9095 9096 // Inflate the suggestion items once and for all. 9097 for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { 9098 View childView = inflater.inflate(mTextEditSuggestionItemLayout, 9099 mContentView, false); 9100 9101 if (! (childView instanceof TextView)) { 9102 throw new IllegalArgumentException( 9103 "Inflated TextEdit suggestion item is not a TextView: " + childView); 9104 } 9105 9106 childView.setTag(new SuggestionInfo()); 9107 mContentView.addView(childView); 9108 childView.setOnClickListener(this); 9109 } 9110 } 9111 9112 private class SuggestionInfo { 9113 int suggestionStart, suggestionEnd; // range of suggestion item with replacement text 9114 int spanStart, spanEnd; // range in TextView where text should be inserted 9115 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 9116 int suggestionIndex; // the index of the suggestion inside suggestionSpan 9117 } 9118 9119 /** 9120 * Returns the suggestion spans that cover the current cursor position. The suggestion 9121 * spans are sorted according to the length of text that they are attached to. 9122 */ 9123 private SuggestionSpan[] getSuggestionSpans() { 9124 int pos = TextView.this.getSelectionStart(); 9125 Spannable spannable = (Spannable) TextView.this.mText; 9126 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 9127 9128 // Cache the span length for performance reason. 9129 final HashMap<SuggestionSpan, Integer> spansLengths = 9130 new HashMap<SuggestionSpan, Integer>(); 9131 9132 for (SuggestionSpan suggestionSpan : suggestionSpans) { 9133 int start = spannable.getSpanStart(suggestionSpan); 9134 int end = spannable.getSpanEnd(suggestionSpan); 9135 spansLengths.put(suggestionSpan, Integer.valueOf(end - start)); 9136 } 9137 9138 // The suggestions are sorted according to the lenght of the text that they cover 9139 // (shorter first) 9140 Arrays.sort(suggestionSpans, new Comparator<SuggestionSpan>() { 9141 public int compare(SuggestionSpan span1, SuggestionSpan span2) { 9142 return spansLengths.get(span1).intValue() - spansLengths.get(span2).intValue(); 9143 } 9144 }); 9145 9146 return suggestionSpans; 9147 } 9148 9149 @Override 9150 public void show() { 9151 if (!(mText instanceof Editable)) return; 9152 updateSuggestions(); 9153 9154 super.show(); 9155 } 9156 9157 @Override 9158 protected int getTextOffset() { 9159 return getSelectionStart(); 9160 } 9161 9162 @Override 9163 protected int getVerticalLocalPosition(int line) { 9164 return mLayout.getLineBottom(line); 9165 } 9166 9167 @Override 9168 protected int clipVertically(int positionY) { 9169 final int height = mContentView.getMeasuredHeight(); 9170 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9171 return Math.min(positionY, displayMetrics.heightPixels - height); 9172 } 9173 9174 @Override 9175 public void hide() { 9176 super.hide(); 9177 if ((mText instanceof Editable) && mSuggestionRangeSpan != null) { 9178 ((Editable) mText).removeSpan(mSuggestionRangeSpan); 9179 } 9180 } 9181 9182 private void updateSuggestions() { 9183 Spannable spannable = (Spannable)TextView.this.mText; 9184 SuggestionSpan[] suggestionSpans = getSuggestionSpans(); 9185 9186 final int nbSpans = suggestionSpans.length; 9187 9188 int totalNbSuggestions = 0; 9189 int spanUnionStart = mText.length(); 9190 int spanUnionEnd = 0; 9191 9192 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 9193 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 9194 final int spanStart = spannable.getSpanStart(suggestionSpan); 9195 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 9196 spanUnionStart = Math.min(spanStart, spanUnionStart); 9197 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 9198 9199 String[] suggestions = suggestionSpan.getSuggestions(); 9200 int nbSuggestions = suggestions.length; 9201 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 9202 TextView textView = (TextView) mContentView.getChildAt( 9203 totalNbSuggestions); 9204 textView.setText(suggestions[suggestionIndex]); 9205 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 9206 suggestionInfo.spanStart = spanStart; 9207 suggestionInfo.spanEnd = spanEnd; 9208 suggestionInfo.suggestionSpan = suggestionSpan; 9209 suggestionInfo.suggestionIndex = suggestionIndex; 9210 9211 totalNbSuggestions++; 9212 if (totalNbSuggestions == MAX_NUMBER_SUGGESTIONS) { 9213 // Also end outer for loop 9214 spanIndex = nbSpans; 9215 break; 9216 } 9217 } 9218 } 9219 9220 if (totalNbSuggestions == 0) { 9221 // TODO Replace by final text, use a dedicated layout, add a fade out timer... 9222 TextView textView = (TextView) mContentView.getChildAt(0); 9223 textView.setText("No suggestions available"); 9224 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 9225 suggestionInfo.spanStart = NO_SUGGESTIONS; 9226 totalNbSuggestions++; 9227 } else { 9228 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 9229 ((Editable) mText).setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 9230 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9231 9232 for (int i = 0; i < totalNbSuggestions; i++) { 9233 final TextView textView = (TextView) mContentView.getChildAt(i); 9234 highlightTextDifferences(textView, spanUnionStart, spanUnionEnd); 9235 } 9236 } 9237 9238 for (int i = 0; i < totalNbSuggestions; i++) { 9239 mContentView.getChildAt(i).setVisibility(VISIBLE); 9240 } 9241 for (int i = totalNbSuggestions; i < MAX_NUMBER_SUGGESTIONS; i++) { 9242 mContentView.getChildAt(i).setVisibility(GONE); 9243 } 9244 } 9245 9246 private long[] getWordLimits(CharSequence text) { 9247 // TODO locale for mSuggestionWordIterator 9248 if (mSuggestionWordIterator == null) mSuggestionWordIterator = new WordIterator(); 9249 mSuggestionWordIterator.setCharSequence(text); 9250 9251 // First pass will simply count the number of words to be able to create an array 9252 // Not too expensive since previous break positions are cached by the BreakIterator 9253 int nbWords = 0; 9254 int position = mSuggestionWordIterator.following(0); 9255 while (position != BreakIterator.DONE) { 9256 nbWords++; 9257 position = mSuggestionWordIterator.following(position); 9258 } 9259 9260 int index = 0; 9261 long[] result = new long[nbWords]; 9262 9263 position = mSuggestionWordIterator.following(0); 9264 while (position != BreakIterator.DONE) { 9265 int wordStart = mSuggestionWordIterator.getBeginning(position); 9266 result[index++] = packRangeInLong(wordStart, position); 9267 position = mSuggestionWordIterator.following(position); 9268 } 9269 9270 return result; 9271 } 9272 9273 private TextAppearanceSpan highlightSpan(int index) { 9274 final int length = mHighlightSpans.length; 9275 if (index < length) { 9276 return mHighlightSpans[index]; 9277 } 9278 9279 // Assumes indexes are requested in sequence: simply append one more item 9280 TextAppearanceSpan[] newArray = new TextAppearanceSpan[length + 1]; 9281 System.arraycopy(mHighlightSpans, 0, newArray, 0, length); 9282 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext, 9283 android.R.style.TextAppearance_SuggestionHighlight); 9284 newArray[length] = highlightSpan; 9285 mHighlightSpans = newArray; 9286 return highlightSpan; 9287 } 9288 9289 private void highlightTextDifferences(TextView textView, int unionStart, int unionEnd) { 9290 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 9291 final int spanStart = suggestionInfo.spanStart; 9292 final int spanEnd = suggestionInfo.spanEnd; 9293 9294 // Remove all text formating by converting to Strings 9295 final String text = textView.getText().toString(); 9296 final String sourceText = mText.subSequence(spanStart, spanEnd).toString(); 9297 9298 long[] sourceWordLimits = getWordLimits(sourceText); 9299 long[] wordLimits = getWordLimits(text); 9300 9301 SpannableStringBuilder ssb = new SpannableStringBuilder(); 9302 // span [spanStart, spanEnd] is included in union [spanUnionStart, int spanUnionEnd] 9303 // The final result is made of 3 parts: the text before, between and after the span 9304 // This is the text before, provided for context 9305 ssb.append(mText.subSequence(unionStart, spanStart).toString()); 9306 9307 // shift is used to offset spans positions wrt span's beginning 9308 final int shift = spanStart - unionStart; 9309 suggestionInfo.suggestionStart = shift; 9310 suggestionInfo.suggestionEnd = shift + text.length(); 9311 9312 // This is the actual suggestion text, which will be highlighted by the following code 9313 ssb.append(text); 9314 9315 String[] words = new String[wordLimits.length]; 9316 for (int i = 0; i < wordLimits.length; i++) { 9317 int wordStart = extractRangeStartFromLong(wordLimits[i]); 9318 int wordEnd = extractRangeEndFromLong(wordLimits[i]); 9319 words[i] = text.substring(wordStart, wordEnd); 9320 } 9321 9322 // Highlighted word algorithm is based on word matching between source and text 9323 // Matching words are found from left to right. TODO: change for RTL languages 9324 // Characters between matching words are highlighted 9325 int previousCommonWordIndex = -1; 9326 int nbHighlightSpans = 0; 9327 for (int i = 0; i < sourceWordLimits.length; i++) { 9328 int wordStart = extractRangeStartFromLong(sourceWordLimits[i]); 9329 int wordEnd = extractRangeEndFromLong(sourceWordLimits[i]); 9330 String sourceWord = sourceText.substring(wordStart, wordEnd); 9331 9332 for (int j = previousCommonWordIndex + 1; j < words.length; j++) { 9333 if (sourceWord.equals(words[j])) { 9334 if (j != previousCommonWordIndex + 1) { 9335 int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 : 9336 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 9337 int lastDifferentPosition = extractRangeStartFromLong(wordLimits[j]); 9338 ssb.setSpan(highlightSpan(nbHighlightSpans++), 9339 shift + firstDifferentPosition, shift + lastDifferentPosition, 9340 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9341 } else { 9342 // Compare characters between words 9343 int previousSourceWordEnd = i == 0 ? 0 : 9344 extractRangeEndFromLong(sourceWordLimits[i - 1]); 9345 int sourceWordStart = extractRangeStartFromLong(sourceWordLimits[i]); 9346 String sourceSpaces = sourceText.substring(previousSourceWordEnd, 9347 sourceWordStart); 9348 9349 int previousWordEnd = j == 0 ? 0 : 9350 extractRangeEndFromLong(wordLimits[j - 1]); 9351 int currentWordStart = extractRangeStartFromLong(wordLimits[j]); 9352 String textSpaces = text.substring(previousWordEnd, currentWordStart); 9353 9354 if (!sourceSpaces.equals(textSpaces)) { 9355 ssb.setSpan(highlightSpan(nbHighlightSpans++), 9356 shift + previousWordEnd, shift + currentWordStart, 9357 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9358 } 9359 } 9360 previousCommonWordIndex = j; 9361 break; 9362 } 9363 } 9364 } 9365 9366 // Finally, compare ends of Strings 9367 if (previousCommonWordIndex < words.length - 1) { 9368 int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 : 9369 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 9370 int lastDifferentPosition = textView.length(); 9371 ssb.setSpan(highlightSpan(nbHighlightSpans++), 9372 shift + firstDifferentPosition, shift + lastDifferentPosition, 9373 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9374 } else { 9375 int lastSourceWordEnd = sourceWordLimits.length == 0 ? 0 : 9376 extractRangeEndFromLong(sourceWordLimits[sourceWordLimits.length - 1]); 9377 String sourceSpaces = sourceText.substring(lastSourceWordEnd, sourceText.length()); 9378 9379 int lastCommonTextWordEnd = previousCommonWordIndex < 0 ? 0 : 9380 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 9381 String textSpaces = text.substring(lastCommonTextWordEnd, textView.length()); 9382 9383 if (!sourceSpaces.equals(textSpaces) && textSpaces.length() > 0) { 9384 ssb.setSpan(highlightSpan(nbHighlightSpans++), 9385 shift + lastCommonTextWordEnd, shift + textView.length(), 9386 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9387 } 9388 } 9389 9390 // Final part, text after the current suggestion range. 9391 ssb.append(mText.subSequence(spanEnd, unionEnd).toString()); 9392 textView.setText(ssb); 9393 } 9394 9395 @Override 9396 public void onClick(View view) { 9397 if (view instanceof TextView) { 9398 TextView textView = (TextView) view; 9399 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 9400 final int spanStart = suggestionInfo.spanStart; 9401 final int spanEnd = suggestionInfo.spanEnd; 9402 if (spanStart != NO_SUGGESTIONS) { 9403 // SuggestionSpans are removed by replace: save them before 9404 Editable editable = ((Editable) mText); 9405 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 9406 SuggestionSpan.class); 9407 final int length = suggestionSpans.length; 9408 int[] suggestionSpansStarts = new int[length]; 9409 int[] suggestionSpansEnds = new int[length]; 9410 int[] suggestionSpansFlags = new int[length]; 9411 for (int i = 0; i < length; i++) { 9412 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 9413 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 9414 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 9415 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 9416 } 9417 9418 final int suggestionStart = suggestionInfo.suggestionStart; 9419 final int suggestionEnd = suggestionInfo.suggestionEnd; 9420 final String suggestion = textView.getText().subSequence( 9421 suggestionStart, suggestionEnd).toString(); 9422 final String originalText = mText.subSequence(spanStart, spanEnd).toString(); 9423 ((Editable) mText).replace(spanStart, spanEnd, suggestion); 9424 9425 // Notify source IME of the suggestion pick. Do this before swaping texts. 9426 if (!TextUtils.isEmpty( 9427 suggestionInfo.suggestionSpan.getNotificationTargetClassName())) { 9428 InputMethodManager imm = InputMethodManager.peekInstance(); 9429 imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText, 9430 suggestionInfo.suggestionIndex); 9431 } 9432 9433 // Swap text content between actual text and Suggestion span 9434 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 9435 suggestions[suggestionInfo.suggestionIndex] = originalText; 9436 9437 // Restore previous SuggestionSpans 9438 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 9439 for (int i = 0; i < length; i++) { 9440 // Only spans that include the modified region make sense after replacement 9441 // Spans partially included in the replaced region are removed, there is no 9442 // way to assign them a valid range after replacement 9443 if (suggestionSpansStarts[i] <= spanStart && 9444 suggestionSpansEnds[i] >= spanEnd) { 9445 editable.setSpan(suggestionSpans[i], suggestionSpansStarts[i], 9446 suggestionSpansEnds[i] + lengthDifference, 9447 suggestionSpansFlags[i]); 9448 } 9449 } 9450 } 9451 } 9452 hide(); 9453 } 9454 } 9455 9456 void showSuggestions() { 9457 if (!isSuggestionsEnabled() || !isTextEditable()) return; 9458 9459 if (mSuggestionsPopupWindow == null) { 9460 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 9461 } 9462 hideControllers(); 9463 mSuggestionsPopupWindow.show(); 9464 } 9465 9466 void hideSuggestions() { 9467 if (mSuggestionsPopupWindow != null) { 9468 mSuggestionsPopupWindow.hide(); 9469 } 9470 } 9471 9472 boolean areSuggestionsShown() { 9473 return mSuggestionsPopupWindow != null && mSuggestionsPopupWindow.isShowing(); 9474 } 9475 9476 /** 9477 * Some parts of the text can have alternate suggestion text attached. This is typically done by 9478 * the IME by adding {@link SuggestionSpan}s to the text. 9479 * 9480 * When suggestions are enabled (default), this list of suggestions will be displayed when the 9481 * user double taps on these parts of the text. No suggestions are displayed when this value is 9482 * false. Use {@link #setSuggestionsEnabled(boolean)} to change this value. 9483 * 9484 * Note that suggestions are only enabled for a subset of input types. In addition to setting 9485 * this flag to <code>true</code> using {@link #setSuggestionsEnabled(boolean)} or the 9486 * <code>android:suggestionsEnabled</code> xml attribute, this method will return 9487 * <code>true</code> only if the class of your input type is {@link InputType#TYPE_CLASS_TEXT}. 9488 * In addition, the type variation must also be one of 9489 * {@link InputType#TYPE_TEXT_VARIATION_NORMAL}, 9490 * {@link InputType#TYPE_TEXT_VARIATION_EMAIL_SUBJECT}, 9491 * {@link InputType#TYPE_TEXT_VARIATION_LONG_MESSAGE}, 9492 * {@link InputType#TYPE_TEXT_VARIATION_SHORT_MESSAGE} or 9493 * {@link InputType#TYPE_TEXT_VARIATION_WEB_EDIT_TEXT}. 9494 * 9495 * @return true if the suggestions popup window is enabled. 9496 * 9497 * @attr ref android.R.styleable#TextView_suggestionsEnabled 9498 */ 9499 public boolean isSuggestionsEnabled() { 9500 if (!mSuggestionsEnabled) return false; 9501 if ((mInputType & InputType.TYPE_MASK_CLASS) != InputType.TYPE_CLASS_TEXT) return false; 9502 final int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 9503 if (variation == EditorInfo.TYPE_TEXT_VARIATION_NORMAL || 9504 variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT || 9505 variation == EditorInfo.TYPE_TEXT_VARIATION_LONG_MESSAGE || 9506 variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE || 9507 variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) return true; 9508 9509 return false; 9510 } 9511 9512 /** 9513 * Enables or disables the suggestion popup. See {@link #isSuggestionsEnabled()}. 9514 * 9515 * @param enabled Whether or not suggestions are enabled. 9516 * 9517 * @attr ref android.R.styleable#TextView_suggestionsEnabled 9518 */ 9519 public void setSuggestionsEnabled(boolean enabled) { 9520 mSuggestionsEnabled = enabled; 9521 } 9522 9523 /** 9524 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 9525 * selection is initiated in this View. 9526 * 9527 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 9528 * Paste actions, depending on what this View supports. 9529 * 9530 * A custom implementation can add new entries in the default menu in its 9531 * {@link android.view.ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The 9532 * default actions can also be removed from the menu using {@link Menu#removeItem(int)} and 9533 * passing {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} 9534 * or {@link android.R.id#paste} ids as parameters. 9535 * 9536 * Returning false from 9537 * {@link android.view.ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will prevent 9538 * the action mode from being started. 9539 * 9540 * Action click events should be handled by the custom implementation of 9541 * {@link android.view.ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 9542 * 9543 * Note that text selection mode is not started when a TextView receives focus and the 9544 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 9545 * that case, to allow for quick replacement. 9546 */ 9547 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 9548 mCustomSelectionActionModeCallback = actionModeCallback; 9549 } 9550 9551 /** 9552 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 9553 * 9554 * @return The current custom selection callback. 9555 */ 9556 public ActionMode.Callback getCustomSelectionActionModeCallback() { 9557 return mCustomSelectionActionModeCallback; 9558 } 9559 9560 /** 9561 * 9562 * @return true if the selection mode was actually started. 9563 */ 9564 private boolean startSelectionActionMode() { 9565 if (mSelectionActionMode != null) { 9566 // Selection action mode is already started 9567 return false; 9568 } 9569 9570 if (!canSelectText() || !requestFocus()) { 9571 Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled."); 9572 return false; 9573 } 9574 9575 if (!hasSelection()) { 9576 // There may already be a selection on device rotation 9577 boolean currentWordSelected = selectCurrentWord(); 9578 if (!currentWordSelected) { 9579 // No word found under cursor or text selection not permitted. 9580 return false; 9581 } 9582 } 9583 9584 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 9585 mSelectionActionMode = startActionMode(actionModeCallback); 9586 final boolean selectionStarted = mSelectionActionMode != null; 9587 9588 if (selectionStarted && !mTextIsSelectable) { 9589 // Show the IME to be able to replace text, except when selecting non editable text. 9590 final InputMethodManager imm = InputMethodManager.peekInstance(); 9591 if (imm != null) imm.showSoftInput(this, 0, null); 9592 } 9593 9594 return selectionStarted; 9595 } 9596 9597 private void stopSelectionActionMode() { 9598 if (mSelectionActionMode != null) { 9599 // This will hide the mSelectionModifierCursorController 9600 mSelectionActionMode.finish(); 9601 } 9602 } 9603 9604 /** 9605 * Paste clipboard content between min and max positions. 9606 */ 9607 private void paste(int min, int max) { 9608 ClipboardManager clipboard = 9609 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 9610 ClipData clip = clipboard.getPrimaryClip(); 9611 if (clip != null) { 9612 boolean didFirst = false; 9613 for (int i=0; i<clip.getItemCount(); i++) { 9614 CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); 9615 if (paste != null) { 9616 if (!didFirst) { 9617 long minMax = prepareSpacesAroundPaste(min, max, paste); 9618 min = extractRangeStartFromLong(minMax); 9619 max = extractRangeEndFromLong(minMax); 9620 Selection.setSelection((Spannable) mText, max); 9621 ((Editable) mText).replace(min, max, paste); 9622 didFirst = true; 9623 } else { 9624 ((Editable) mText).insert(getSelectionEnd(), "\n"); 9625 ((Editable) mText).insert(getSelectionEnd(), paste); 9626 } 9627 } 9628 } 9629 stopSelectionActionMode(); 9630 sLastCutOrCopyTime = 0; 9631 } 9632 } 9633 9634 private void setPrimaryClip(ClipData clip) { 9635 ClipboardManager clipboard = (ClipboardManager) getContext(). 9636 getSystemService(Context.CLIPBOARD_SERVICE); 9637 clipboard.setPrimaryClip(clip); 9638 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 9639 } 9640 9641 /** 9642 * An ActionMode Callback class that is used to provide actions while in text selection mode. 9643 * 9644 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 9645 * on which of these this TextView supports. 9646 */ 9647 private class SelectionActionModeCallback implements ActionMode.Callback { 9648 9649 @Override 9650 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 9651 TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme); 9652 9653 boolean allowText = getContext().getResources().getBoolean( 9654 com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon); 9655 9656 mode.setTitle(allowText ? 9657 mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null); 9658 mode.setSubtitle(null); 9659 9660 int selectAllIconId = 0; // No icon by default 9661 if (!allowText) { 9662 // Provide an icon, text will not be displayed on smaller screens. 9663 selectAllIconId = styledAttributes.getResourceId( 9664 R.styleable.Theme_actionModeSelectAllDrawable, 0); 9665 } 9666 9667 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 9668 setIcon(selectAllIconId). 9669 setAlphabeticShortcut('a'). 9670 setShowAsAction( 9671 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9672 9673 if (canCut()) { 9674 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 9675 setIcon(styledAttributes.getResourceId( 9676 R.styleable.Theme_actionModeCutDrawable, 0)). 9677 setAlphabeticShortcut('x'). 9678 setShowAsAction( 9679 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9680 } 9681 9682 if (canCopy()) { 9683 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 9684 setIcon(styledAttributes.getResourceId( 9685 R.styleable.Theme_actionModeCopyDrawable, 0)). 9686 setAlphabeticShortcut('c'). 9687 setShowAsAction( 9688 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9689 } 9690 9691 if (canPaste()) { 9692 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 9693 setIcon(styledAttributes.getResourceId( 9694 R.styleable.Theme_actionModePasteDrawable, 0)). 9695 setAlphabeticShortcut('v'). 9696 setShowAsAction( 9697 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9698 } 9699 9700 styledAttributes.recycle(); 9701 9702 if (mCustomSelectionActionModeCallback != null) { 9703 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 9704 // The custom mode can choose to cancel the action mode 9705 return false; 9706 } 9707 } 9708 9709 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 9710 getSelectionController().show(); 9711 return true; 9712 } else { 9713 return false; 9714 } 9715 } 9716 9717 @Override 9718 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 9719 if (mCustomSelectionActionModeCallback != null) { 9720 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 9721 } 9722 return true; 9723 } 9724 9725 @Override 9726 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 9727 if (mCustomSelectionActionModeCallback != null && 9728 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 9729 return true; 9730 } 9731 return onTextContextMenuItem(item.getItemId()); 9732 } 9733 9734 @Override 9735 public void onDestroyActionMode(ActionMode mode) { 9736 if (mCustomSelectionActionModeCallback != null) { 9737 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 9738 } 9739 Selection.setSelection((Spannable) mText, getSelectionEnd()); 9740 9741 if (mSelectionModifierCursorController != null) { 9742 mSelectionModifierCursorController.hide(); 9743 } 9744 9745 mSelectionActionMode = null; 9746 } 9747 } 9748 9749 private class ActionPopupWindow extends PinnedPopupWindow implements OnClickListener { 9750 private static final int POPUP_TEXT_LAYOUT = 9751 com.android.internal.R.layout.text_edit_action_popup_text; 9752 private TextView mPasteTextView; 9753 private TextView mReplaceTextView; 9754 9755 @Override 9756 protected void createPopupWindow() { 9757 mPopupWindow = new PopupWindow(TextView.this.mContext, null, 9758 com.android.internal.R.attr.textSelectHandleWindowStyle); 9759 mPopupWindow.setClippingEnabled(true); 9760 } 9761 9762 @Override 9763 protected void initContentView() { 9764 mContentView.setOrientation(LinearLayout.HORIZONTAL); 9765 mContentView.setBackgroundResource( 9766 com.android.internal.R.drawable.text_edit_side_paste_window); 9767 9768 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 9769 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 9770 9771 LayoutParams wrapContent = new LayoutParams( 9772 ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 9773 9774 mPasteTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 9775 mPasteTextView.setLayoutParams(wrapContent); 9776 mContentView.addView(mPasteTextView); 9777 mPasteTextView.setText(com.android.internal.R.string.paste); 9778 mPasteTextView.setOnClickListener(this); 9779 9780 mReplaceTextView = (TextView) inflater.inflate(POPUP_TEXT_LAYOUT, null); 9781 mReplaceTextView.setLayoutParams(wrapContent); 9782 mContentView.addView(mReplaceTextView); 9783 mReplaceTextView.setText(com.android.internal.R.string.replace); 9784 mReplaceTextView.setOnClickListener(this); 9785 } 9786 9787 @Override 9788 public void show() { 9789 boolean canPaste = canPaste(); 9790 boolean suggestionsEnabled = isSuggestionsEnabled(); 9791 mPasteTextView.setVisibility(canPaste ? View.VISIBLE : View.GONE); 9792 mReplaceTextView.setVisibility(suggestionsEnabled ? View.VISIBLE : View.GONE); 9793 9794 if (!canPaste && !suggestionsEnabled) return; 9795 9796 super.show(); 9797 } 9798 9799 @Override 9800 public void onClick(View view) { 9801 if (view == mPasteTextView && canPaste()) { 9802 onTextContextMenuItem(ID_PASTE); 9803 hide(); 9804 } else if (view == mReplaceTextView) { 9805 showSuggestions(); 9806 } 9807 } 9808 9809 @Override 9810 protected int getTextOffset() { 9811 return (getSelectionStart() + getSelectionEnd()) / 2; 9812 } 9813 9814 @Override 9815 protected int getVerticalLocalPosition(int line) { 9816 return mLayout.getLineTop(line) - mContentView.getMeasuredHeight(); 9817 } 9818 9819 @Override 9820 protected int clipVertically(int positionY) { 9821 if (positionY < 0) { 9822 final int offset = getTextOffset(); 9823 final int line = mLayout.getLineForOffset(offset); 9824 positionY += mLayout.getLineBottom(line) - mLayout.getLineTop(line); 9825 positionY += mContentView.getMeasuredHeight(); 9826 9827 // Assumes insertion and selection handles share the same height 9828 final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes); 9829 positionY += handle.getIntrinsicHeight(); 9830 } 9831 9832 return positionY; 9833 } 9834 } 9835 9836 private abstract class HandleView extends View implements TextViewPositionListener { 9837 protected Drawable mDrawable; 9838 private final PopupWindow mContainer; 9839 // Position with respect to the parent TextView 9840 private int mPositionX, mPositionY; 9841 private boolean mIsDragging; 9842 // Offset from touch position to mPosition 9843 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 9844 protected int mHotspotX; 9845 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 9846 private float mTouchOffsetY; 9847 // Where the touch position should be on the handle to ensure a maximum cursor visibility 9848 private float mIdealVerticalOffset; 9849 // Parent's (TextView) previous position in window 9850 private int mLastParentX, mLastParentY; 9851 // Transient action popup window for Paste and Replace actions 9852 protected ActionPopupWindow mActionPopupWindow; 9853 // Previous text character offset 9854 private int mPreviousOffset = -1; 9855 // Previous text character offset 9856 private boolean mPositionHasChanged = true; 9857 // Used to delay the appearance of the action popup window 9858 private Runnable mActionPopupShower; 9859 9860 public HandleView() { 9861 super(TextView.this.mContext); 9862 mContainer = new PopupWindow(TextView.this.mContext, null, 9863 com.android.internal.R.attr.textSelectHandleWindowStyle); 9864 mContainer.setSplitTouchEnabled(true); 9865 mContainer.setClippingEnabled(false); 9866 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 9867 mContainer.setContentView(this); 9868 9869 initDrawable(); 9870 9871 final int handleHeight = mDrawable.getIntrinsicHeight(); 9872 mTouchOffsetY = -0.3f * handleHeight; 9873 mIdealVerticalOffset = 0.7f * handleHeight; 9874 } 9875 9876 protected abstract void initDrawable(); 9877 9878 // Touch-up filter: number of previous positions remembered 9879 private static final int HISTORY_SIZE = 5; 9880 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 9881 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 9882 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 9883 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 9884 private int mPreviousOffsetIndex = 0; 9885 private int mNumberPreviousOffsets = 0; 9886 9887 private void startTouchUpFilter(int offset) { 9888 mNumberPreviousOffsets = 0; 9889 addPositionToTouchUpFilter(offset); 9890 } 9891 9892 private void addPositionToTouchUpFilter(int offset) { 9893 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 9894 mPreviousOffsets[mPreviousOffsetIndex] = offset; 9895 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 9896 mNumberPreviousOffsets++; 9897 } 9898 9899 private void filterOnTouchUp() { 9900 final long now = SystemClock.uptimeMillis(); 9901 int i = 0; 9902 int index = mPreviousOffsetIndex; 9903 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 9904 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 9905 i++; 9906 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 9907 } 9908 9909 if (i > 0 && i < iMax && 9910 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 9911 positionAtCursorOffset(mPreviousOffsets[index]); 9912 } 9913 } 9914 9915 public boolean offsetHasBeenChanged() { 9916 return mNumberPreviousOffsets > 1; 9917 } 9918 9919 @Override 9920 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 9921 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 9922 } 9923 9924 public void show() { 9925 if (isShowing()) return; 9926 9927 getPositionListener().addSubscriber(this, true); 9928 9929 // Make sure the offset is always considered new, even when focusing at same position 9930 mPreviousOffset = -1; 9931 positionAtCursorOffset(getCurrentCursorOffset()); 9932 9933 hideActionPopupWindow(); 9934 } 9935 9936 protected void dismiss() { 9937 mIsDragging = false; 9938 mContainer.dismiss(); 9939 onDetached(); 9940 } 9941 9942 public void hide() { 9943 dismiss(); 9944 9945 TextView.this.getPositionListener().removeSubscriber(this); 9946 } 9947 9948 void showActionPopupWindow(int delay) { 9949 if (mActionPopupWindow == null) { 9950 mActionPopupWindow = new ActionPopupWindow(); 9951 } 9952 if (mActionPopupShower == null) { 9953 mActionPopupShower = new Runnable() { 9954 public void run() { 9955 mActionPopupWindow.show(); 9956 } 9957 }; 9958 } else { 9959 TextView.this.removeCallbacks(mActionPopupShower); 9960 } 9961 TextView.this.postDelayed(mActionPopupShower, delay); 9962 } 9963 9964 protected void hideActionPopupWindow() { 9965 if (mActionPopupShower != null) { 9966 TextView.this.removeCallbacks(mActionPopupShower); 9967 } 9968 if (mActionPopupWindow != null) { 9969 mActionPopupWindow.hide(); 9970 } 9971 } 9972 9973 public boolean isShowing() { 9974 return mContainer.isShowing(); 9975 } 9976 9977 private boolean isVisible() { 9978 // Always show a dragging handle. 9979 if (mIsDragging) { 9980 return true; 9981 } 9982 9983 if (isInBatchEditMode()) { 9984 return false; 9985 } 9986 9987 return getPositionListener().isVisible(mPositionX + mHotspotX, mPositionY); 9988 } 9989 9990 public abstract int getCurrentCursorOffset(); 9991 9992 public abstract void updateSelection(int offset); 9993 9994 public abstract void updatePosition(float x, float y); 9995 9996 protected void positionAtCursorOffset(int offset) { 9997 // A HandleView relies on the layout, which may be nulled by external methods 9998 if (mLayout == null) { 9999 // Will update controllers' state, hiding them and stopping selection mode if needed 10000 prepareCursorControllers(); 10001 return; 10002 } 10003 10004 if (offset != mPreviousOffset) { 10005 updateSelection(offset); 10006 addPositionToTouchUpFilter(offset); 10007 final int line = mLayout.getLineForOffset(offset); 10008 10009 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 10010 mPositionY = mLayout.getLineBottom(line); 10011 10012 // Take TextView's padding into account. 10013 mPositionX += viewportToContentHorizontalOffset(); 10014 mPositionY += viewportToContentVerticalOffset(); 10015 10016 mPreviousOffset = offset; 10017 mPositionHasChanged = true; 10018 } 10019 } 10020 10021 public void updatePosition(int parentPositionX, int parentPositionY, boolean modified) { 10022 positionAtCursorOffset(getCurrentCursorOffset()); 10023 if (modified || mPositionHasChanged) { 10024 if (mIsDragging) { 10025 // Update touchToWindow offset in case of parent scrolling while dragging 10026 if (parentPositionX != mLastParentX || parentPositionY != mLastParentY) { 10027 mTouchToWindowOffsetX += parentPositionX - mLastParentX; 10028 mTouchToWindowOffsetY += parentPositionY - mLastParentY; 10029 mLastParentX = parentPositionX; 10030 mLastParentY = parentPositionY; 10031 } 10032 10033 onHandleMoved(); 10034 } 10035 10036 if (isVisible()) { 10037 final int positionX = parentPositionX + mPositionX; 10038 final int positionY = parentPositionY + mPositionY; 10039 if (isShowing()) { 10040 mContainer.update(positionX, positionY, -1, -1); 10041 } else { 10042 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, 10043 positionX, positionY); 10044 } 10045 } else { 10046 if (isShowing()) { 10047 dismiss(); 10048 } 10049 } 10050 10051 mPositionHasChanged = false; 10052 } 10053 } 10054 10055 @Override 10056 protected void onDraw(Canvas c) { 10057 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 10058 mDrawable.draw(c); 10059 } 10060 10061 @Override 10062 public boolean onTouchEvent(MotionEvent ev) { 10063 switch (ev.getActionMasked()) { 10064 case MotionEvent.ACTION_DOWN: { 10065 startTouchUpFilter(getCurrentCursorOffset()); 10066 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 10067 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 10068 10069 final PositionListener positionListener = getPositionListener(); 10070 mLastParentX = positionListener.getPositionX(); 10071 mLastParentY = positionListener.getPositionY(); 10072 mIsDragging = true; 10073 break; 10074 } 10075 10076 case MotionEvent.ACTION_MOVE: { 10077 final float rawX = ev.getRawX(); 10078 final float rawY = ev.getRawY(); 10079 10080 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 10081 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 10082 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 10083 float newVerticalOffset; 10084 if (previousVerticalOffset < mIdealVerticalOffset) { 10085 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 10086 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 10087 } else { 10088 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 10089 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 10090 } 10091 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 10092 10093 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 10094 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 10095 10096 updatePosition(newPosX, newPosY); 10097 break; 10098 } 10099 10100 case MotionEvent.ACTION_UP: 10101 filterOnTouchUp(); 10102 mIsDragging = false; 10103 break; 10104 10105 case MotionEvent.ACTION_CANCEL: 10106 mIsDragging = false; 10107 break; 10108 } 10109 return true; 10110 } 10111 10112 public boolean isDragging() { 10113 return mIsDragging; 10114 } 10115 10116 void onHandleMoved() { 10117 hideActionPopupWindow(); 10118 } 10119 10120 public void onDetached() { 10121 hideActionPopupWindow(); 10122 } 10123 } 10124 10125 private class InsertionHandleView extends HandleView { 10126 private static final int DELAY_BEFORE_HANDLE_FADES_OUT = 4000; 10127 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 10128 10129 // Used to detect taps on the insertion handle, which will affect the ActionPopupWindow 10130 private float mDownPositionX, mDownPositionY; 10131 private Runnable mHider; 10132 10133 @Override 10134 public void show() { 10135 super.show(); 10136 hideAfterDelay(); 10137 } 10138 10139 public void show(int delayBeforeShowActionPopup) { 10140 show(); 10141 10142 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 10143 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 10144 delayBeforeShowActionPopup = 0; 10145 } 10146 showActionPopupWindow(delayBeforeShowActionPopup); 10147 } 10148 10149 private void hideAfterDelay() { 10150 removeHiderCallback(); 10151 if (mHider == null) { 10152 mHider = new Runnable() { 10153 public void run() { 10154 hide(); 10155 } 10156 }; 10157 } 10158 TextView.this.postDelayed(mHider, DELAY_BEFORE_HANDLE_FADES_OUT); 10159 } 10160 10161 private void removeHiderCallback() { 10162 if (mHider != null) { 10163 TextView.this.removeCallbacks(mHider); 10164 } 10165 } 10166 10167 @Override 10168 protected void initDrawable() { 10169 if (mSelectHandleCenter == null) { 10170 mSelectHandleCenter = mContext.getResources().getDrawable( 10171 mTextSelectHandleRes); 10172 } 10173 mDrawable = mSelectHandleCenter; 10174 mHotspotX = mDrawable.getIntrinsicWidth() / 2; 10175 } 10176 10177 @Override 10178 public boolean onTouchEvent(MotionEvent ev) { 10179 final boolean result = super.onTouchEvent(ev); 10180 10181 switch (ev.getActionMasked()) { 10182 case MotionEvent.ACTION_DOWN: 10183 mDownPositionX = ev.getRawX(); 10184 mDownPositionY = ev.getRawY(); 10185 break; 10186 10187 case MotionEvent.ACTION_UP: 10188 if (!offsetHasBeenChanged()) { 10189 final float deltaX = mDownPositionX - ev.getRawX(); 10190 final float deltaY = mDownPositionY - ev.getRawY(); 10191 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 10192 if (distanceSquared < mSquaredTouchSlopDistance) { 10193 if (mActionPopupWindow != null && mActionPopupWindow.isShowing()) { 10194 // Tapping on the handle dismisses the displayed action popup 10195 mActionPopupWindow.hide(); 10196 } else { 10197 show(0); 10198 } 10199 } 10200 } 10201 hideAfterDelay(); 10202 break; 10203 10204 case MotionEvent.ACTION_CANCEL: 10205 hideAfterDelay(); 10206 break; 10207 10208 default: 10209 break; 10210 } 10211 10212 return result; 10213 } 10214 10215 @Override 10216 public int getCurrentCursorOffset() { 10217 return TextView.this.getSelectionStart(); 10218 } 10219 10220 @Override 10221 public void updateSelection(int offset) { 10222 Selection.setSelection((Spannable) mText, offset); 10223 } 10224 10225 @Override 10226 public void updatePosition(float x, float y) { 10227 positionAtCursorOffset(getOffsetForPosition(x, y)); 10228 } 10229 10230 @Override 10231 void onHandleMoved() { 10232 super.onHandleMoved(); 10233 removeHiderCallback(); 10234 } 10235 10236 @Override 10237 public void onDetached() { 10238 super.onDetached(); 10239 removeHiderCallback(); 10240 } 10241 } 10242 10243 private class SelectionStartHandleView extends HandleView { 10244 @Override 10245 protected void initDrawable() { 10246 if (mSelectHandleLeft == null) { 10247 mSelectHandleLeft = mContext.getResources().getDrawable( 10248 mTextSelectHandleLeftRes); 10249 } 10250 mDrawable = mSelectHandleLeft; 10251 mHotspotX = (mDrawable.getIntrinsicWidth() * 3) / 4; 10252 } 10253 10254 @Override 10255 public int getCurrentCursorOffset() { 10256 return TextView.this.getSelectionStart(); 10257 } 10258 10259 @Override 10260 public void updateSelection(int offset) { 10261 Selection.setSelection((Spannable) mText, offset, getSelectionEnd()); 10262 } 10263 10264 @Override 10265 public void updatePosition(float x, float y) { 10266 final int selectionStart = getSelectionStart(); 10267 final int selectionEnd = getSelectionEnd(); 10268 10269 int offset = getOffsetForPosition(x, y); 10270 10271 // No need to redraw when the offset is unchanged 10272 if (offset == selectionStart) return; 10273 // Handles can not cross and selection is at least one character 10274 if (offset >= selectionEnd) offset = selectionEnd - 1; 10275 10276 positionAtCursorOffset(offset); 10277 } 10278 10279 public ActionPopupWindow getActionPopupWindow() { 10280 return mActionPopupWindow; 10281 } 10282 } 10283 10284 private class SelectionEndHandleView extends HandleView { 10285 @Override 10286 protected void initDrawable() { 10287 if (mSelectHandleRight == null) { 10288 mSelectHandleRight = mContext.getResources().getDrawable( 10289 mTextSelectHandleRightRes); 10290 } 10291 mDrawable = mSelectHandleRight; 10292 mHotspotX = mDrawable.getIntrinsicWidth() / 4; 10293 } 10294 10295 @Override 10296 public int getCurrentCursorOffset() { 10297 return TextView.this.getSelectionEnd(); 10298 } 10299 10300 @Override 10301 public void updateSelection(int offset) { 10302 Selection.setSelection((Spannable) mText, getSelectionStart(), offset); 10303 } 10304 10305 @Override 10306 public void updatePosition(float x, float y) { 10307 final int selectionStart = getSelectionStart(); 10308 final int selectionEnd = getSelectionEnd(); 10309 10310 int offset = getOffsetForPosition(x, y); 10311 10312 // No need to redraw when the offset is unchanged 10313 if (offset == selectionEnd) return; 10314 // Handles can not cross and selection is at least one character 10315 if (offset <= selectionStart) offset = selectionStart + 1; 10316 10317 positionAtCursorOffset(offset); 10318 } 10319 10320 public void setActionPopupWindow(ActionPopupWindow actionPopupWindow) { 10321 mActionPopupWindow = actionPopupWindow; 10322 } 10323 } 10324 10325 /** 10326 * A CursorController instance can be used to control a cursor in the text. 10327 * It is not used outside of {@link TextView}. 10328 * @hide 10329 */ 10330 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 10331 /** 10332 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 10333 * See also {@link #hide()}. 10334 */ 10335 public void show(); 10336 10337 /** 10338 * Hide the cursor controller from screen. 10339 * See also {@link #show()}. 10340 */ 10341 public void hide(); 10342 10343 /** 10344 * Called when the view is detached from window. Perform house keeping task, such as 10345 * stopping Runnable thread that would otherwise keep a reference on the context, thus 10346 * preventing the activity from being recycled. 10347 */ 10348 public void onDetached(); 10349 } 10350 10351 private class InsertionPointCursorController implements CursorController { 10352 private static final int DELAY_BEFORE_PASTE_ACTION = 1600; 10353 10354 private InsertionHandleView mHandle; 10355 10356 public void show() { 10357 getHandle().show(DELAY_BEFORE_PASTE_ACTION); 10358 } 10359 10360 public void showImmediately() { 10361 getHandle().show(0); 10362 } 10363 10364 public void hide() { 10365 if (mHandle != null) { 10366 mHandle.hide(); 10367 } 10368 } 10369 10370 public void onTouchModeChanged(boolean isInTouchMode) { 10371 if (!isInTouchMode) { 10372 hide(); 10373 } 10374 } 10375 10376 private InsertionHandleView getHandle() { 10377 if (mHandle == null) { 10378 mHandle = new InsertionHandleView(); 10379 } 10380 return mHandle; 10381 } 10382 10383 @Override 10384 public void onDetached() { 10385 final ViewTreeObserver observer = getViewTreeObserver(); 10386 observer.removeOnTouchModeChangeListener(this); 10387 10388 if (mHandle != null) mHandle.onDetached(); 10389 } 10390 } 10391 10392 private class SelectionModifierCursorController implements CursorController { 10393 private static final int DELAY_BEFORE_REPLACE_ACTION = 1200; 10394 // The cursor controller handles, lazily created when shown. 10395 private SelectionStartHandleView mStartHandle; 10396 private SelectionEndHandleView mEndHandle; 10397 // The offsets of that last touch down event. Remembered to start selection there. 10398 private int mMinTouchOffset, mMaxTouchOffset; 10399 10400 // Double tap detection 10401 private long mPreviousTapUpTime = 0; 10402 private float mPreviousTapPositionX, mPreviousTapPositionY; 10403 10404 SelectionModifierCursorController() { 10405 resetTouchOffsets(); 10406 } 10407 10408 public void show() { 10409 if (isInBatchEditMode()) { 10410 return; 10411 } 10412 10413 // Lazy object creation has to be done before updatePosition() is called. 10414 if (mStartHandle == null) mStartHandle = new SelectionStartHandleView(); 10415 if (mEndHandle == null) mEndHandle = new SelectionEndHandleView(); 10416 10417 mStartHandle.show(); 10418 mEndHandle.show(); 10419 10420 // Make sure both left and right handles share the same ActionPopupWindow (so that 10421 // moving any of the handles hides the action popup). 10422 mStartHandle.showActionPopupWindow(DELAY_BEFORE_REPLACE_ACTION); 10423 mEndHandle.setActionPopupWindow(mStartHandle.getActionPopupWindow()); 10424 10425 hideInsertionPointCursorController(); 10426 hideSuggestions(); 10427 } 10428 10429 public void hide() { 10430 if (mStartHandle != null) mStartHandle.hide(); 10431 if (mEndHandle != null) mEndHandle.hide(); 10432 } 10433 10434 public void onTouchEvent(MotionEvent event) { 10435 // This is done even when the View does not have focus, so that long presses can start 10436 // selection and tap can move cursor from this tap position. 10437 switch (event.getActionMasked()) { 10438 case MotionEvent.ACTION_DOWN: 10439 final float x = event.getX(); 10440 final float y = event.getY(); 10441 10442 // Remember finger down position, to be able to start selection from there 10443 mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y); 10444 10445 // Double tap detection 10446 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 10447 if (duration <= ViewConfiguration.getDoubleTapTimeout() && 10448 isPositionOnText(x, y)) { 10449 final float deltaX = x - mPreviousTapPositionX; 10450 final float deltaY = y - mPreviousTapPositionY; 10451 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 10452 if (distanceSquared < mSquaredTouchSlopDistance) { 10453 startSelectionActionMode(); 10454 mDiscardNextActionUp = true; 10455 } 10456 } 10457 10458 mPreviousTapPositionX = x; 10459 mPreviousTapPositionY = y; 10460 break; 10461 10462 case MotionEvent.ACTION_POINTER_DOWN: 10463 case MotionEvent.ACTION_POINTER_UP: 10464 // Handle multi-point gestures. Keep min and max offset positions. 10465 // Only activated for devices that correctly handle multi-touch. 10466 if (mContext.getPackageManager().hasSystemFeature( 10467 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 10468 updateMinAndMaxOffsets(event); 10469 } 10470 break; 10471 10472 case MotionEvent.ACTION_UP: 10473 mPreviousTapUpTime = SystemClock.uptimeMillis(); 10474 break; 10475 } 10476 } 10477 10478 /** 10479 * @param event 10480 */ 10481 private void updateMinAndMaxOffsets(MotionEvent event) { 10482 int pointerCount = event.getPointerCount(); 10483 for (int index = 0; index < pointerCount; index++) { 10484 int offset = getOffsetForPosition(event.getX(index), event.getY(index)); 10485 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 10486 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 10487 } 10488 } 10489 10490 public int getMinTouchOffset() { 10491 return mMinTouchOffset; 10492 } 10493 10494 public int getMaxTouchOffset() { 10495 return mMaxTouchOffset; 10496 } 10497 10498 public void resetTouchOffsets() { 10499 mMinTouchOffset = mMaxTouchOffset = -1; 10500 } 10501 10502 /** 10503 * @return true iff this controller is currently used to move the selection start. 10504 */ 10505 public boolean isSelectionStartDragged() { 10506 return mStartHandle != null && mStartHandle.isDragging(); 10507 } 10508 10509 public void onTouchModeChanged(boolean isInTouchMode) { 10510 if (!isInTouchMode) { 10511 hide(); 10512 } 10513 } 10514 10515 @Override 10516 public void onDetached() { 10517 final ViewTreeObserver observer = getViewTreeObserver(); 10518 observer.removeOnTouchModeChangeListener(this); 10519 10520 if (mStartHandle != null) mStartHandle.onDetached(); 10521 if (mEndHandle != null) mEndHandle.onDetached(); 10522 } 10523 } 10524 10525 private void hideInsertionPointCursorController() { 10526 // No need to create the controller to hide it. 10527 if (mInsertionPointCursorController != null) { 10528 mInsertionPointCursorController.hide(); 10529 } 10530 } 10531 10532 /** 10533 * Hides the insertion controller and stops text selection mode, hiding the selection controller 10534 */ 10535 private void hideControllers() { 10536 hideInsertionPointCursorController(); 10537 stopSelectionActionMode(); 10538 hideSuggestions(); 10539 } 10540 10541 /** 10542 * Get the character offset closest to the specified absolute position. A typical use case is to 10543 * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. 10544 * 10545 * @param x The horizontal absolute position of a point on screen 10546 * @param y The vertical absolute position of a point on screen 10547 * @return the character offset for the character whose position is closest to the specified 10548 * position. Returns -1 if there is no layout. 10549 */ 10550 public int getOffsetForPosition(float x, float y) { 10551 if (getLayout() == null) return -1; 10552 final int line = getLineAtCoordinate(y); 10553 final int offset = getOffsetAtCoordinate(line, x); 10554 return offset; 10555 } 10556 10557 private float convertToLocalHorizontalCoordinate(float x) { 10558 x -= getTotalPaddingLeft(); 10559 // Clamp the position to inside of the view. 10560 x = Math.max(0.0f, x); 10561 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 10562 x += getScrollX(); 10563 return x; 10564 } 10565 10566 private int getLineAtCoordinate(float y) { 10567 y -= getTotalPaddingTop(); 10568 // Clamp the position to inside of the view. 10569 y = Math.max(0.0f, y); 10570 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 10571 y += getScrollY(); 10572 return getLayout().getLineForVertical((int) y); 10573 } 10574 10575 private int getOffsetAtCoordinate(int line, float x) { 10576 x = convertToLocalHorizontalCoordinate(x); 10577 return getLayout().getOffsetForHorizontal(line, x); 10578 } 10579 10580 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 10581 * in the view. Returns false when the position is in the empty space of left/right of text. 10582 */ 10583 private boolean isPositionOnText(float x, float y) { 10584 if (getLayout() == null) return false; 10585 10586 final int line = getLineAtCoordinate(y); 10587 x = convertToLocalHorizontalCoordinate(x); 10588 10589 if (x < getLayout().getLineLeft(line)) return false; 10590 if (x > getLayout().getLineRight(line)) return false; 10591 return true; 10592 } 10593 10594 @Override 10595 public boolean onDragEvent(DragEvent event) { 10596 switch (event.getAction()) { 10597 case DragEvent.ACTION_DRAG_STARTED: 10598 return hasInsertionController(); 10599 10600 case DragEvent.ACTION_DRAG_ENTERED: 10601 TextView.this.requestFocus(); 10602 return true; 10603 10604 case DragEvent.ACTION_DRAG_LOCATION: 10605 final int offset = getOffsetForPosition(event.getX(), event.getY()); 10606 Selection.setSelection((Spannable)mText, offset); 10607 return true; 10608 10609 case DragEvent.ACTION_DROP: 10610 onDrop(event); 10611 return true; 10612 10613 case DragEvent.ACTION_DRAG_ENDED: 10614 case DragEvent.ACTION_DRAG_EXITED: 10615 default: 10616 return true; 10617 } 10618 } 10619 10620 private void onDrop(DragEvent event) { 10621 StringBuilder content = new StringBuilder(""); 10622 ClipData clipData = event.getClipData(); 10623 final int itemCount = clipData.getItemCount(); 10624 for (int i=0; i < itemCount; i++) { 10625 Item item = clipData.getItemAt(i); 10626 content.append(item.coerceToText(TextView.this.mContext)); 10627 } 10628 10629 final int offset = getOffsetForPosition(event.getX(), event.getY()); 10630 10631 Object localState = event.getLocalState(); 10632 DragLocalState dragLocalState = null; 10633 if (localState instanceof DragLocalState) { 10634 dragLocalState = (DragLocalState) localState; 10635 } 10636 boolean dragDropIntoItself = dragLocalState != null && 10637 dragLocalState.sourceTextView == this; 10638 10639 if (dragDropIntoItself) { 10640 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 10641 // A drop inside the original selection discards the drop. 10642 return; 10643 } 10644 } 10645 10646 final int originalLength = mText.length(); 10647 long minMax = prepareSpacesAroundPaste(offset, offset, content); 10648 int min = extractRangeStartFromLong(minMax); 10649 int max = extractRangeEndFromLong(minMax); 10650 10651 Selection.setSelection((Spannable) mText, max); 10652 ((Editable) mText).replace(min, max, content); 10653 10654 if (dragDropIntoItself) { 10655 int dragSourceStart = dragLocalState.start; 10656 int dragSourceEnd = dragLocalState.end; 10657 if (max <= dragSourceStart) { 10658 // Inserting text before selection has shifted positions 10659 final int shift = mText.length() - originalLength; 10660 dragSourceStart += shift; 10661 dragSourceEnd += shift; 10662 } 10663 10664 // Delete original selection 10665 ((Editable) mText).delete(dragSourceStart, dragSourceEnd); 10666 10667 // Make sure we do not leave two adjacent spaces. 10668 if ((dragSourceStart == 0 || 10669 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 10670 (dragSourceStart == mText.length() || 10671 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 10672 final int pos = dragSourceStart == mText.length() ? 10673 dragSourceStart - 1 : dragSourceStart; 10674 ((Editable) mText).delete(pos, pos + 1); 10675 } 10676 } 10677 } 10678 10679 /** 10680 * @return True if this view supports insertion handles. 10681 */ 10682 boolean hasInsertionController() { 10683 return mInsertionControllerEnabled; 10684 } 10685 10686 /** 10687 * @return True if this view supports selection handles. 10688 */ 10689 boolean hasSelectionController() { 10690 return mSelectionControllerEnabled; 10691 } 10692 10693 InsertionPointCursorController getInsertionController() { 10694 if (!mInsertionControllerEnabled) { 10695 return null; 10696 } 10697 10698 if (mInsertionPointCursorController == null) { 10699 mInsertionPointCursorController = new InsertionPointCursorController(); 10700 10701 final ViewTreeObserver observer = getViewTreeObserver(); 10702 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 10703 } 10704 10705 return mInsertionPointCursorController; 10706 } 10707 10708 SelectionModifierCursorController getSelectionController() { 10709 if (!mSelectionControllerEnabled) { 10710 return null; 10711 } 10712 10713 if (mSelectionModifierCursorController == null) { 10714 mSelectionModifierCursorController = new SelectionModifierCursorController(); 10715 10716 final ViewTreeObserver observer = getViewTreeObserver(); 10717 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 10718 } 10719 10720 return mSelectionModifierCursorController; 10721 } 10722 10723 boolean isInBatchEditMode() { 10724 final InputMethodState ims = mInputMethodState; 10725 if (ims != null) { 10726 return ims.mBatchEditNesting > 0; 10727 } 10728 return mInBatchEditControllers; 10729 } 10730 10731 @Override 10732 protected void resolveTextDirection() { 10733 // Always need to resolve layout direction first 10734 final boolean defaultIsRtl = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL); 10735 10736 // Then resolve text direction on the parent 10737 super.resolveTextDirection(); 10738 10739 // Now, we can select the heuristic 10740 int textDir = getResolvedTextDirection(); 10741 switch (textDir) { 10742 default: 10743 case TEXT_DIRECTION_FIRST_STRONG: 10744 mTextDir = (defaultIsRtl ? TextDirectionHeuristics.FIRSTSTRONG_RTL : 10745 TextDirectionHeuristics.FIRSTSTRONG_LTR); 10746 break; 10747 case TEXT_DIRECTION_ANY_RTL: 10748 mTextDir = TextDirectionHeuristics.ANYRTL_LTR; 10749 break; 10750 case TEXT_DIRECTION_CHAR_COUNT: 10751 mTextDir = (defaultIsRtl ? TextDirectionHeuristics.CHARCOUNT_RTL: 10752 TextDirectionHeuristics.CHARCOUNT_LTR); 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 * Subclasses will need to override this method to implement their own way of resolving 10765 * drawables depending on the layout direction. 10766 * 10767 * A call to the super method will be required from the subclasses implementation. 10768 * 10769 */ 10770 protected void resolveDrawables() { 10771 // No need to resolve twice 10772 if (mResolvedDrawables) { 10773 return; 10774 } 10775 // No drawable to resolve 10776 if (mDrawables == null) { 10777 return; 10778 } 10779 // No relative drawable to resolve 10780 if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) { 10781 mResolvedDrawables = true; 10782 return; 10783 } 10784 10785 Drawables dr = mDrawables; 10786 switch(getResolvedLayoutDirection()) { 10787 case LAYOUT_DIRECTION_RTL: 10788 if (dr.mDrawableStart != null) { 10789 dr.mDrawableRight = dr.mDrawableStart; 10790 10791 dr.mDrawableSizeRight = dr.mDrawableSizeStart; 10792 dr.mDrawableHeightRight = dr.mDrawableHeightStart; 10793 } 10794 if (dr.mDrawableEnd != null) { 10795 dr.mDrawableLeft = dr.mDrawableEnd; 10796 10797 dr.mDrawableSizeLeft = dr.mDrawableSizeEnd; 10798 dr.mDrawableHeightLeft = dr.mDrawableHeightEnd; 10799 } 10800 break; 10801 10802 case LAYOUT_DIRECTION_LTR: 10803 default: 10804 if (dr.mDrawableStart != null) { 10805 dr.mDrawableLeft = dr.mDrawableStart; 10806 10807 dr.mDrawableSizeLeft = dr.mDrawableSizeStart; 10808 dr.mDrawableHeightLeft = dr.mDrawableHeightStart; 10809 } 10810 if (dr.mDrawableEnd != null) { 10811 dr.mDrawableRight = dr.mDrawableEnd; 10812 10813 dr.mDrawableSizeRight = dr.mDrawableSizeEnd; 10814 dr.mDrawableHeightRight = dr.mDrawableHeightEnd; 10815 } 10816 break; 10817 } 10818 mResolvedDrawables = true; 10819 } 10820 10821 protected void resetResolvedDrawables() { 10822 mResolvedDrawables = false; 10823 } 10824 10825 @ViewDebug.ExportedProperty(category = "text") 10826 private CharSequence mText; 10827 private CharSequence mTransformed; 10828 private BufferType mBufferType = BufferType.NORMAL; 10829 10830 private int mInputType = EditorInfo.TYPE_NULL; 10831 private CharSequence mHint; 10832 private Layout mHintLayout; 10833 10834 private KeyListener mInput; 10835 10836 private MovementMethod mMovement; 10837 private TransformationMethod mTransformation; 10838 private boolean mAllowTransformationLengthChange; 10839 private ChangeWatcher mChangeWatcher; 10840 10841 private ArrayList<TextWatcher> mListeners = null; 10842 10843 // display attributes 10844 private final TextPaint mTextPaint; 10845 private boolean mUserSetTextScaleX; 10846 private final Paint mHighlightPaint; 10847 private int mHighlightColor = 0xCC475925; 10848 /** 10849 * This is temporarily visible to fix bug 3085564 in webView. Do not rely on 10850 * this field being protected. Will be restored as private when lineHeight 10851 * feature request 3215097 is implemented 10852 * @hide 10853 */ 10854 protected Layout mLayout; 10855 10856 private long mShowCursor; 10857 private Blink mBlink; 10858 private boolean mCursorVisible = true; 10859 10860 // Cursor Controllers. 10861 private InsertionPointCursorController mInsertionPointCursorController; 10862 private SelectionModifierCursorController mSelectionModifierCursorController; 10863 private ActionMode mSelectionActionMode; 10864 private boolean mInsertionControllerEnabled; 10865 private boolean mSelectionControllerEnabled; 10866 private boolean mInBatchEditControllers; 10867 10868 // These are needed to desambiguate a long click. If the long click comes from ones of these, we 10869 // select from the current cursor position. Otherwise, select from long pressed position. 10870 private boolean mDPadCenterIsDown = false; 10871 private boolean mEnterKeyIsDown = false; 10872 private boolean mContextMenuTriggeredByKey = false; 10873 10874 private boolean mSelectAllOnFocus = false; 10875 10876 private int mGravity = Gravity.TOP | Gravity.START; 10877 private boolean mHorizontallyScrolling; 10878 10879 private int mAutoLinkMask; 10880 private boolean mLinksClickable = true; 10881 10882 private float mSpacingMult = 1; 10883 private float mSpacingAdd = 0; 10884 private boolean mTextIsSelectable = false; 10885 10886 private static final int LINES = 1; 10887 private static final int EMS = LINES; 10888 private static final int PIXELS = 2; 10889 10890 private int mMaximum = Integer.MAX_VALUE; 10891 private int mMaxMode = LINES; 10892 private int mMinimum = 0; 10893 private int mMinMode = LINES; 10894 10895 private int mOldMaximum = mMaximum; 10896 private int mOldMaxMode = mMaxMode; 10897 10898 private int mMaxWidth = Integer.MAX_VALUE; 10899 private int mMaxWidthMode = PIXELS; 10900 private int mMinWidth = 0; 10901 private int mMinWidthMode = PIXELS; 10902 10903 private boolean mSingleLine; 10904 private int mDesiredHeightAtMeasure = -1; 10905 private boolean mIncludePad = true; 10906 10907 // tmp primitives, so we don't alloc them on each draw 10908 private Path mHighlightPath; 10909 private boolean mHighlightPathBogus = true; 10910 private static final RectF sTempRect = new RectF(); 10911 10912 // XXX should be much larger 10913 private static final int VERY_WIDE = 16384; 10914 10915 private static final int BLINK = 500; 10916 10917 private static final int ANIMATED_SCROLL_GAP = 250; 10918 private long mLastScroll; 10919 private Scroller mScroller = null; 10920 10921 private BoringLayout.Metrics mBoring; 10922 private BoringLayout.Metrics mHintBoring; 10923 10924 private BoringLayout mSavedLayout, mSavedHintLayout; 10925 10926 private TextDirectionHeuristic mTextDir = null; 10927 10928 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 10929 private InputFilter[] mFilters = NO_FILTERS; 10930 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 10931 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 10932 // System wide time for last cut or copy action. 10933 private static long sLastCutOrCopyTime; 10934 // Used to highlight a word when it is corrected by the IME 10935 private CorrectionHighlighter mCorrectionHighlighter; 10936 // New state used to change background based on whether this TextView is multiline. 10937 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 10938} 10939