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