TextView.java revision 59f13c7dfb3cb38f03b7cc207d8e381f6274bfef
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 com.android.internal.util.FastMath; 20import com.android.internal.widget.EditableInputConnection; 21 22import org.xmlpull.v1.XmlPullParserException; 23 24import android.R; 25import android.content.ClipData; 26import android.content.ClipData.Item; 27import android.content.ClipboardManager; 28import android.content.Context; 29import android.content.pm.PackageManager; 30import android.content.res.ColorStateList; 31import android.content.res.Resources; 32import android.content.res.TypedArray; 33import android.content.res.XmlResourceParser; 34import android.graphics.Canvas; 35import android.graphics.Color; 36import android.graphics.Paint; 37import android.graphics.Path; 38import android.graphics.Rect; 39import android.graphics.RectF; 40import android.graphics.Typeface; 41import android.graphics.drawable.Drawable; 42import android.inputmethodservice.ExtractEditText; 43import android.net.Uri; 44import android.os.Bundle; 45import android.os.Handler; 46import android.os.Message; 47import android.os.Parcel; 48import android.os.Parcelable; 49import android.os.SystemClock; 50import android.text.BoringLayout; 51import android.text.DynamicLayout; 52import android.text.Editable; 53import android.text.GetChars; 54import android.text.GraphicsOperations; 55import android.text.InputFilter; 56import android.text.InputType; 57import android.text.Layout; 58import android.text.ParcelableSpan; 59import android.text.Selection; 60import android.text.SpanWatcher; 61import android.text.Spannable; 62import android.text.SpannableString; 63import android.text.SpannableStringBuilder; 64import android.text.Spanned; 65import android.text.SpannedString; 66import android.text.StaticLayout; 67import android.text.TextDirectionHeuristic; 68import android.text.TextDirectionHeuristics; 69import android.text.TextDirectionHeuristics.AnyStrong; 70import android.text.TextDirectionHeuristics.CharCount; 71import android.text.TextDirectionHeuristics.FirstStrong; 72import android.text.TextDirectionHeuristics.TextDirectionAlgorithm; 73import android.text.TextDirectionHeuristics.TextDirectionHeuristicImpl; 74import android.text.TextPaint; 75import android.text.TextUtils; 76import android.text.TextWatcher; 77import android.text.method.AllCapsTransformationMethod; 78import android.text.method.ArrowKeyMovementMethod; 79import android.text.method.DateKeyListener; 80import android.text.method.DateTimeKeyListener; 81import android.text.method.DialerKeyListener; 82import android.text.method.DigitsKeyListener; 83import android.text.method.KeyListener; 84import android.text.method.LinkMovementMethod; 85import android.text.method.MetaKeyKeyListener; 86import android.text.method.MovementMethod; 87import android.text.method.PasswordTransformationMethod; 88import android.text.method.SingleLineTransformationMethod; 89import android.text.method.TextKeyListener; 90import android.text.method.TimeKeyListener; 91import android.text.method.TransformationMethod; 92import android.text.method.TransformationMethod2; 93import android.text.method.WordIterator; 94import android.text.style.ClickableSpan; 95import android.text.style.ParagraphStyle; 96import android.text.style.SuggestionSpan; 97import android.text.style.TextAppearanceSpan; 98import android.text.style.URLSpan; 99import android.text.style.UnderlineSpan; 100import android.text.style.UpdateAppearance; 101import android.text.util.Linkify; 102import android.util.AttributeSet; 103import android.util.DisplayMetrics; 104import android.util.FloatMath; 105import android.util.Log; 106import android.util.TypedValue; 107import android.view.ActionMode; 108import android.view.ActionMode.Callback; 109import android.view.ContextMenu; 110import android.view.DragEvent; 111import android.view.Gravity; 112import android.view.HapticFeedbackConstants; 113import android.view.KeyCharacterMap; 114import android.view.KeyEvent; 115import android.view.LayoutInflater; 116import android.view.Menu; 117import android.view.MenuItem; 118import android.view.MotionEvent; 119import android.view.View; 120import android.view.ViewRootImpl; 121import android.view.ViewConfiguration; 122import android.view.ViewDebug; 123import android.view.ViewGroup; 124import android.view.ViewGroup.LayoutParams; 125import android.view.ViewParent; 126import android.view.ViewTreeObserver; 127import android.view.WindowManager; 128import android.view.accessibility.AccessibilityEvent; 129import android.view.accessibility.AccessibilityManager; 130import android.view.accessibility.AccessibilityNodeInfo; 131import android.view.animation.AnimationUtils; 132import android.view.inputmethod.BaseInputConnection; 133import android.view.inputmethod.CompletionInfo; 134import android.view.inputmethod.CorrectionInfo; 135import android.view.inputmethod.EditorInfo; 136import android.view.inputmethod.ExtractedText; 137import android.view.inputmethod.ExtractedTextRequest; 138import android.view.inputmethod.InputConnection; 139import android.view.inputmethod.InputMethodManager; 140import android.widget.RemoteViews.RemoteView; 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 mResolvedDrawables = 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(ViewRootImpl.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(ViewRootImpl.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 /** 5066 * @hide 5067 * @param offsetRequired 5068 */ 5069 @Override 5070 protected int getFadeTop(boolean offsetRequired) { 5071 if (mLayout == null) return 0; 5072 5073 int voffset = 0; 5074 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 5075 voffset = getVerticalOffset(true); 5076 } 5077 5078 if (offsetRequired) voffset += getTopPaddingOffset(); 5079 5080 return getExtendedPaddingTop() + voffset; 5081 } 5082 5083 /** 5084 * @hide 5085 * @param offsetRequired 5086 */ 5087 protected int getFadeHeight(boolean offsetRequired) { 5088 return mLayout != null ? mLayout.getHeight() : 0; 5089 } 5090 5091 @Override 5092 public boolean onKeyDown(int keyCode, KeyEvent event) { 5093 int which = doKeyDown(keyCode, event, null); 5094 if (which == 0) { 5095 // Go through default dispatching. 5096 return super.onKeyDown(keyCode, event); 5097 } 5098 5099 return true; 5100 } 5101 5102 @Override 5103 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 5104 KeyEvent down = KeyEvent.changeAction(event, KeyEvent.ACTION_DOWN); 5105 5106 int which = doKeyDown(keyCode, down, event); 5107 if (which == 0) { 5108 // Go through default dispatching. 5109 return super.onKeyMultiple(keyCode, repeatCount, event); 5110 } 5111 if (which == -1) { 5112 // Consumed the whole thing. 5113 return true; 5114 } 5115 5116 repeatCount--; 5117 5118 // We are going to dispatch the remaining events to either the input 5119 // or movement method. To do this, we will just send a repeated stream 5120 // of down and up events until we have done the complete repeatCount. 5121 // It would be nice if those interfaces had an onKeyMultiple() method, 5122 // but adding that is a more complicated change. 5123 KeyEvent up = KeyEvent.changeAction(event, KeyEvent.ACTION_UP); 5124 if (which == 1) { 5125 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 5126 while (--repeatCount > 0) { 5127 mInput.onKeyDown(this, (Editable)mText, keyCode, down); 5128 mInput.onKeyUp(this, (Editable)mText, keyCode, up); 5129 } 5130 hideErrorIfUnchanged(); 5131 5132 } else if (which == 2) { 5133 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 5134 while (--repeatCount > 0) { 5135 mMovement.onKeyDown(this, (Spannable)mText, keyCode, down); 5136 mMovement.onKeyUp(this, (Spannable)mText, keyCode, up); 5137 } 5138 } 5139 5140 return true; 5141 } 5142 5143 /** 5144 * Returns true if pressing ENTER in this field advances focus instead 5145 * of inserting the character. This is true mostly in single-line fields, 5146 * but also in mail addresses and subjects which will display on multiple 5147 * lines but where it doesn't make sense to insert newlines. 5148 */ 5149 private boolean shouldAdvanceFocusOnEnter() { 5150 if (mInput == null) { 5151 return false; 5152 } 5153 5154 if (mSingleLine) { 5155 return true; 5156 } 5157 5158 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 5159 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 5160 if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS 5161 || variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { 5162 return true; 5163 } 5164 } 5165 5166 return false; 5167 } 5168 5169 /** 5170 * Returns true if pressing TAB in this field advances focus instead 5171 * of inserting the character. Insert tabs only in multi-line editors. 5172 */ 5173 private boolean shouldAdvanceFocusOnTab() { 5174 if (mInput != null && !mSingleLine) { 5175 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 5176 int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; 5177 if (variation == EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE 5178 || variation == EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) { 5179 return false; 5180 } 5181 } 5182 } 5183 return true; 5184 } 5185 5186 private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { 5187 if (!isEnabled()) { 5188 return 0; 5189 } 5190 5191 switch (keyCode) { 5192 case KeyEvent.KEYCODE_ENTER: 5193 mEnterKeyIsDown = true; 5194 if (event.hasNoModifiers()) { 5195 // When mInputContentType is set, we know that we are 5196 // running in a "modern" cupcake environment, so don't need 5197 // to worry about the application trying to capture 5198 // enter key events. 5199 if (mInputContentType != null) { 5200 // If there is an action listener, given them a 5201 // chance to consume the event. 5202 if (mInputContentType.onEditorActionListener != null && 5203 mInputContentType.onEditorActionListener.onEditorAction( 5204 this, EditorInfo.IME_NULL, event)) { 5205 mInputContentType.enterDown = true; 5206 // We are consuming the enter key for them. 5207 return -1; 5208 } 5209 } 5210 5211 // If our editor should move focus when enter is pressed, or 5212 // this is a generated event from an IME action button, then 5213 // don't let it be inserted into the text. 5214 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 5215 || shouldAdvanceFocusOnEnter()) { 5216 if (mOnClickListener != null) { 5217 return 0; 5218 } 5219 return -1; 5220 } 5221 } 5222 break; 5223 5224 case KeyEvent.KEYCODE_DPAD_CENTER: 5225 mDPadCenterIsDown = true; 5226 if (event.hasNoModifiers()) { 5227 if (shouldAdvanceFocusOnEnter()) { 5228 return 0; 5229 } 5230 } 5231 break; 5232 5233 case KeyEvent.KEYCODE_TAB: 5234 if (event.hasNoModifiers() || event.hasModifiers(KeyEvent.META_SHIFT_ON)) { 5235 if (shouldAdvanceFocusOnTab()) { 5236 return 0; 5237 } 5238 } 5239 break; 5240 5241 // Has to be done on key down (and not on key up) to correctly be intercepted. 5242 case KeyEvent.KEYCODE_BACK: 5243 if (mSelectionActionMode != null) { 5244 stopSelectionActionMode(); 5245 return -1; 5246 } 5247 break; 5248 } 5249 5250 if (mInput != null) { 5251 resetErrorChangedFlag(); 5252 5253 boolean doDown = true; 5254 if (otherEvent != null) { 5255 try { 5256 beginBatchEdit(); 5257 final boolean handled = mInput.onKeyOther(this, (Editable) mText, otherEvent); 5258 hideErrorIfUnchanged(); 5259 doDown = false; 5260 if (handled) { 5261 return -1; 5262 } 5263 } catch (AbstractMethodError e) { 5264 // onKeyOther was added after 1.0, so if it isn't 5265 // implemented we need to try to dispatch as a regular down. 5266 } finally { 5267 endBatchEdit(); 5268 } 5269 } 5270 5271 if (doDown) { 5272 beginBatchEdit(); 5273 final boolean handled = mInput.onKeyDown(this, (Editable) mText, keyCode, event); 5274 endBatchEdit(); 5275 hideErrorIfUnchanged(); 5276 if (handled) return 1; 5277 } 5278 } 5279 5280 // bug 650865: sometimes we get a key event before a layout. 5281 // don't try to move around if we don't know the layout. 5282 5283 if (mMovement != null && mLayout != null) { 5284 boolean doDown = true; 5285 if (otherEvent != null) { 5286 try { 5287 boolean handled = mMovement.onKeyOther(this, (Spannable) mText, 5288 otherEvent); 5289 doDown = false; 5290 if (handled) { 5291 return -1; 5292 } 5293 } catch (AbstractMethodError e) { 5294 // onKeyOther was added after 1.0, so if it isn't 5295 // implemented we need to try to dispatch as a regular down. 5296 } 5297 } 5298 if (doDown) { 5299 if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) 5300 return 2; 5301 } 5302 } 5303 5304 return 0; 5305 } 5306 5307 /** 5308 * Resets the mErrorWasChanged flag, so that future calls to {@link #setError(CharSequence)} 5309 * can be recorded. 5310 * @hide 5311 */ 5312 public void resetErrorChangedFlag() { 5313 /* 5314 * Keep track of what the error was before doing the input 5315 * so that if an input filter changed the error, we leave 5316 * that error showing. Otherwise, we take down whatever 5317 * error was showing when the user types something. 5318 */ 5319 mErrorWasChanged = false; 5320 } 5321 5322 /** 5323 * @hide 5324 */ 5325 public void hideErrorIfUnchanged() { 5326 if (mError != null && !mErrorWasChanged) { 5327 setError(null, null); 5328 } 5329 } 5330 5331 @Override 5332 public boolean onKeyUp(int keyCode, KeyEvent event) { 5333 if (!isEnabled()) { 5334 return super.onKeyUp(keyCode, event); 5335 } 5336 5337 switch (keyCode) { 5338 case KeyEvent.KEYCODE_DPAD_CENTER: 5339 mDPadCenterIsDown = false; 5340 if (event.hasNoModifiers()) { 5341 /* 5342 * If there is a click listener, just call through to 5343 * super, which will invoke it. 5344 * 5345 * If there isn't a click listener, try to show the soft 5346 * input method. (It will also 5347 * call performClick(), but that won't do anything in 5348 * this case.) 5349 */ 5350 if (mOnClickListener == null) { 5351 if (mMovement != null && mText instanceof Editable 5352 && mLayout != null && onCheckIsTextEditor()) { 5353 InputMethodManager imm = InputMethodManager.peekInstance(); 5354 if (imm != null) { 5355 imm.viewClicked(this); 5356 imm.showSoftInput(this, 0); 5357 } 5358 } 5359 } 5360 } 5361 return super.onKeyUp(keyCode, event); 5362 5363 case KeyEvent.KEYCODE_ENTER: 5364 mEnterKeyIsDown = false; 5365 if (event.hasNoModifiers()) { 5366 if (mInputContentType != null 5367 && mInputContentType.onEditorActionListener != null 5368 && mInputContentType.enterDown) { 5369 mInputContentType.enterDown = false; 5370 if (mInputContentType.onEditorActionListener.onEditorAction( 5371 this, EditorInfo.IME_NULL, event)) { 5372 return true; 5373 } 5374 } 5375 5376 if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0 5377 || shouldAdvanceFocusOnEnter()) { 5378 /* 5379 * If there is a click listener, just call through to 5380 * super, which will invoke it. 5381 * 5382 * If there isn't a click listener, try to advance focus, 5383 * but still call through to super, which will reset the 5384 * pressed state and longpress state. (It will also 5385 * call performClick(), but that won't do anything in 5386 * this case.) 5387 */ 5388 if (mOnClickListener == null) { 5389 View v = focusSearch(FOCUS_DOWN); 5390 5391 if (v != null) { 5392 if (!v.requestFocus(FOCUS_DOWN)) { 5393 throw new IllegalStateException( 5394 "focus search returned a view " + 5395 "that wasn't able to take focus!"); 5396 } 5397 5398 /* 5399 * Return true because we handled the key; super 5400 * will return false because there was no click 5401 * listener. 5402 */ 5403 super.onKeyUp(keyCode, event); 5404 return true; 5405 } else if ((event.getFlags() 5406 & KeyEvent.FLAG_EDITOR_ACTION) != 0) { 5407 // No target for next focus, but make sure the IME 5408 // if this came from it. 5409 InputMethodManager imm = InputMethodManager.peekInstance(); 5410 if (imm != null && imm.isActive(this)) { 5411 imm.hideSoftInputFromWindow(getWindowToken(), 0); 5412 } 5413 } 5414 } 5415 } 5416 return super.onKeyUp(keyCode, event); 5417 } 5418 break; 5419 } 5420 5421 if (mInput != null) 5422 if (mInput.onKeyUp(this, (Editable) mText, keyCode, event)) 5423 return true; 5424 5425 if (mMovement != null && mLayout != null) 5426 if (mMovement.onKeyUp(this, (Spannable) mText, keyCode, event)) 5427 return true; 5428 5429 return super.onKeyUp(keyCode, event); 5430 } 5431 5432 @Override public boolean onCheckIsTextEditor() { 5433 return mInputType != EditorInfo.TYPE_NULL; 5434 } 5435 5436 @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 5437 if (onCheckIsTextEditor() && isEnabled()) { 5438 if (mInputMethodState == null) { 5439 mInputMethodState = new InputMethodState(); 5440 } 5441 outAttrs.inputType = mInputType; 5442 if (mInputContentType != null) { 5443 outAttrs.imeOptions = mInputContentType.imeOptions; 5444 outAttrs.privateImeOptions = mInputContentType.privateImeOptions; 5445 outAttrs.actionLabel = mInputContentType.imeActionLabel; 5446 outAttrs.actionId = mInputContentType.imeActionId; 5447 outAttrs.extras = mInputContentType.extras; 5448 } else { 5449 outAttrs.imeOptions = EditorInfo.IME_NULL; 5450 } 5451 if (focusSearch(FOCUS_DOWN) != null) { 5452 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 5453 } 5454 if (focusSearch(FOCUS_UP) != null) { 5455 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_PREVIOUS; 5456 } 5457 if ((outAttrs.imeOptions&EditorInfo.IME_MASK_ACTION) 5458 == EditorInfo.IME_ACTION_UNSPECIFIED) { 5459 if ((outAttrs.imeOptions&EditorInfo.IME_FLAG_NAVIGATE_NEXT) != 0) { 5460 // An action has not been set, but the enter key will move to 5461 // the next focus, so set the action to that. 5462 outAttrs.imeOptions |= EditorInfo.IME_ACTION_NEXT; 5463 } else { 5464 // An action has not been set, and there is no focus to move 5465 // to, so let's just supply a "done" action. 5466 outAttrs.imeOptions |= EditorInfo.IME_ACTION_DONE; 5467 } 5468 if (!shouldAdvanceFocusOnEnter()) { 5469 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5470 } 5471 } 5472 if (isMultilineInputType(outAttrs.inputType)) { 5473 // Multi-line text editors should always show an enter key. 5474 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_ENTER_ACTION; 5475 } 5476 outAttrs.hintText = mHint; 5477 if (mText instanceof Editable) { 5478 InputConnection ic = new EditableInputConnection(this); 5479 outAttrs.initialSelStart = getSelectionStart(); 5480 outAttrs.initialSelEnd = getSelectionEnd(); 5481 outAttrs.initialCapsMode = ic.getCursorCapsMode(mInputType); 5482 return ic; 5483 } 5484 } 5485 return null; 5486 } 5487 5488 /** 5489 * If this TextView contains editable content, extract a portion of it 5490 * based on the information in <var>request</var> in to <var>outText</var>. 5491 * @return Returns true if the text was successfully extracted, else false. 5492 */ 5493 public boolean extractText(ExtractedTextRequest request, 5494 ExtractedText outText) { 5495 return extractTextInternal(request, EXTRACT_UNKNOWN, EXTRACT_UNKNOWN, 5496 EXTRACT_UNKNOWN, outText); 5497 } 5498 5499 static final int EXTRACT_NOTHING = -2; 5500 static final int EXTRACT_UNKNOWN = -1; 5501 5502 boolean extractTextInternal(ExtractedTextRequest request, 5503 int partialStartOffset, int partialEndOffset, int delta, 5504 ExtractedText outText) { 5505 final CharSequence content = mText; 5506 if (content != null) { 5507 if (partialStartOffset != EXTRACT_NOTHING) { 5508 final int N = content.length(); 5509 if (partialStartOffset < 0) { 5510 outText.partialStartOffset = outText.partialEndOffset = -1; 5511 partialStartOffset = 0; 5512 partialEndOffset = N; 5513 } else { 5514 // Now use the delta to determine the actual amount of text 5515 // we need. 5516 partialEndOffset += delta; 5517 // Adjust offsets to ensure we contain full spans. 5518 if (content instanceof Spanned) { 5519 Spanned spanned = (Spanned)content; 5520 Object[] spans = spanned.getSpans(partialStartOffset, 5521 partialEndOffset, ParcelableSpan.class); 5522 int i = spans.length; 5523 while (i > 0) { 5524 i--; 5525 int j = spanned.getSpanStart(spans[i]); 5526 if (j < partialStartOffset) partialStartOffset = j; 5527 j = spanned.getSpanEnd(spans[i]); 5528 if (j > partialEndOffset) partialEndOffset = j; 5529 } 5530 } 5531 outText.partialStartOffset = partialStartOffset; 5532 outText.partialEndOffset = partialEndOffset - delta; 5533 5534 if (partialStartOffset > N) { 5535 partialStartOffset = N; 5536 } else if (partialStartOffset < 0) { 5537 partialStartOffset = 0; 5538 } 5539 if (partialEndOffset > N) { 5540 partialEndOffset = N; 5541 } else if (partialEndOffset < 0) { 5542 partialEndOffset = 0; 5543 } 5544 } 5545 if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { 5546 outText.text = content.subSequence(partialStartOffset, 5547 partialEndOffset); 5548 } else { 5549 outText.text = TextUtils.substring(content, partialStartOffset, 5550 partialEndOffset); 5551 } 5552 } else { 5553 outText.partialStartOffset = 0; 5554 outText.partialEndOffset = 0; 5555 outText.text = ""; 5556 } 5557 outText.flags = 0; 5558 if (MetaKeyKeyListener.getMetaState(mText, MetaKeyKeyListener.META_SELECTING) != 0) { 5559 outText.flags |= ExtractedText.FLAG_SELECTING; 5560 } 5561 if (mSingleLine) { 5562 outText.flags |= ExtractedText.FLAG_SINGLE_LINE; 5563 } 5564 outText.startOffset = 0; 5565 outText.selectionStart = getSelectionStart(); 5566 outText.selectionEnd = getSelectionEnd(); 5567 return true; 5568 } 5569 return false; 5570 } 5571 5572 boolean reportExtractedText() { 5573 final InputMethodState ims = mInputMethodState; 5574 if (ims != null) { 5575 final boolean contentChanged = ims.mContentChanged; 5576 if (contentChanged || ims.mSelectionModeChanged) { 5577 ims.mContentChanged = false; 5578 ims.mSelectionModeChanged = false; 5579 final ExtractedTextRequest req = mInputMethodState.mExtracting; 5580 if (req != null) { 5581 InputMethodManager imm = InputMethodManager.peekInstance(); 5582 if (imm != null) { 5583 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Retrieving extracted start=" 5584 + ims.mChangedStart + " end=" + ims.mChangedEnd 5585 + " delta=" + ims.mChangedDelta); 5586 if (ims.mChangedStart < 0 && !contentChanged) { 5587 ims.mChangedStart = EXTRACT_NOTHING; 5588 } 5589 if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, 5590 ims.mChangedDelta, ims.mTmpExtracted)) { 5591 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Reporting extracted start=" 5592 + ims.mTmpExtracted.partialStartOffset 5593 + " end=" + ims.mTmpExtracted.partialEndOffset 5594 + ": " + ims.mTmpExtracted.text); 5595 imm.updateExtractedText(this, req.token, 5596 mInputMethodState.mTmpExtracted); 5597 ims.mChangedStart = EXTRACT_UNKNOWN; 5598 ims.mChangedEnd = EXTRACT_UNKNOWN; 5599 ims.mChangedDelta = 0; 5600 ims.mContentChanged = false; 5601 return true; 5602 } 5603 } 5604 } 5605 } 5606 } 5607 return false; 5608 } 5609 5610 /** 5611 * This is used to remove all style-impacting spans from text before new 5612 * extracted text is being replaced into it, so that we don't have any 5613 * lingering spans applied during the replace. 5614 */ 5615 static void removeParcelableSpans(Spannable spannable, int start, int end) { 5616 Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); 5617 int i = spans.length; 5618 while (i > 0) { 5619 i--; 5620 spannable.removeSpan(spans[i]); 5621 } 5622 } 5623 5624 /** 5625 * Apply to this text view the given extracted text, as previously 5626 * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. 5627 */ 5628 public void setExtractedText(ExtractedText text) { 5629 Editable content = getEditableText(); 5630 if (text.text != null) { 5631 if (content == null) { 5632 setText(text.text, TextView.BufferType.EDITABLE); 5633 } else if (text.partialStartOffset < 0) { 5634 removeParcelableSpans(content, 0, content.length()); 5635 content.replace(0, content.length(), text.text); 5636 } else { 5637 final int N = content.length(); 5638 int start = text.partialStartOffset; 5639 if (start > N) start = N; 5640 int end = text.partialEndOffset; 5641 if (end > N) end = N; 5642 removeParcelableSpans(content, start, end); 5643 content.replace(start, end, text.text); 5644 } 5645 } 5646 5647 // Now set the selection position... make sure it is in range, to 5648 // avoid crashes. If this is a partial update, it is possible that 5649 // the underlying text may have changed, causing us problems here. 5650 // Also we just don't want to trust clients to do the right thing. 5651 Spannable sp = (Spannable)getText(); 5652 final int N = sp.length(); 5653 int start = text.selectionStart; 5654 if (start < 0) start = 0; 5655 else if (start > N) start = N; 5656 int end = text.selectionEnd; 5657 if (end < 0) end = 0; 5658 else if (end > N) end = N; 5659 Selection.setSelection(sp, start, end); 5660 5661 // Finally, update the selection mode. 5662 if ((text.flags&ExtractedText.FLAG_SELECTING) != 0) { 5663 MetaKeyKeyListener.startSelecting(this, sp); 5664 } else { 5665 MetaKeyKeyListener.stopSelecting(this, sp); 5666 } 5667 } 5668 5669 /** 5670 * @hide 5671 */ 5672 public void setExtracting(ExtractedTextRequest req) { 5673 if (mInputMethodState != null) { 5674 mInputMethodState.mExtracting = req; 5675 } 5676 // This stops a possible text selection mode. Maybe not intended. 5677 hideControllers(); 5678 } 5679 5680 /** 5681 * Called by the framework in response to a text completion from 5682 * the current input method, provided by it calling 5683 * {@link InputConnection#commitCompletion 5684 * InputConnection.commitCompletion()}. The default implementation does 5685 * nothing; text views that are supporting auto-completion should override 5686 * this to do their desired behavior. 5687 * 5688 * @param text The auto complete text the user has selected. 5689 */ 5690 public void onCommitCompletion(CompletionInfo text) { 5691 // intentionally empty 5692 } 5693 5694 /** 5695 * Called by the framework in response to a text auto-correction (such as fixing a typo using a 5696 * a dictionnary) from the current input method, provided by it calling 5697 * {@link InputConnection#commitCorrection} InputConnection.commitCorrection()}. The default 5698 * implementation flashes the background of the corrected word to provide feedback to the user. 5699 * 5700 * @param info The auto correct info about the text that was corrected. 5701 */ 5702 public void onCommitCorrection(CorrectionInfo info) { 5703 if (mCorrectionHighlighter == null) { 5704 mCorrectionHighlighter = new CorrectionHighlighter(); 5705 } else { 5706 mCorrectionHighlighter.invalidate(false); 5707 } 5708 5709 mCorrectionHighlighter.highlight(info); 5710 } 5711 5712 private class CorrectionHighlighter { 5713 private final Path mPath = new Path(); 5714 private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 5715 private int mStart, mEnd; 5716 private long mFadingStartTime; 5717 private final static int FADE_OUT_DURATION = 400; 5718 5719 public CorrectionHighlighter() { 5720 mPaint.setCompatibilityScaling(getResources().getCompatibilityInfo().applicationScale); 5721 mPaint.setStyle(Paint.Style.FILL); 5722 } 5723 5724 public void highlight(CorrectionInfo info) { 5725 mStart = info.getOffset(); 5726 mEnd = mStart + info.getNewText().length(); 5727 mFadingStartTime = SystemClock.uptimeMillis(); 5728 5729 if (mStart < 0 || mEnd < 0) { 5730 stopAnimation(); 5731 } 5732 } 5733 5734 public void draw(Canvas canvas, int cursorOffsetVertical) { 5735 if (updatePath() && updatePaint()) { 5736 if (cursorOffsetVertical != 0) { 5737 canvas.translate(0, cursorOffsetVertical); 5738 } 5739 5740 canvas.drawPath(mPath, mPaint); 5741 5742 if (cursorOffsetVertical != 0) { 5743 canvas.translate(0, -cursorOffsetVertical); 5744 } 5745 invalidate(true); 5746 } else { 5747 stopAnimation(); 5748 invalidate(false); 5749 } 5750 } 5751 5752 private boolean updatePaint() { 5753 final long duration = SystemClock.uptimeMillis() - mFadingStartTime; 5754 if (duration > FADE_OUT_DURATION) return false; 5755 5756 final float coef = 1.0f - (float) duration / FADE_OUT_DURATION; 5757 final int highlightColorAlpha = Color.alpha(mHighlightColor); 5758 final int color = (mHighlightColor & 0x00FFFFFF) + 5759 ((int) (highlightColorAlpha * coef) << 24); 5760 mPaint.setColor(color); 5761 return true; 5762 } 5763 5764 private boolean updatePath() { 5765 final Layout layout = TextView.this.mLayout; 5766 if (layout == null) return false; 5767 5768 // Update in case text is edited while the animation is run 5769 final int length = mText.length(); 5770 int start = Math.min(length, mStart); 5771 int end = Math.min(length, mEnd); 5772 5773 mPath.reset(); 5774 TextView.this.mLayout.getSelectionPath(start, end, mPath); 5775 return true; 5776 } 5777 5778 private void invalidate(boolean delayed) { 5779 if (TextView.this.mLayout == null) return; 5780 5781 synchronized (sTempRect) { 5782 mPath.computeBounds(sTempRect, false); 5783 5784 int left = getCompoundPaddingLeft(); 5785 int top = getExtendedPaddingTop() + getVerticalOffset(true); 5786 5787 if (delayed) { 5788 TextView.this.postInvalidateDelayed(16, // 60 Hz update 5789 left + (int) sTempRect.left, top + (int) sTempRect.top, 5790 left + (int) sTempRect.right, top + (int) sTempRect.bottom); 5791 } else { 5792 TextView.this.postInvalidate((int) sTempRect.left, (int) sTempRect.top, 5793 (int) sTempRect.right, (int) sTempRect.bottom); 5794 } 5795 } 5796 } 5797 5798 private void stopAnimation() { 5799 TextView.this.mCorrectionHighlighter = null; 5800 } 5801 } 5802 5803 public void beginBatchEdit() { 5804 mInBatchEditControllers = true; 5805 final InputMethodState ims = mInputMethodState; 5806 if (ims != null) { 5807 int nesting = ++ims.mBatchEditNesting; 5808 if (nesting == 1) { 5809 ims.mCursorChanged = false; 5810 ims.mChangedDelta = 0; 5811 if (ims.mContentChanged) { 5812 // We already have a pending change from somewhere else, 5813 // so turn this into a full update. 5814 ims.mChangedStart = 0; 5815 ims.mChangedEnd = mText.length(); 5816 } else { 5817 ims.mChangedStart = EXTRACT_UNKNOWN; 5818 ims.mChangedEnd = EXTRACT_UNKNOWN; 5819 ims.mContentChanged = false; 5820 } 5821 onBeginBatchEdit(); 5822 } 5823 } 5824 } 5825 5826 public void endBatchEdit() { 5827 mInBatchEditControllers = false; 5828 final InputMethodState ims = mInputMethodState; 5829 if (ims != null) { 5830 int nesting = --ims.mBatchEditNesting; 5831 if (nesting == 0) { 5832 finishBatchEdit(ims); 5833 } 5834 } 5835 } 5836 5837 void ensureEndedBatchEdit() { 5838 final InputMethodState ims = mInputMethodState; 5839 if (ims != null && ims.mBatchEditNesting != 0) { 5840 ims.mBatchEditNesting = 0; 5841 finishBatchEdit(ims); 5842 } 5843 } 5844 5845 void finishBatchEdit(final InputMethodState ims) { 5846 onEndBatchEdit(); 5847 5848 if (ims.mContentChanged || ims.mSelectionModeChanged) { 5849 updateAfterEdit(); 5850 reportExtractedText(); 5851 } else if (ims.mCursorChanged) { 5852 // Cheezy way to get us to report the current cursor location. 5853 invalidateCursor(); 5854 } 5855 } 5856 5857 void updateAfterEdit() { 5858 invalidate(); 5859 int curs = getSelectionStart(); 5860 5861 if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 5862 registerForPreDraw(); 5863 } 5864 5865 if (curs >= 0) { 5866 mHighlightPathBogus = true; 5867 makeBlink(); 5868 bringPointIntoView(curs); 5869 } 5870 5871 checkForResize(); 5872 } 5873 5874 /** 5875 * Called by the framework in response to a request to begin a batch 5876 * of edit operations through a call to link {@link #beginBatchEdit()}. 5877 */ 5878 public void onBeginBatchEdit() { 5879 // intentionally empty 5880 } 5881 5882 /** 5883 * Called by the framework in response to a request to end a batch 5884 * of edit operations through a call to link {@link #endBatchEdit}. 5885 */ 5886 public void onEndBatchEdit() { 5887 // intentionally empty 5888 } 5889 5890 /** 5891 * Called by the framework in response to a private command from the 5892 * current method, provided by it calling 5893 * {@link InputConnection#performPrivateCommand 5894 * InputConnection.performPrivateCommand()}. 5895 * 5896 * @param action The action name of the command. 5897 * @param data Any additional data for the command. This may be null. 5898 * @return Return true if you handled the command, else false. 5899 */ 5900 public boolean onPrivateIMECommand(String action, Bundle data) { 5901 return false; 5902 } 5903 5904 private void nullLayouts() { 5905 if (mLayout instanceof BoringLayout && mSavedLayout == null) { 5906 mSavedLayout = (BoringLayout) mLayout; 5907 } 5908 if (mHintLayout instanceof BoringLayout && mSavedHintLayout == null) { 5909 mSavedHintLayout = (BoringLayout) mHintLayout; 5910 } 5911 5912 mLayout = mHintLayout = null; 5913 5914 // Since it depends on the value of mLayout 5915 prepareCursorControllers(); 5916 } 5917 5918 /** 5919 * Make a new Layout based on the already-measured size of the view, 5920 * on the assumption that it was measured correctly at some point. 5921 */ 5922 private void assumeLayout() { 5923 int width = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 5924 5925 if (width < 1) { 5926 width = 0; 5927 } 5928 5929 int physicalWidth = width; 5930 5931 if (mHorizontallyScrolling) { 5932 width = VERY_WIDE; 5933 } 5934 5935 makeNewLayout(width, physicalWidth, UNKNOWN_BORING, UNKNOWN_BORING, 5936 physicalWidth, false); 5937 } 5938 5939 @Override 5940 protected void resetResolvedLayoutDirection() { 5941 super.resetResolvedLayoutDirection(); 5942 5943 if (mLayoutAlignment != null && 5944 (mTextAlign == TextAlign.VIEW_START || 5945 mTextAlign == TextAlign.VIEW_END)) { 5946 mLayoutAlignment = null; 5947 } 5948 } 5949 5950 private Layout.Alignment getLayoutAlignment() { 5951 if (mLayoutAlignment == null) { 5952 Layout.Alignment alignment; 5953 TextAlign textAlign = mTextAlign; 5954 switch (textAlign) { 5955 case INHERIT: 5956 // fall through to gravity temporarily 5957 // intention is to inherit value through view hierarchy. 5958 case GRAVITY: 5959 switch (mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) { 5960 case Gravity.START: 5961 alignment = Layout.Alignment.ALIGN_NORMAL; 5962 break; 5963 case Gravity.END: 5964 alignment = Layout.Alignment.ALIGN_OPPOSITE; 5965 break; 5966 case Gravity.LEFT: 5967 alignment = Layout.Alignment.ALIGN_LEFT; 5968 break; 5969 case Gravity.RIGHT: 5970 alignment = Layout.Alignment.ALIGN_RIGHT; 5971 break; 5972 case Gravity.CENTER_HORIZONTAL: 5973 alignment = Layout.Alignment.ALIGN_CENTER; 5974 break; 5975 default: 5976 alignment = Layout.Alignment.ALIGN_NORMAL; 5977 break; 5978 } 5979 break; 5980 case TEXT_START: 5981 alignment = Layout.Alignment.ALIGN_NORMAL; 5982 break; 5983 case TEXT_END: 5984 alignment = Layout.Alignment.ALIGN_OPPOSITE; 5985 break; 5986 case CENTER: 5987 alignment = Layout.Alignment.ALIGN_CENTER; 5988 break; 5989 case VIEW_START: 5990 alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 5991 Layout.Alignment.ALIGN_RIGHT : Layout.Alignment.ALIGN_LEFT; 5992 break; 5993 case VIEW_END: 5994 alignment = (getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) ? 5995 Layout.Alignment.ALIGN_LEFT : Layout.Alignment.ALIGN_RIGHT; 5996 break; 5997 default: 5998 alignment = Layout.Alignment.ALIGN_NORMAL; 5999 break; 6000 } 6001 mLayoutAlignment = alignment; 6002 } 6003 return mLayoutAlignment; 6004 } 6005 6006 /** 6007 * The width passed in is now the desired layout width, 6008 * not the full view width with padding. 6009 * {@hide} 6010 */ 6011 protected void makeNewLayout(int w, int hintWidth, 6012 BoringLayout.Metrics boring, 6013 BoringLayout.Metrics hintBoring, 6014 int ellipsisWidth, boolean bringIntoView) { 6015 stopMarquee(); 6016 6017 mHighlightPathBogus = true; 6018 6019 if (w < 0) { 6020 w = 0; 6021 } 6022 if (hintWidth < 0) { 6023 hintWidth = 0; 6024 } 6025 6026 Layout.Alignment alignment = getLayoutAlignment(); 6027 boolean shouldEllipsize = mEllipsize != null && mInput == null; 6028 6029 if (mTextDir == null) { 6030 resolveTextDirection(); 6031 } 6032 if (mText instanceof Spannable) { 6033 mLayout = new DynamicLayout(mText, mTransformed, mTextPaint, w, 6034 alignment, mTextDir, mSpacingMult, 6035 mSpacingAdd, mIncludePad, mInput == null ? mEllipsize : null, 6036 ellipsisWidth); 6037 } else { 6038 if (boring == UNKNOWN_BORING) { 6039 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6040 if (boring != null) { 6041 mBoring = boring; 6042 } 6043 } 6044 6045 if (boring != null) { 6046 if (boring.width <= w && 6047 (mEllipsize == null || boring.width <= ellipsisWidth)) { 6048 if (mSavedLayout != null) { 6049 mLayout = mSavedLayout. 6050 replaceOrMake(mTransformed, mTextPaint, 6051 w, alignment, mSpacingMult, mSpacingAdd, 6052 boring, mIncludePad); 6053 } else { 6054 mLayout = BoringLayout.make(mTransformed, mTextPaint, 6055 w, alignment, mSpacingMult, mSpacingAdd, 6056 boring, mIncludePad); 6057 } 6058 6059 mSavedLayout = (BoringLayout) mLayout; 6060 } else if (shouldEllipsize && boring.width <= w) { 6061 if (mSavedLayout != null) { 6062 mLayout = mSavedLayout. 6063 replaceOrMake(mTransformed, mTextPaint, 6064 w, alignment, mSpacingMult, mSpacingAdd, 6065 boring, mIncludePad, mEllipsize, 6066 ellipsisWidth); 6067 } else { 6068 mLayout = BoringLayout.make(mTransformed, mTextPaint, 6069 w, alignment, mSpacingMult, mSpacingAdd, 6070 boring, mIncludePad, mEllipsize, 6071 ellipsisWidth); 6072 } 6073 } else if (shouldEllipsize) { 6074 mLayout = new StaticLayout(mTransformed, 6075 0, mTransformed.length(), 6076 mTextPaint, w, alignment, mTextDir, mSpacingMult, 6077 mSpacingAdd, mIncludePad, mEllipsize, 6078 ellipsisWidth); 6079 } else { 6080 mLayout = new StaticLayout(mTransformed, mTextPaint, 6081 w, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6082 mIncludePad); 6083 } 6084 } else if (shouldEllipsize) { 6085 mLayout = new StaticLayout(mTransformed, 6086 0, mTransformed.length(), 6087 mTextPaint, w, alignment, mTextDir, mSpacingMult, 6088 mSpacingAdd, mIncludePad, mEllipsize, 6089 ellipsisWidth); 6090 } else { 6091 mLayout = new StaticLayout(mTransformed, mTextPaint, 6092 w, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6093 mIncludePad); 6094 } 6095 } 6096 6097 shouldEllipsize = mEllipsize != null; 6098 mHintLayout = null; 6099 6100 if (mHint != null) { 6101 if (shouldEllipsize) hintWidth = w; 6102 6103 if (hintBoring == UNKNOWN_BORING) { 6104 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mTextDir, 6105 mHintBoring); 6106 if (hintBoring != null) { 6107 mHintBoring = hintBoring; 6108 } 6109 } 6110 6111 if (hintBoring != null) { 6112 if (hintBoring.width <= hintWidth && 6113 (!shouldEllipsize || hintBoring.width <= ellipsisWidth)) { 6114 if (mSavedHintLayout != null) { 6115 mHintLayout = mSavedHintLayout. 6116 replaceOrMake(mHint, mTextPaint, 6117 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6118 hintBoring, mIncludePad); 6119 } else { 6120 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6121 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6122 hintBoring, mIncludePad); 6123 } 6124 6125 mSavedHintLayout = (BoringLayout) mHintLayout; 6126 } else if (shouldEllipsize && hintBoring.width <= hintWidth) { 6127 if (mSavedHintLayout != null) { 6128 mHintLayout = mSavedHintLayout. 6129 replaceOrMake(mHint, mTextPaint, 6130 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6131 hintBoring, mIncludePad, mEllipsize, 6132 ellipsisWidth); 6133 } else { 6134 mHintLayout = BoringLayout.make(mHint, mTextPaint, 6135 hintWidth, alignment, mSpacingMult, mSpacingAdd, 6136 hintBoring, mIncludePad, mEllipsize, 6137 ellipsisWidth); 6138 } 6139 } else if (shouldEllipsize) { 6140 mHintLayout = new StaticLayout(mHint, 6141 0, mHint.length(), 6142 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6143 mSpacingAdd, mIncludePad, mEllipsize, 6144 ellipsisWidth); 6145 } else { 6146 mHintLayout = new StaticLayout(mHint, mTextPaint, 6147 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6148 mIncludePad); 6149 } 6150 } else if (shouldEllipsize) { 6151 mHintLayout = new StaticLayout(mHint, 6152 0, mHint.length(), 6153 mTextPaint, hintWidth, alignment, mTextDir, mSpacingMult, 6154 mSpacingAdd, mIncludePad, mEllipsize, 6155 ellipsisWidth); 6156 } else { 6157 mHintLayout = new StaticLayout(mHint, mTextPaint, 6158 hintWidth, alignment, mTextDir, mSpacingMult, mSpacingAdd, 6159 mIncludePad); 6160 } 6161 } 6162 6163 if (bringIntoView) { 6164 registerForPreDraw(); 6165 } 6166 6167 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 6168 if (!compressText(ellipsisWidth)) { 6169 final int height = mLayoutParams.height; 6170 // If the size of the view does not depend on the size of the text, try to 6171 // start the marquee immediately 6172 if (height != LayoutParams.WRAP_CONTENT && height != LayoutParams.MATCH_PARENT) { 6173 startMarquee(); 6174 } else { 6175 // Defer the start of the marquee until we know our width (see setFrame()) 6176 mRestartMarquee = true; 6177 } 6178 } 6179 } 6180 6181 // CursorControllers need a non-null mLayout 6182 prepareCursorControllers(); 6183 } 6184 6185 private boolean compressText(float width) { 6186 if (isHardwareAccelerated()) return false; 6187 6188 // Only compress the text if it hasn't been compressed by the previous pass 6189 if (width > 0.0f && mLayout != null && getLineCount() == 1 && !mUserSetTextScaleX && 6190 mTextPaint.getTextScaleX() == 1.0f) { 6191 final float textWidth = mLayout.getLineWidth(0); 6192 final float overflow = (textWidth + 1.0f - width) / width; 6193 if (overflow > 0.0f && overflow <= Marquee.MARQUEE_DELTA_MAX) { 6194 mTextPaint.setTextScaleX(1.0f - overflow - 0.005f); 6195 post(new Runnable() { 6196 public void run() { 6197 requestLayout(); 6198 } 6199 }); 6200 return true; 6201 } 6202 } 6203 6204 return false; 6205 } 6206 6207 private static int desired(Layout layout) { 6208 int n = layout.getLineCount(); 6209 CharSequence text = layout.getText(); 6210 float max = 0; 6211 6212 // if any line was wrapped, we can't use it. 6213 // but it's ok for the last line not to have a newline 6214 6215 for (int i = 0; i < n - 1; i++) { 6216 if (text.charAt(layout.getLineEnd(i) - 1) != '\n') 6217 return -1; 6218 } 6219 6220 for (int i = 0; i < n; i++) { 6221 max = Math.max(max, layout.getLineWidth(i)); 6222 } 6223 6224 return (int) FloatMath.ceil(max); 6225 } 6226 6227 /** 6228 * Set whether the TextView includes extra top and bottom padding to make 6229 * room for accents that go above the normal ascent and descent. 6230 * The default is true. 6231 * 6232 * @attr ref android.R.styleable#TextView_includeFontPadding 6233 */ 6234 public void setIncludeFontPadding(boolean includepad) { 6235 mIncludePad = includepad; 6236 6237 if (mLayout != null) { 6238 nullLayouts(); 6239 requestLayout(); 6240 invalidate(); 6241 } 6242 } 6243 6244 private static final BoringLayout.Metrics UNKNOWN_BORING = new BoringLayout.Metrics(); 6245 6246 @Override 6247 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6248 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6249 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6250 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6251 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6252 6253 int width; 6254 int height; 6255 6256 BoringLayout.Metrics boring = UNKNOWN_BORING; 6257 BoringLayout.Metrics hintBoring = UNKNOWN_BORING; 6258 6259 if (mTextDir == null) { 6260 resolveTextDirection(); 6261 } 6262 6263 int des = -1; 6264 boolean fromexisting = false; 6265 6266 if (widthMode == MeasureSpec.EXACTLY) { 6267 // Parent has told us how big to be. So be it. 6268 width = widthSize; 6269 } else { 6270 if (mLayout != null && mEllipsize == null) { 6271 des = desired(mLayout); 6272 } 6273 6274 if (des < 0) { 6275 boring = BoringLayout.isBoring(mTransformed, mTextPaint, mTextDir, mBoring); 6276 if (boring != null) { 6277 mBoring = boring; 6278 } 6279 } else { 6280 fromexisting = true; 6281 } 6282 6283 if (boring == null || boring == UNKNOWN_BORING) { 6284 if (des < 0) { 6285 des = (int) FloatMath.ceil(Layout.getDesiredWidth(mTransformed, mTextPaint)); 6286 } 6287 6288 width = des; 6289 } else { 6290 width = boring.width; 6291 } 6292 6293 final Drawables dr = mDrawables; 6294 if (dr != null) { 6295 width = Math.max(width, dr.mDrawableWidthTop); 6296 width = Math.max(width, dr.mDrawableWidthBottom); 6297 } 6298 6299 if (mHint != null) { 6300 int hintDes = -1; 6301 int hintWidth; 6302 6303 if (mHintLayout != null && mEllipsize == null) { 6304 hintDes = desired(mHintLayout); 6305 } 6306 6307 if (hintDes < 0) { 6308 hintBoring = BoringLayout.isBoring(mHint, mTextPaint, mHintBoring); 6309 if (hintBoring != null) { 6310 mHintBoring = hintBoring; 6311 } 6312 } 6313 6314 if (hintBoring == null || hintBoring == UNKNOWN_BORING) { 6315 if (hintDes < 0) { 6316 hintDes = (int) FloatMath.ceil( 6317 Layout.getDesiredWidth(mHint, mTextPaint)); 6318 } 6319 6320 hintWidth = hintDes; 6321 } else { 6322 hintWidth = hintBoring.width; 6323 } 6324 6325 if (hintWidth > width) { 6326 width = hintWidth; 6327 } 6328 } 6329 6330 width += getCompoundPaddingLeft() + getCompoundPaddingRight(); 6331 6332 if (mMaxWidthMode == EMS) { 6333 width = Math.min(width, mMaxWidth * getLineHeight()); 6334 } else { 6335 width = Math.min(width, mMaxWidth); 6336 } 6337 6338 if (mMinWidthMode == EMS) { 6339 width = Math.max(width, mMinWidth * getLineHeight()); 6340 } else { 6341 width = Math.max(width, mMinWidth); 6342 } 6343 6344 // Check against our minimum width 6345 width = Math.max(width, getSuggestedMinimumWidth()); 6346 6347 if (widthMode == MeasureSpec.AT_MOST) { 6348 width = Math.min(widthSize, width); 6349 } 6350 } 6351 6352 int want = width - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6353 int unpaddedWidth = want; 6354 6355 if (mHorizontallyScrolling) want = VERY_WIDE; 6356 6357 int hintWant = want; 6358 int hintWidth = mHintLayout == null ? hintWant : mHintLayout.getWidth(); 6359 6360 if (mLayout == null) { 6361 makeNewLayout(want, hintWant, boring, hintBoring, 6362 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6363 } else if ((mLayout.getWidth() != want) || (hintWidth != hintWant) || 6364 (mLayout.getEllipsizedWidth() != 6365 width - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 6366 if (mHint == null && mEllipsize == null && 6367 want > mLayout.getWidth() && 6368 (mLayout instanceof BoringLayout || 6369 (fromexisting && des >= 0 && des <= want))) { 6370 mLayout.increaseWidthTo(want); 6371 } else { 6372 makeNewLayout(want, hintWant, boring, hintBoring, 6373 width - getCompoundPaddingLeft() - getCompoundPaddingRight(), false); 6374 } 6375 } else { 6376 // Width has not changed. 6377 } 6378 6379 if (heightMode == MeasureSpec.EXACTLY) { 6380 // Parent has told us how big to be. So be it. 6381 height = heightSize; 6382 mDesiredHeightAtMeasure = -1; 6383 } else { 6384 int desired = getDesiredHeight(); 6385 6386 height = desired; 6387 mDesiredHeightAtMeasure = desired; 6388 6389 if (heightMode == MeasureSpec.AT_MOST) { 6390 height = Math.min(desired, heightSize); 6391 } 6392 } 6393 6394 int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); 6395 if (mMaxMode == LINES && mLayout.getLineCount() > mMaximum) { 6396 unpaddedHeight = Math.min(unpaddedHeight, mLayout.getLineTop(mMaximum)); 6397 } 6398 6399 /* 6400 * We didn't let makeNewLayout() register to bring the cursor into view, 6401 * so do it here if there is any possibility that it is needed. 6402 */ 6403 if (mMovement != null || 6404 mLayout.getWidth() > unpaddedWidth || 6405 mLayout.getHeight() > unpaddedHeight) { 6406 registerForPreDraw(); 6407 } else { 6408 scrollTo(0, 0); 6409 } 6410 6411 setMeasuredDimension(width, height); 6412 } 6413 6414 private int getDesiredHeight() { 6415 return Math.max( 6416 getDesiredHeight(mLayout, true), 6417 getDesiredHeight(mHintLayout, mEllipsize != null)); 6418 } 6419 6420 private int getDesiredHeight(Layout layout, boolean cap) { 6421 if (layout == null) { 6422 return 0; 6423 } 6424 6425 int linecount = layout.getLineCount(); 6426 int pad = getCompoundPaddingTop() + getCompoundPaddingBottom(); 6427 int desired = layout.getLineTop(linecount); 6428 6429 final Drawables dr = mDrawables; 6430 if (dr != null) { 6431 desired = Math.max(desired, dr.mDrawableHeightLeft); 6432 desired = Math.max(desired, dr.mDrawableHeightRight); 6433 } 6434 6435 desired += pad; 6436 layout.setMaximumVisibleLineCount(0); 6437 6438 if (mMaxMode == LINES) { 6439 /* 6440 * Don't cap the hint to a certain number of lines. 6441 * (Do cap it, though, if we have a maximum pixel height.) 6442 */ 6443 if (cap) { 6444 if (linecount > mMaximum) { 6445 layout.setMaximumVisibleLineCount(mMaximum); 6446 desired = layout.getLineTop(mMaximum); 6447 6448 if (dr != null) { 6449 desired = Math.max(desired, dr.mDrawableHeightLeft); 6450 desired = Math.max(desired, dr.mDrawableHeightRight); 6451 } 6452 6453 desired += pad; 6454 linecount = mMaximum; 6455 } 6456 } 6457 } else { 6458 desired = Math.min(desired, mMaximum); 6459 } 6460 6461 if (mMinMode == LINES) { 6462 if (linecount < mMinimum) { 6463 desired += getLineHeight() * (mMinimum - linecount); 6464 } 6465 } else { 6466 desired = Math.max(desired, mMinimum); 6467 } 6468 6469 // Check against our minimum height 6470 desired = Math.max(desired, getSuggestedMinimumHeight()); 6471 6472 return desired; 6473 } 6474 6475 /** 6476 * Check whether a change to the existing text layout requires a 6477 * new view layout. 6478 */ 6479 private void checkForResize() { 6480 boolean sizeChanged = false; 6481 6482 if (mLayout != null) { 6483 // Check if our width changed 6484 if (mLayoutParams.width == LayoutParams.WRAP_CONTENT) { 6485 sizeChanged = true; 6486 invalidate(); 6487 } 6488 6489 // Check if our height changed 6490 if (mLayoutParams.height == LayoutParams.WRAP_CONTENT) { 6491 int desiredHeight = getDesiredHeight(); 6492 6493 if (desiredHeight != this.getHeight()) { 6494 sizeChanged = true; 6495 } 6496 } else if (mLayoutParams.height == LayoutParams.MATCH_PARENT) { 6497 if (mDesiredHeightAtMeasure >= 0) { 6498 int desiredHeight = getDesiredHeight(); 6499 6500 if (desiredHeight != mDesiredHeightAtMeasure) { 6501 sizeChanged = true; 6502 } 6503 } 6504 } 6505 } 6506 6507 if (sizeChanged) { 6508 requestLayout(); 6509 // caller will have already invalidated 6510 } 6511 } 6512 6513 /** 6514 * Check whether entirely new text requires a new view layout 6515 * or merely a new text layout. 6516 */ 6517 private void checkForRelayout() { 6518 // If we have a fixed width, we can just swap in a new text layout 6519 // if the text height stays the same or if the view height is fixed. 6520 6521 if ((mLayoutParams.width != LayoutParams.WRAP_CONTENT || 6522 (mMaxWidthMode == mMinWidthMode && mMaxWidth == mMinWidth)) && 6523 (mHint == null || mHintLayout != null) && 6524 (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight() > 0)) { 6525 // Static width, so try making a new text layout. 6526 6527 int oldht = mLayout.getHeight(); 6528 int want = mLayout.getWidth(); 6529 int hintWant = mHintLayout == null ? 0 : mHintLayout.getWidth(); 6530 6531 /* 6532 * No need to bring the text into view, since the size is not 6533 * changing (unless we do the requestLayout(), in which case it 6534 * will happen at measure). 6535 */ 6536 makeNewLayout(want, hintWant, UNKNOWN_BORING, UNKNOWN_BORING, 6537 mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(), 6538 false); 6539 6540 if (mEllipsize != TextUtils.TruncateAt.MARQUEE) { 6541 // In a fixed-height view, so use our new text layout. 6542 if (mLayoutParams.height != LayoutParams.WRAP_CONTENT && 6543 mLayoutParams.height != LayoutParams.MATCH_PARENT) { 6544 invalidate(); 6545 return; 6546 } 6547 6548 // Dynamic height, but height has stayed the same, 6549 // so use our new text layout. 6550 if (mLayout.getHeight() == oldht && 6551 (mHintLayout == null || mHintLayout.getHeight() == oldht)) { 6552 invalidate(); 6553 return; 6554 } 6555 } 6556 6557 // We lose: the height has changed and we have a dynamic height. 6558 // Request a new view layout using our new text layout. 6559 requestLayout(); 6560 invalidate(); 6561 } else { 6562 // Dynamic width, so we have no choice but to request a new 6563 // view layout with a new text layout. 6564 6565 nullLayouts(); 6566 requestLayout(); 6567 invalidate(); 6568 } 6569 } 6570 6571 /** 6572 * Returns true if anything changed. 6573 */ 6574 private boolean bringTextIntoView() { 6575 int line = 0; 6576 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6577 line = mLayout.getLineCount() - 1; 6578 } 6579 6580 Layout.Alignment a = mLayout.getParagraphAlignment(line); 6581 int dir = mLayout.getParagraphDirection(line); 6582 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6583 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6584 int ht = mLayout.getHeight(); 6585 6586 int scrollx, scrolly; 6587 6588 // Convert to left, center, or right alignment. 6589 if (a == Layout.Alignment.ALIGN_NORMAL) { 6590 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_LEFT : 6591 Layout.Alignment.ALIGN_RIGHT; 6592 } else if (a == Layout.Alignment.ALIGN_OPPOSITE){ 6593 a = dir == Layout.DIR_LEFT_TO_RIGHT ? Layout.Alignment.ALIGN_RIGHT : 6594 Layout.Alignment.ALIGN_LEFT; 6595 } 6596 6597 if (a == Layout.Alignment.ALIGN_CENTER) { 6598 /* 6599 * Keep centered if possible, or, if it is too wide to fit, 6600 * keep leading edge in view. 6601 */ 6602 6603 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6604 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6605 6606 if (right - left < hspace) { 6607 scrollx = (right + left) / 2 - hspace / 2; 6608 } else { 6609 if (dir < 0) { 6610 scrollx = right - hspace; 6611 } else { 6612 scrollx = left; 6613 } 6614 } 6615 } else if (a == Layout.Alignment.ALIGN_RIGHT) { 6616 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6617 scrollx = right - hspace; 6618 } else { // a == Layout.Alignment.ALIGN_LEFT (will also be the default) 6619 scrollx = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6620 } 6621 6622 if (ht < vspace) { 6623 scrolly = 0; 6624 } else { 6625 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) { 6626 scrolly = ht - vspace; 6627 } else { 6628 scrolly = 0; 6629 } 6630 } 6631 6632 if (scrollx != mScrollX || scrolly != mScrollY) { 6633 scrollTo(scrollx, scrolly); 6634 return true; 6635 } else { 6636 return false; 6637 } 6638 } 6639 6640 /** 6641 * Move the point, specified by the offset, into the view if it is needed. 6642 * This has to be called after layout. Returns true if anything changed. 6643 */ 6644 public boolean bringPointIntoView(int offset) { 6645 boolean changed = false; 6646 6647 if (mLayout == null) return changed; 6648 6649 int line = mLayout.getLineForOffset(offset); 6650 6651 // FIXME: Is it okay to truncate this, or should we round? 6652 final int x = (int)mLayout.getPrimaryHorizontal(offset); 6653 final int top = mLayout.getLineTop(line); 6654 final int bottom = mLayout.getLineTop(line + 1); 6655 6656 int left = (int) FloatMath.floor(mLayout.getLineLeft(line)); 6657 int right = (int) FloatMath.ceil(mLayout.getLineRight(line)); 6658 int ht = mLayout.getHeight(); 6659 6660 int grav; 6661 6662 switch (mLayout.getParagraphAlignment(line)) { 6663 case ALIGN_LEFT: 6664 grav = 1; 6665 break; 6666 case ALIGN_RIGHT: 6667 grav = -1; 6668 break; 6669 case ALIGN_NORMAL: 6670 grav = mLayout.getParagraphDirection(line); 6671 break; 6672 case ALIGN_OPPOSITE: 6673 grav = -mLayout.getParagraphDirection(line); 6674 break; 6675 case ALIGN_CENTER: 6676 default: 6677 grav = 0; 6678 break; 6679 } 6680 6681 int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6682 int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6683 6684 int hslack = (bottom - top) / 2; 6685 int vslack = hslack; 6686 6687 if (vslack > vspace / 4) 6688 vslack = vspace / 4; 6689 if (hslack > hspace / 4) 6690 hslack = hspace / 4; 6691 6692 int hs = mScrollX; 6693 int vs = mScrollY; 6694 6695 if (top - vs < vslack) 6696 vs = top - vslack; 6697 if (bottom - vs > vspace - vslack) 6698 vs = bottom - (vspace - vslack); 6699 if (ht - vs < vspace) 6700 vs = ht - vspace; 6701 if (0 - vs > 0) 6702 vs = 0; 6703 6704 if (grav != 0) { 6705 if (x - hs < hslack) { 6706 hs = x - hslack; 6707 } 6708 if (x - hs > hspace - hslack) { 6709 hs = x - (hspace - hslack); 6710 } 6711 } 6712 6713 if (grav < 0) { 6714 if (left - hs > 0) 6715 hs = left; 6716 if (right - hs < hspace) 6717 hs = right - hspace; 6718 } else if (grav > 0) { 6719 if (right - hs < hspace) 6720 hs = right - hspace; 6721 if (left - hs > 0) 6722 hs = left; 6723 } else /* grav == 0 */ { 6724 if (right - left <= hspace) { 6725 /* 6726 * If the entire text fits, center it exactly. 6727 */ 6728 hs = left - (hspace - (right - left)) / 2; 6729 } else if (x > right - hslack) { 6730 /* 6731 * If we are near the right edge, keep the right edge 6732 * at the edge of the view. 6733 */ 6734 hs = right - hspace; 6735 } else if (x < left + hslack) { 6736 /* 6737 * If we are near the left edge, keep the left edge 6738 * at the edge of the view. 6739 */ 6740 hs = left; 6741 } else if (left > hs) { 6742 /* 6743 * Is there whitespace visible at the left? Fix it if so. 6744 */ 6745 hs = left; 6746 } else if (right < hs + hspace) { 6747 /* 6748 * Is there whitespace visible at the right? Fix it if so. 6749 */ 6750 hs = right - hspace; 6751 } else { 6752 /* 6753 * Otherwise, float as needed. 6754 */ 6755 if (x - hs < hslack) { 6756 hs = x - hslack; 6757 } 6758 if (x - hs > hspace - hslack) { 6759 hs = x - (hspace - hslack); 6760 } 6761 } 6762 } 6763 6764 if (hs != mScrollX || vs != mScrollY) { 6765 if (mScroller == null) { 6766 scrollTo(hs, vs); 6767 } else { 6768 long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; 6769 int dx = hs - mScrollX; 6770 int dy = vs - mScrollY; 6771 6772 if (duration > ANIMATED_SCROLL_GAP) { 6773 mScroller.startScroll(mScrollX, mScrollY, dx, dy); 6774 awakenScrollBars(mScroller.getDuration()); 6775 invalidate(); 6776 } else { 6777 if (!mScroller.isFinished()) { 6778 mScroller.abortAnimation(); 6779 } 6780 6781 scrollBy(dx, dy); 6782 } 6783 6784 mLastScroll = AnimationUtils.currentAnimationTimeMillis(); 6785 } 6786 6787 changed = true; 6788 } 6789 6790 if (isFocused()) { 6791 // This offsets because getInterestingRect() is in terms of viewport coordinates, but 6792 // requestRectangleOnScreen() is in terms of content coordinates. 6793 6794 if (mTempRect == null) mTempRect = new Rect(); 6795 mTempRect.set(x, top, x + 1, bottom); 6796 getInterestingRect(mTempRect, line); 6797 mTempRect.offset(mScrollX, mScrollY); 6798 6799 if (requestRectangleOnScreen(mTempRect)) { 6800 changed = true; 6801 } 6802 } 6803 6804 return changed; 6805 } 6806 6807 /** 6808 * Move the cursor, if needed, so that it is at an offset that is visible 6809 * to the user. This will not move the cursor if it represents more than 6810 * one character (a selection range). This will only work if the 6811 * TextView contains spannable text; otherwise it will do nothing. 6812 * 6813 * @return True if the cursor was actually moved, false otherwise. 6814 */ 6815 public boolean moveCursorToVisibleOffset() { 6816 if (!(mText instanceof Spannable)) { 6817 return false; 6818 } 6819 int start = getSelectionStart(); 6820 int end = getSelectionEnd(); 6821 if (start != end) { 6822 return false; 6823 } 6824 6825 // First: make sure the line is visible on screen: 6826 6827 int line = mLayout.getLineForOffset(start); 6828 6829 final int top = mLayout.getLineTop(line); 6830 final int bottom = mLayout.getLineTop(line + 1); 6831 final int vspace = mBottom - mTop - getExtendedPaddingTop() - getExtendedPaddingBottom(); 6832 int vslack = (bottom - top) / 2; 6833 if (vslack > vspace / 4) 6834 vslack = vspace / 4; 6835 final int vs = mScrollY; 6836 6837 if (top < (vs+vslack)) { 6838 line = mLayout.getLineForVertical(vs+vslack+(bottom-top)); 6839 } else if (bottom > (vspace+vs-vslack)) { 6840 line = mLayout.getLineForVertical(vspace+vs-vslack-(bottom-top)); 6841 } 6842 6843 // Next: make sure the character is visible on screen: 6844 6845 final int hspace = mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight(); 6846 final int hs = mScrollX; 6847 final int leftChar = mLayout.getOffsetForHorizontal(line, hs); 6848 final int rightChar = mLayout.getOffsetForHorizontal(line, hspace+hs); 6849 6850 // line might contain bidirectional text 6851 final int lowChar = leftChar < rightChar ? leftChar : rightChar; 6852 final int highChar = leftChar > rightChar ? leftChar : rightChar; 6853 6854 int newStart = start; 6855 if (newStart < lowChar) { 6856 newStart = lowChar; 6857 } else if (newStart > highChar) { 6858 newStart = highChar; 6859 } 6860 6861 if (newStart != start) { 6862 Selection.setSelection((Spannable)mText, newStart); 6863 return true; 6864 } 6865 6866 return false; 6867 } 6868 6869 @Override 6870 public void computeScroll() { 6871 if (mScroller != null) { 6872 if (mScroller.computeScrollOffset()) { 6873 mScrollX = mScroller.getCurrX(); 6874 mScrollY = mScroller.getCurrY(); 6875 invalidateParentCaches(); 6876 postInvalidate(); // So we draw again 6877 } 6878 } 6879 } 6880 6881 private void getInterestingRect(Rect r, int line) { 6882 convertFromViewportToContentCoordinates(r); 6883 6884 // Rectangle can can be expanded on first and last line to take 6885 // padding into account. 6886 // TODO Take left/right padding into account too? 6887 if (line == 0) r.top -= getExtendedPaddingTop(); 6888 if (line == mLayout.getLineCount() - 1) r.bottom += getExtendedPaddingBottom(); 6889 } 6890 6891 private void convertFromViewportToContentCoordinates(Rect r) { 6892 final int horizontalOffset = viewportToContentHorizontalOffset(); 6893 r.left += horizontalOffset; 6894 r.right += horizontalOffset; 6895 6896 final int verticalOffset = viewportToContentVerticalOffset(); 6897 r.top += verticalOffset; 6898 r.bottom += verticalOffset; 6899 } 6900 6901 private int viewportToContentHorizontalOffset() { 6902 return getCompoundPaddingLeft() - mScrollX; 6903 } 6904 6905 private int viewportToContentVerticalOffset() { 6906 int offset = getExtendedPaddingTop() - mScrollY; 6907 if ((mGravity & Gravity.VERTICAL_GRAVITY_MASK) != Gravity.TOP) { 6908 offset += getVerticalOffset(false); 6909 } 6910 return offset; 6911 } 6912 6913 @Override 6914 public void debug(int depth) { 6915 super.debug(depth); 6916 6917 String output = debugIndent(depth); 6918 output += "frame={" + mLeft + ", " + mTop + ", " + mRight 6919 + ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY 6920 + "} "; 6921 6922 if (mText != null) { 6923 6924 output += "mText=\"" + mText + "\" "; 6925 if (mLayout != null) { 6926 output += "mLayout width=" + mLayout.getWidth() 6927 + " height=" + mLayout.getHeight(); 6928 } 6929 } else { 6930 output += "mText=NULL"; 6931 } 6932 Log.d(VIEW_LOG_TAG, output); 6933 } 6934 6935 /** 6936 * Convenience for {@link Selection#getSelectionStart}. 6937 */ 6938 @ViewDebug.ExportedProperty(category = "text") 6939 public int getSelectionStart() { 6940 return Selection.getSelectionStart(getText()); 6941 } 6942 6943 /** 6944 * Convenience for {@link Selection#getSelectionEnd}. 6945 */ 6946 @ViewDebug.ExportedProperty(category = "text") 6947 public int getSelectionEnd() { 6948 return Selection.getSelectionEnd(getText()); 6949 } 6950 6951 /** 6952 * Return true iff there is a selection inside this text view. 6953 */ 6954 public boolean hasSelection() { 6955 final int selectionStart = getSelectionStart(); 6956 final int selectionEnd = getSelectionEnd(); 6957 6958 return selectionStart >= 0 && selectionStart != selectionEnd; 6959 } 6960 6961 /** 6962 * Sets the properties of this field (lines, horizontally scrolling, 6963 * transformation method) to be for a single-line input. 6964 * 6965 * @attr ref android.R.styleable#TextView_singleLine 6966 */ 6967 public void setSingleLine() { 6968 setSingleLine(true); 6969 } 6970 6971 /** 6972 * Sets the properties of this field to transform input to ALL CAPS 6973 * display. This may use a "small caps" formatting if available. 6974 * This setting will be ignored if this field is editable or selectable. 6975 * 6976 * This call replaces the current transformation method. Disabling this 6977 * will not necessarily restore the previous behavior from before this 6978 * was enabled. 6979 * 6980 * @see #setTransformationMethod(TransformationMethod) 6981 * @attr ref android.R.styleable#TextView_textAllCaps 6982 */ 6983 public void setAllCaps(boolean allCaps) { 6984 if (allCaps) { 6985 setTransformationMethod(new AllCapsTransformationMethod(getContext())); 6986 } else { 6987 setTransformationMethod(null); 6988 } 6989 } 6990 6991 /** 6992 * If true, sets the properties of this field (number of lines, horizontally scrolling, 6993 * transformation method) to be for a single-line input; if false, restores these to the default 6994 * conditions. 6995 * 6996 * Note that the default conditions are not necessarily those that were in effect prior this 6997 * method, and you may want to reset these properties to your custom values. 6998 * 6999 * @attr ref android.R.styleable#TextView_singleLine 7000 */ 7001 @android.view.RemotableViewMethod 7002 public void setSingleLine(boolean singleLine) { 7003 // Could be used, but may break backward compatibility. 7004 // if (mSingleLine == singleLine) return; 7005 setInputTypeSingleLine(singleLine); 7006 applySingleLine(singleLine, true, true); 7007 } 7008 7009 /** 7010 * Adds or remove the EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE on the mInputType. 7011 * @param singleLine 7012 */ 7013 private void setInputTypeSingleLine(boolean singleLine) { 7014 if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { 7015 if (singleLine) { 7016 mInputType &= ~EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7017 } else { 7018 mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; 7019 } 7020 } 7021 } 7022 7023 private void applySingleLine(boolean singleLine, boolean applyTransformation, 7024 boolean changeMaxLines) { 7025 mSingleLine = singleLine; 7026 if (singleLine) { 7027 setLines(1); 7028 setHorizontallyScrolling(true); 7029 if (applyTransformation) { 7030 setTransformationMethod(SingleLineTransformationMethod.getInstance()); 7031 } 7032 } else { 7033 if (changeMaxLines) { 7034 setMaxLines(Integer.MAX_VALUE); 7035 } 7036 setHorizontallyScrolling(false); 7037 if (applyTransformation) { 7038 setTransformationMethod(null); 7039 } 7040 } 7041 } 7042 7043 /** 7044 * Causes words in the text that are longer than the view is wide 7045 * to be ellipsized instead of broken in the middle. You may also 7046 * want to {@link #setSingleLine} or {@link #setHorizontallyScrolling} 7047 * to constrain the text to a single line. Use <code>null</code> 7048 * to turn off ellipsizing. 7049 * 7050 * @attr ref android.R.styleable#TextView_ellipsize 7051 */ 7052 public void setEllipsize(TextUtils.TruncateAt where) { 7053 mEllipsize = where; 7054 7055 if (mLayout != null) { 7056 nullLayouts(); 7057 requestLayout(); 7058 invalidate(); 7059 } 7060 } 7061 7062 /** 7063 * Sets how many times to repeat the marquee animation. Only applied if the 7064 * TextView has marquee enabled. Set to -1 to repeat indefinitely. 7065 * 7066 * @attr ref android.R.styleable#TextView_marqueeRepeatLimit 7067 */ 7068 public void setMarqueeRepeatLimit(int marqueeLimit) { 7069 mMarqueeRepeatLimit = marqueeLimit; 7070 } 7071 7072 /** 7073 * Returns where, if anywhere, words that are longer than the view 7074 * is wide should be ellipsized. 7075 */ 7076 @ViewDebug.ExportedProperty 7077 public TextUtils.TruncateAt getEllipsize() { 7078 return mEllipsize; 7079 } 7080 7081 /** 7082 * Set the TextView so that when it takes focus, all the text is 7083 * selected. 7084 * 7085 * @attr ref android.R.styleable#TextView_selectAllOnFocus 7086 */ 7087 @android.view.RemotableViewMethod 7088 public void setSelectAllOnFocus(boolean selectAllOnFocus) { 7089 mSelectAllOnFocus = selectAllOnFocus; 7090 7091 if (selectAllOnFocus && !(mText instanceof Spannable)) { 7092 setText(mText, BufferType.SPANNABLE); 7093 } 7094 } 7095 7096 /** 7097 * Set whether the cursor is visible. The default is true. 7098 * 7099 * @attr ref android.R.styleable#TextView_cursorVisible 7100 */ 7101 @android.view.RemotableViewMethod 7102 public void setCursorVisible(boolean visible) { 7103 if (mCursorVisible != visible) { 7104 mCursorVisible = visible; 7105 invalidate(); 7106 7107 makeBlink(); 7108 7109 // InsertionPointCursorController depends on mCursorVisible 7110 prepareCursorControllers(); 7111 } 7112 } 7113 7114 private boolean isCursorVisible() { 7115 return mCursorVisible && isTextEditable(); 7116 } 7117 7118 private boolean canMarquee() { 7119 int width = (mRight - mLeft - getCompoundPaddingLeft() - getCompoundPaddingRight()); 7120 return width > 0 && mLayout.getLineWidth(0) > width; 7121 } 7122 7123 private void startMarquee() { 7124 // Do not ellipsize EditText 7125 if (mInput != null) return; 7126 7127 if (compressText(getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight())) { 7128 return; 7129 } 7130 7131 if ((mMarquee == null || mMarquee.isStopped()) && (isFocused() || isSelected()) && 7132 getLineCount() == 1 && canMarquee()) { 7133 7134 if (mMarquee == null) mMarquee = new Marquee(this); 7135 mMarquee.start(mMarqueeRepeatLimit); 7136 } 7137 } 7138 7139 private void stopMarquee() { 7140 if (mMarquee != null && !mMarquee.isStopped()) { 7141 mMarquee.stop(); 7142 } 7143 } 7144 7145 private void startStopMarquee(boolean start) { 7146 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7147 if (start) { 7148 startMarquee(); 7149 } else { 7150 stopMarquee(); 7151 } 7152 } 7153 } 7154 7155 private static final class Marquee extends Handler { 7156 // TODO: Add an option to configure this 7157 private static final float MARQUEE_DELTA_MAX = 0.07f; 7158 private static final int MARQUEE_DELAY = 1200; 7159 private static final int MARQUEE_RESTART_DELAY = 1200; 7160 private static final int MARQUEE_RESOLUTION = 1000 / 30; 7161 private static final int MARQUEE_PIXELS_PER_SECOND = 30; 7162 7163 private static final byte MARQUEE_STOPPED = 0x0; 7164 private static final byte MARQUEE_STARTING = 0x1; 7165 private static final byte MARQUEE_RUNNING = 0x2; 7166 7167 private static final int MESSAGE_START = 0x1; 7168 private static final int MESSAGE_TICK = 0x2; 7169 private static final int MESSAGE_RESTART = 0x3; 7170 7171 private final WeakReference<TextView> mView; 7172 7173 private byte mStatus = MARQUEE_STOPPED; 7174 private final float mScrollUnit; 7175 private float mMaxScroll; 7176 float mMaxFadeScroll; 7177 private float mGhostStart; 7178 private float mGhostOffset; 7179 private float mFadeStop; 7180 private int mRepeatLimit; 7181 7182 float mScroll; 7183 7184 Marquee(TextView v) { 7185 final float density = v.getContext().getResources().getDisplayMetrics().density; 7186 mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / MARQUEE_RESOLUTION; 7187 mView = new WeakReference<TextView>(v); 7188 } 7189 7190 @Override 7191 public void handleMessage(Message msg) { 7192 switch (msg.what) { 7193 case MESSAGE_START: 7194 mStatus = MARQUEE_RUNNING; 7195 tick(); 7196 break; 7197 case MESSAGE_TICK: 7198 tick(); 7199 break; 7200 case MESSAGE_RESTART: 7201 if (mStatus == MARQUEE_RUNNING) { 7202 if (mRepeatLimit >= 0) { 7203 mRepeatLimit--; 7204 } 7205 start(mRepeatLimit); 7206 } 7207 break; 7208 } 7209 } 7210 7211 void tick() { 7212 if (mStatus != MARQUEE_RUNNING) { 7213 return; 7214 } 7215 7216 removeMessages(MESSAGE_TICK); 7217 7218 final TextView textView = mView.get(); 7219 if (textView != null && (textView.isFocused() || textView.isSelected())) { 7220 mScroll += mScrollUnit; 7221 if (mScroll > mMaxScroll) { 7222 mScroll = mMaxScroll; 7223 sendEmptyMessageDelayed(MESSAGE_RESTART, MARQUEE_RESTART_DELAY); 7224 } else { 7225 sendEmptyMessageDelayed(MESSAGE_TICK, MARQUEE_RESOLUTION); 7226 } 7227 textView.invalidate(); 7228 } 7229 } 7230 7231 void stop() { 7232 mStatus = MARQUEE_STOPPED; 7233 removeMessages(MESSAGE_START); 7234 removeMessages(MESSAGE_RESTART); 7235 removeMessages(MESSAGE_TICK); 7236 resetScroll(); 7237 } 7238 7239 private void resetScroll() { 7240 mScroll = 0.0f; 7241 final TextView textView = mView.get(); 7242 if (textView != null) textView.invalidate(); 7243 } 7244 7245 void start(int repeatLimit) { 7246 if (repeatLimit == 0) { 7247 stop(); 7248 return; 7249 } 7250 mRepeatLimit = repeatLimit; 7251 final TextView textView = mView.get(); 7252 if (textView != null && textView.mLayout != null) { 7253 mStatus = MARQUEE_STARTING; 7254 mScroll = 0.0f; 7255 final int textWidth = textView.getWidth() - textView.getCompoundPaddingLeft() - 7256 textView.getCompoundPaddingRight(); 7257 final float lineWidth = textView.mLayout.getLineWidth(0); 7258 final float gap = textWidth / 3.0f; 7259 mGhostStart = lineWidth - textWidth + gap; 7260 mMaxScroll = mGhostStart + textWidth; 7261 mGhostOffset = lineWidth + gap; 7262 mFadeStop = lineWidth + textWidth / 6.0f; 7263 mMaxFadeScroll = mGhostStart + lineWidth + lineWidth; 7264 7265 textView.invalidate(); 7266 sendEmptyMessageDelayed(MESSAGE_START, MARQUEE_DELAY); 7267 } 7268 } 7269 7270 float getGhostOffset() { 7271 return mGhostOffset; 7272 } 7273 7274 boolean shouldDrawLeftFade() { 7275 return mScroll <= mFadeStop; 7276 } 7277 7278 boolean shouldDrawGhost() { 7279 return mStatus == MARQUEE_RUNNING && mScroll > mGhostStart; 7280 } 7281 7282 boolean isRunning() { 7283 return mStatus == MARQUEE_RUNNING; 7284 } 7285 7286 boolean isStopped() { 7287 return mStatus == MARQUEE_STOPPED; 7288 } 7289 } 7290 7291 /** 7292 * This method is called when the text is changed, in case any subclasses 7293 * would like to know. 7294 * 7295 * Within <code>text</code>, the <code>lengthAfter</code> characters 7296 * beginning at <code>start</code> have just replaced old text that had 7297 * length <code>lengthBefore</code>. It is an error to attempt to make 7298 * changes to <code>text</code> from this callback. 7299 * 7300 * @param text The text the TextView is displaying 7301 * @param start The offset of the start of the range of the text that was 7302 * modified 7303 * @param lengthBefore The length of the former text that has been replaced 7304 * @param lengthAfter The length of the replacement modified text 7305 */ 7306 protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { 7307 // intentionally empty 7308 } 7309 7310 /** 7311 * This method is called when the selection has changed, in case any 7312 * subclasses would like to know. 7313 * 7314 * @param selStart The new selection start location. 7315 * @param selEnd The new selection end location. 7316 */ 7317 protected void onSelectionChanged(int selStart, int selEnd) { 7318 sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED); 7319 } 7320 7321 /** 7322 * Adds a TextWatcher to the list of those whose methods are called 7323 * whenever this TextView's text changes. 7324 * <p> 7325 * In 1.0, the {@link TextWatcher#afterTextChanged} method was erroneously 7326 * not called after {@link #setText} calls. Now, doing {@link #setText} 7327 * if there are any text changed listeners forces the buffer type to 7328 * Editable if it would not otherwise be and does call this method. 7329 */ 7330 public void addTextChangedListener(TextWatcher watcher) { 7331 if (mListeners == null) { 7332 mListeners = new ArrayList<TextWatcher>(); 7333 } 7334 7335 mListeners.add(watcher); 7336 } 7337 7338 /** 7339 * Removes the specified TextWatcher from the list of those whose 7340 * methods are called 7341 * whenever this TextView's text changes. 7342 */ 7343 public void removeTextChangedListener(TextWatcher watcher) { 7344 if (mListeners != null) { 7345 int i = mListeners.indexOf(watcher); 7346 7347 if (i >= 0) { 7348 mListeners.remove(i); 7349 } 7350 } 7351 } 7352 7353 private void sendBeforeTextChanged(CharSequence text, int start, int before, 7354 int after) { 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).beforeTextChanged(text, start, before, after); 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 sendOnTextChanged(CharSequence text, int start, int before, 7369 int after) { 7370 if (mListeners != null) { 7371 final ArrayList<TextWatcher> list = mListeners; 7372 final int count = list.size(); 7373 for (int i = 0; i < count; i++) { 7374 list.get(i).onTextChanged(text, start, before, after); 7375 } 7376 } 7377 } 7378 7379 /** 7380 * Not private so it can be called from an inner class without going 7381 * through a thunk. 7382 */ 7383 void sendAfterTextChanged(Editable text) { 7384 if (mListeners != null) { 7385 final ArrayList<TextWatcher> list = mListeners; 7386 final int count = list.size(); 7387 for (int i = 0; i < count; i++) { 7388 list.get(i).afterTextChanged(text); 7389 } 7390 } 7391 } 7392 7393 /** 7394 * Not private so it can be called from an inner class without going 7395 * through a thunk. 7396 */ 7397 void handleTextChanged(CharSequence buffer, int start, int before, int after) { 7398 final InputMethodState ims = mInputMethodState; 7399 if (ims == null || ims.mBatchEditNesting == 0) { 7400 updateAfterEdit(); 7401 } 7402 if (ims != null) { 7403 ims.mContentChanged = true; 7404 if (ims.mChangedStart < 0) { 7405 ims.mChangedStart = start; 7406 ims.mChangedEnd = start+before; 7407 } else { 7408 ims.mChangedStart = Math.min(ims.mChangedStart, start); 7409 ims.mChangedEnd = Math.max(ims.mChangedEnd, start + before - ims.mChangedDelta); 7410 } 7411 ims.mChangedDelta += after-before; 7412 } 7413 7414 sendOnTextChanged(buffer, start, before, after); 7415 onTextChanged(buffer, start, before, after); 7416 7417 // Hide the controllers if the amount of content changed 7418 if (before != after) { 7419 hideControllers(); 7420 } 7421 } 7422 7423 /** 7424 * Not private so it can be called from an inner class without going 7425 * through a thunk. 7426 */ 7427 void spanChange(Spanned buf, Object what, int oldStart, int newStart, int oldEnd, int newEnd) { 7428 // XXX Make the start and end move together if this ends up 7429 // spending too much time invalidating. 7430 7431 boolean selChanged = false; 7432 int newSelStart=-1, newSelEnd=-1; 7433 7434 final InputMethodState ims = mInputMethodState; 7435 7436 if (what == Selection.SELECTION_END) { 7437 mHighlightPathBogus = true; 7438 selChanged = true; 7439 newSelEnd = newStart; 7440 7441 if (!isFocused()) { 7442 mSelectionMoved = true; 7443 } 7444 7445 if (oldStart >= 0 || newStart >= 0) { 7446 invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); 7447 registerForPreDraw(); 7448 makeBlink(); 7449 } 7450 } 7451 7452 if (what == Selection.SELECTION_START) { 7453 mHighlightPathBogus = true; 7454 selChanged = true; 7455 newSelStart = newStart; 7456 7457 if (!isFocused()) { 7458 mSelectionMoved = true; 7459 } 7460 7461 if (oldStart >= 0 || newStart >= 0) { 7462 int end = Selection.getSelectionEnd(buf); 7463 invalidateCursor(end, oldStart, newStart); 7464 } 7465 } 7466 7467 if (selChanged) { 7468 if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { 7469 if (newSelStart < 0) { 7470 newSelStart = Selection.getSelectionStart(buf); 7471 } 7472 if (newSelEnd < 0) { 7473 newSelEnd = Selection.getSelectionEnd(buf); 7474 } 7475 onSelectionChanged(newSelStart, newSelEnd); 7476 } 7477 } 7478 7479 if (what instanceof UpdateAppearance || 7480 what instanceof ParagraphStyle) { 7481 if (ims == null || ims.mBatchEditNesting == 0) { 7482 invalidate(); 7483 mHighlightPathBogus = true; 7484 checkForResize(); 7485 } else { 7486 ims.mContentChanged = true; 7487 } 7488 } 7489 7490 if (MetaKeyKeyListener.isMetaTracker(buf, what)) { 7491 mHighlightPathBogus = true; 7492 if (ims != null && MetaKeyKeyListener.isSelectingMetaTracker(buf, what)) { 7493 ims.mSelectionModeChanged = true; 7494 } 7495 7496 if (Selection.getSelectionStart(buf) >= 0) { 7497 if (ims == null || ims.mBatchEditNesting == 0) { 7498 invalidateCursor(); 7499 } else { 7500 ims.mCursorChanged = true; 7501 } 7502 } 7503 } 7504 7505 if (what instanceof ParcelableSpan) { 7506 // If this is a span that can be sent to a remote process, 7507 // the current extract editor would be interested in it. 7508 if (ims != null && ims.mExtracting != null) { 7509 if (ims.mBatchEditNesting != 0) { 7510 if (oldStart >= 0) { 7511 if (ims.mChangedStart > oldStart) { 7512 ims.mChangedStart = oldStart; 7513 } 7514 if (ims.mChangedStart > oldEnd) { 7515 ims.mChangedStart = oldEnd; 7516 } 7517 } 7518 if (newStart >= 0) { 7519 if (ims.mChangedStart > newStart) { 7520 ims.mChangedStart = newStart; 7521 } 7522 if (ims.mChangedStart > newEnd) { 7523 ims.mChangedStart = newEnd; 7524 } 7525 } 7526 } else { 7527 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "Span change outside of batch: " 7528 + oldStart + "-" + oldEnd + "," 7529 + newStart + "-" + newEnd + what); 7530 ims.mContentChanged = true; 7531 } 7532 } 7533 } 7534 } 7535 7536 private class ChangeWatcher 7537 implements TextWatcher, SpanWatcher { 7538 7539 private CharSequence mBeforeText; 7540 7541 public void beforeTextChanged(CharSequence buffer, int start, 7542 int before, int after) { 7543 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "beforeTextChanged start=" + start 7544 + " before=" + before + " after=" + after + ": " + buffer); 7545 7546 if (AccessibilityManager.getInstance(mContext).isEnabled() 7547 && !isPasswordInputType(mInputType) 7548 && !hasPasswordTransformationMethod()) { 7549 mBeforeText = buffer.toString(); 7550 } 7551 7552 TextView.this.sendBeforeTextChanged(buffer, start, before, after); 7553 } 7554 7555 public void onTextChanged(CharSequence buffer, int start, 7556 int before, int after) { 7557 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onTextChanged start=" + start 7558 + " before=" + before + " after=" + after + ": " + buffer); 7559 TextView.this.handleTextChanged(buffer, start, before, after); 7560 7561 if (AccessibilityManager.getInstance(mContext).isEnabled() && 7562 (isFocused() || isSelected() && 7563 isShown())) { 7564 sendAccessibilityEventTypeViewTextChanged(mBeforeText, start, before, after); 7565 mBeforeText = null; 7566 } 7567 } 7568 7569 public void afterTextChanged(Editable buffer) { 7570 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "afterTextChanged: " + buffer); 7571 TextView.this.sendAfterTextChanged(buffer); 7572 7573 if (MetaKeyKeyListener.getMetaState(buffer, 7574 MetaKeyKeyListener.META_SELECTING) != 0) { 7575 MetaKeyKeyListener.stopSelecting(TextView.this, buffer); 7576 } 7577 } 7578 7579 public void onSpanChanged(Spannable buf, 7580 Object what, int s, int e, int st, int en) { 7581 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanChanged s=" + s + " e=" + e 7582 + " st=" + st + " en=" + en + " what=" + what + ": " + buf); 7583 TextView.this.spanChange(buf, what, s, st, e, en); 7584 } 7585 7586 public void onSpanAdded(Spannable buf, Object what, int s, int e) { 7587 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanAdded s=" + s + " e=" + e 7588 + " what=" + what + ": " + buf); 7589 TextView.this.spanChange(buf, what, -1, s, -1, e); 7590 } 7591 7592 public void onSpanRemoved(Spannable buf, Object what, int s, int e) { 7593 if (DEBUG_EXTRACT) Log.v(LOG_TAG, "onSpanRemoved s=" + s + " e=" + e 7594 + " what=" + what + ": " + buf); 7595 TextView.this.spanChange(buf, what, s, -1, e, -1); 7596 } 7597 } 7598 7599 /** 7600 * @hide 7601 */ 7602 @Override 7603 public void dispatchFinishTemporaryDetach() { 7604 mDispatchTemporaryDetach = true; 7605 super.dispatchFinishTemporaryDetach(); 7606 mDispatchTemporaryDetach = false; 7607 } 7608 7609 @Override 7610 public void onStartTemporaryDetach() { 7611 super.onStartTemporaryDetach(); 7612 // Only track when onStartTemporaryDetach() is called directly, 7613 // usually because this instance is an editable field in a list 7614 if (!mDispatchTemporaryDetach) mTemporaryDetach = true; 7615 7616 // Because of View recycling in ListView, there is no easy way to know when a TextView with 7617 // selection becomes visible again. Until a better solution is found, stop text selection 7618 // mode (if any) as soon as this TextView is recycled. 7619 stopSelectionActionMode(); 7620 } 7621 7622 @Override 7623 public void onFinishTemporaryDetach() { 7624 super.onFinishTemporaryDetach(); 7625 // Only track when onStartTemporaryDetach() is called directly, 7626 // usually because this instance is an editable field in a list 7627 if (!mDispatchTemporaryDetach) mTemporaryDetach = false; 7628 } 7629 7630 @Override 7631 protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { 7632 if (mTemporaryDetach) { 7633 // If we are temporarily in the detach state, then do nothing. 7634 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7635 return; 7636 } 7637 7638 mShowCursor = SystemClock.uptimeMillis(); 7639 7640 ensureEndedBatchEdit(); 7641 7642 if (focused) { 7643 int selStart = getSelectionStart(); 7644 int selEnd = getSelectionEnd(); 7645 7646 // SelectAllOnFocus fields are highlighted and not selected. Do not start text selection 7647 // mode for these, unless there was a specific selection already started. 7648 final boolean isFocusHighlighted = mSelectAllOnFocus && selStart == 0 && 7649 selEnd == mText.length(); 7650 mCreatedWithASelection = mFrozenWithFocus && hasSelection() && !isFocusHighlighted; 7651 7652 if (!mFrozenWithFocus || (selStart < 0 || selEnd < 0)) { 7653 // If a tap was used to give focus to that view, move cursor at tap position. 7654 // Has to be done before onTakeFocus, which can be overloaded. 7655 final int lastTapPosition = getLastTapPosition(); 7656 if (lastTapPosition >= 0) { 7657 Selection.setSelection((Spannable) mText, lastTapPosition); 7658 } 7659 7660 if (mMovement != null) { 7661 mMovement.onTakeFocus(this, (Spannable) mText, direction); 7662 } 7663 7664 // The DecorView does not have focus when the 'Done' ExtractEditText button is 7665 // pressed. Since it is the ViewAncestor's mView, it requests focus before 7666 // ExtractEditText clears focus, which gives focus to the ExtractEditText. 7667 // This special case ensure that we keep current selection in that case. 7668 // It would be better to know why the DecorView does not have focus at that time. 7669 if (((this instanceof ExtractEditText) || mSelectionMoved) && 7670 selStart >= 0 && selEnd >= 0) { 7671 /* 7672 * Someone intentionally set the selection, so let them 7673 * do whatever it is that they wanted to do instead of 7674 * the default on-focus behavior. We reset the selection 7675 * here instead of just skipping the onTakeFocus() call 7676 * because some movement methods do something other than 7677 * just setting the selection in theirs and we still 7678 * need to go through that path. 7679 */ 7680 Selection.setSelection((Spannable) mText, selStart, selEnd); 7681 } 7682 7683 if (mSelectAllOnFocus) { 7684 selectAll(); 7685 } 7686 7687 mTouchFocusSelected = true; 7688 } 7689 7690 mFrozenWithFocus = false; 7691 mSelectionMoved = false; 7692 7693 if (mText instanceof Spannable) { 7694 Spannable sp = (Spannable) mText; 7695 MetaKeyKeyListener.resetMetaState(sp); 7696 } 7697 7698 makeBlink(); 7699 7700 if (mError != null) { 7701 showError(); 7702 } 7703 } else { 7704 if (mError != null) { 7705 hideError(); 7706 } 7707 // Don't leave us in the middle of a batch edit. 7708 onEndBatchEdit(); 7709 7710 if (this instanceof ExtractEditText) { 7711 // terminateTextSelectionMode removes selection, which we want to keep when 7712 // ExtractEditText goes out of focus. 7713 final int selStart = getSelectionStart(); 7714 final int selEnd = getSelectionEnd(); 7715 hideControllers(); 7716 Selection.setSelection((Spannable) mText, selStart, selEnd); 7717 } else { 7718 hideControllers(); 7719 } 7720 7721 // No need to create the controller 7722 if (mSelectionModifierCursorController != null) { 7723 mSelectionModifierCursorController.resetTouchOffsets(); 7724 } 7725 } 7726 7727 startStopMarquee(focused); 7728 7729 if (mTransformation != null) { 7730 mTransformation.onFocusChanged(this, mText, focused, direction, previouslyFocusedRect); 7731 } 7732 7733 super.onFocusChanged(focused, direction, previouslyFocusedRect); 7734 } 7735 7736 private int getLastTapPosition() { 7737 // No need to create the controller at that point, no last tap position saved 7738 if (mSelectionModifierCursorController != null) { 7739 int lastTapPosition = mSelectionModifierCursorController.getMinTouchOffset(); 7740 if (lastTapPosition >= 0) { 7741 // Safety check, should not be possible. 7742 if (lastTapPosition > mText.length()) { 7743 Log.e(LOG_TAG, "Invalid tap focus position (" + lastTapPosition + " vs " 7744 + mText.length() + ")"); 7745 lastTapPosition = mText.length(); 7746 } 7747 return lastTapPosition; 7748 } 7749 } 7750 7751 return -1; 7752 } 7753 7754 @Override 7755 public void onWindowFocusChanged(boolean hasWindowFocus) { 7756 super.onWindowFocusChanged(hasWindowFocus); 7757 7758 if (hasWindowFocus) { 7759 if (mBlink != null) { 7760 mBlink.uncancel(); 7761 makeBlink(); 7762 } 7763 } else { 7764 if (mBlink != null) { 7765 mBlink.cancel(); 7766 } 7767 // Don't leave us in the middle of a batch edit. 7768 onEndBatchEdit(); 7769 if (mInputContentType != null) { 7770 mInputContentType.enterDown = false; 7771 } 7772 hideControllers(); 7773 removeAllSuggestionSpans(); 7774 } 7775 7776 startStopMarquee(hasWindowFocus); 7777 } 7778 7779 private void removeAllSuggestionSpans() { 7780 if (mText instanceof Editable) { 7781 Editable editable = ((Editable) mText); 7782 SuggestionSpan[] spans = editable.getSpans(0, mText.length(), SuggestionSpan.class); 7783 final int length = spans.length; 7784 for (int i = 0; i < length; i++) { 7785 editable.removeSpan(spans[i]); 7786 } 7787 } 7788 } 7789 7790 @Override 7791 protected void onVisibilityChanged(View changedView, int visibility) { 7792 super.onVisibilityChanged(changedView, visibility); 7793 if (visibility != VISIBLE) { 7794 hideControllers(); 7795 } 7796 } 7797 7798 /** 7799 * Use {@link BaseInputConnection#removeComposingSpans 7800 * BaseInputConnection.removeComposingSpans()} to remove any IME composing 7801 * state from this text view. 7802 */ 7803 public void clearComposingText() { 7804 if (mText instanceof Spannable) { 7805 BaseInputConnection.removeComposingSpans((Spannable)mText); 7806 } 7807 } 7808 7809 @Override 7810 public void setSelected(boolean selected) { 7811 boolean wasSelected = isSelected(); 7812 7813 super.setSelected(selected); 7814 7815 if (selected != wasSelected && mEllipsize == TextUtils.TruncateAt.MARQUEE) { 7816 if (selected) { 7817 startMarquee(); 7818 } else { 7819 stopMarquee(); 7820 } 7821 } 7822 } 7823 7824 @Override 7825 public boolean onTouchEvent(MotionEvent event) { 7826 final int action = event.getActionMasked(); 7827 7828 if (hasSelectionController()) { 7829 getSelectionController().onTouchEvent(event); 7830 } 7831 7832 if (action == MotionEvent.ACTION_DOWN) { 7833 mLastDownPositionX = event.getX(); 7834 mLastDownPositionY = event.getY(); 7835 7836 // Reset this state; it will be re-set if super.onTouchEvent 7837 // causes focus to move to the view. 7838 mTouchFocusSelected = false; 7839 mIgnoreActionUpEvent = false; 7840 } 7841 7842 final boolean superResult = super.onTouchEvent(event); 7843 7844 /* 7845 * Don't handle the release after a long press, because it will 7846 * move the selection away from whatever the menu action was 7847 * trying to affect. 7848 */ 7849 if (mDiscardNextActionUp && action == MotionEvent.ACTION_UP) { 7850 mDiscardNextActionUp = false; 7851 return superResult; 7852 } 7853 7854 final boolean touchIsFinished = action == MotionEvent.ACTION_UP && !mIgnoreActionUpEvent && 7855 isFocused(); 7856 7857 if ((mMovement != null || onCheckIsTextEditor()) && isEnabled() 7858 && mText instanceof Spannable && mLayout != null) { 7859 boolean handled = false; 7860 7861 if (mMovement != null) { 7862 handled |= mMovement.onTouchEvent(this, (Spannable) mText, event); 7863 } 7864 7865 if (mLinksClickable && mAutoLinkMask != 0 && mTextIsSelectable && touchIsFinished) { 7866 // The LinkMovementMethod which should handle taps on links has not been installed 7867 // to support text selection. We reproduce its behavior here to open links. 7868 ClickableSpan[] links = ((Spannable) mText).getSpans(getSelectionStart(), 7869 getSelectionEnd(), ClickableSpan.class); 7870 7871 if (links.length != 0) { 7872 links[0].onClick(this); 7873 handled = true; 7874 } 7875 } 7876 7877 if ((isTextEditable() || mTextIsSelectable) && touchIsFinished) { 7878 // Show the IME, except when selecting in read-only text. 7879 final InputMethodManager imm = InputMethodManager.peekInstance(); 7880 if (imm != null) { 7881 imm.viewClicked(this); 7882 } 7883 if (!mTextIsSelectable) { 7884 handled |= imm != null && imm.showSoftInput(this, 0); 7885 } 7886 7887 boolean selectAllGotFocus = mSelectAllOnFocus && didTouchFocusSelect(); 7888 if (!selectAllGotFocus && hasSelection()) { 7889 startSelectionActionMode(); 7890 } else { 7891 stopSelectionActionMode(); 7892 hideSuggestions(); 7893 if (hasInsertionController() && !selectAllGotFocus && mText.length() > 0) { 7894 getInsertionController().show(); 7895 } 7896 } 7897 } 7898 7899 if (handled) { 7900 return true; 7901 } 7902 } 7903 7904 return superResult; 7905 } 7906 7907 @Override 7908 public boolean onGenericMotionEvent(MotionEvent event) { 7909 if (mMovement != null && mText instanceof Spannable && mLayout != null) { 7910 try { 7911 if (mMovement.onGenericMotionEvent(this, (Spannable) mText, event)) { 7912 return true; 7913 } 7914 } catch (AbstractMethodError ex) { 7915 // onGenericMotionEvent was added to the MovementMethod interface in API 12. 7916 // Ignore its absence in case third party applications implemented the 7917 // interface directly. 7918 } 7919 } 7920 return super.onGenericMotionEvent(event); 7921 } 7922 7923 private void prepareCursorControllers() { 7924 boolean windowSupportsHandles = false; 7925 7926 ViewGroup.LayoutParams params = getRootView().getLayoutParams(); 7927 if (params instanceof WindowManager.LayoutParams) { 7928 WindowManager.LayoutParams windowParams = (WindowManager.LayoutParams) params; 7929 windowSupportsHandles = windowParams.type < WindowManager.LayoutParams.FIRST_SUB_WINDOW 7930 || windowParams.type > WindowManager.LayoutParams.LAST_SUB_WINDOW; 7931 } 7932 7933 mInsertionControllerEnabled = windowSupportsHandles && isCursorVisible() && mLayout != null; 7934 mSelectionControllerEnabled = windowSupportsHandles && textCanBeSelected() && 7935 mLayout != null; 7936 7937 if (!mInsertionControllerEnabled) { 7938 hideInsertionPointCursorController(); 7939 if (mInsertionPointCursorController != null) { 7940 mInsertionPointCursorController.onDetached(); 7941 mInsertionPointCursorController = null; 7942 } 7943 } 7944 7945 if (!mSelectionControllerEnabled) { 7946 stopSelectionActionMode(); 7947 if (mSelectionModifierCursorController != null) { 7948 mSelectionModifierCursorController.onDetached(); 7949 mSelectionModifierCursorController = null; 7950 } 7951 } 7952 } 7953 7954 /** 7955 * @return True iff this TextView contains a text that can be edited, or if this is 7956 * a selectable TextView. 7957 */ 7958 private boolean isTextEditable() { 7959 return mText instanceof Editable && onCheckIsTextEditor() && isEnabled(); 7960 } 7961 7962 /** 7963 * Returns true, only while processing a touch gesture, if the initial 7964 * touch down event caused focus to move to the text view and as a result 7965 * its selection changed. Only valid while processing the touch gesture 7966 * of interest. 7967 */ 7968 public boolean didTouchFocusSelect() { 7969 return mTouchFocusSelected; 7970 } 7971 7972 @Override 7973 public void cancelLongPress() { 7974 super.cancelLongPress(); 7975 mIgnoreActionUpEvent = true; 7976 } 7977 7978 @Override 7979 public boolean onTrackballEvent(MotionEvent event) { 7980 if (mMovement != null && mText instanceof Spannable && 7981 mLayout != null) { 7982 if (mMovement.onTrackballEvent(this, (Spannable) mText, event)) { 7983 return true; 7984 } 7985 } 7986 7987 return super.onTrackballEvent(event); 7988 } 7989 7990 public void setScroller(Scroller s) { 7991 mScroller = s; 7992 } 7993 7994 private static class Blink extends Handler implements Runnable { 7995 private final WeakReference<TextView> mView; 7996 private boolean mCancelled; 7997 7998 public Blink(TextView v) { 7999 mView = new WeakReference<TextView>(v); 8000 } 8001 8002 public void run() { 8003 if (mCancelled) { 8004 return; 8005 } 8006 8007 removeCallbacks(Blink.this); 8008 8009 TextView tv = mView.get(); 8010 8011 if (tv != null && tv.shouldBlink()) { 8012 if (tv.mLayout != null) { 8013 tv.invalidateCursorPath(); 8014 } 8015 8016 postAtTime(this, SystemClock.uptimeMillis() + BLINK); 8017 } 8018 } 8019 8020 void cancel() { 8021 if (!mCancelled) { 8022 removeCallbacks(Blink.this); 8023 mCancelled = true; 8024 } 8025 } 8026 8027 void uncancel() { 8028 mCancelled = false; 8029 } 8030 } 8031 8032 /** 8033 * @return True when the TextView isFocused and has a valid zero-length selection (cursor). 8034 */ 8035 private boolean shouldBlink() { 8036 if (!isFocused()) return false; 8037 8038 final int start = getSelectionStart(); 8039 if (start < 0) return false; 8040 8041 final int end = getSelectionEnd(); 8042 if (end < 0) return false; 8043 8044 return start == end; 8045 } 8046 8047 private void makeBlink() { 8048 if (isCursorVisible()) { 8049 if (shouldBlink()) { 8050 mShowCursor = SystemClock.uptimeMillis(); 8051 if (mBlink == null) mBlink = new Blink(this); 8052 mBlink.removeCallbacks(mBlink); 8053 mBlink.postAtTime(mBlink, mShowCursor + BLINK); 8054 } 8055 } else { 8056 if (mBlink != null) mBlink.removeCallbacks(mBlink); 8057 } 8058 } 8059 8060 @Override 8061 protected float getLeftFadingEdgeStrength() { 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 if (marquee.shouldDrawLeftFade()) { 8067 return marquee.mScroll / getHorizontalFadingEdgeLength(); 8068 } else { 8069 return 0.0f; 8070 } 8071 } else if (getLineCount() == 1) { 8072 final int layoutDirection = getResolvedLayoutDirection(); 8073 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8074 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8075 case Gravity.LEFT: 8076 return 0.0f; 8077 case Gravity.RIGHT: 8078 return (mLayout.getLineRight(0) - (mRight - mLeft) - 8079 getCompoundPaddingLeft() - getCompoundPaddingRight() - 8080 mLayout.getLineLeft(0)) / getHorizontalFadingEdgeLength(); 8081 case Gravity.CENTER_HORIZONTAL: 8082 return 0.0f; 8083 } 8084 } 8085 } 8086 return super.getLeftFadingEdgeStrength(); 8087 } 8088 8089 @Override 8090 protected float getRightFadingEdgeStrength() { 8091 if (mCurrentAlpha <= ViewConfiguration.ALPHA_THRESHOLD_INT) return 0.0f; 8092 if (mEllipsize == TextUtils.TruncateAt.MARQUEE) { 8093 if (mMarquee != null && !mMarquee.isStopped()) { 8094 final Marquee marquee = mMarquee; 8095 return (marquee.mMaxFadeScroll - marquee.mScroll) / getHorizontalFadingEdgeLength(); 8096 } else if (getLineCount() == 1) { 8097 final int layoutDirection = getResolvedLayoutDirection(); 8098 final int absoluteGravity = Gravity.getAbsoluteGravity(mGravity, layoutDirection); 8099 switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { 8100 case Gravity.LEFT: 8101 final int textWidth = (mRight - mLeft) - getCompoundPaddingLeft() - 8102 getCompoundPaddingRight(); 8103 final float lineWidth = mLayout.getLineWidth(0); 8104 return (lineWidth - textWidth) / getHorizontalFadingEdgeLength(); 8105 case Gravity.RIGHT: 8106 return 0.0f; 8107 case Gravity.CENTER_HORIZONTAL: 8108 case Gravity.FILL_HORIZONTAL: 8109 return (mLayout.getLineWidth(0) - ((mRight - mLeft) - 8110 getCompoundPaddingLeft() - getCompoundPaddingRight())) / 8111 getHorizontalFadingEdgeLength(); 8112 } 8113 } 8114 } 8115 return super.getRightFadingEdgeStrength(); 8116 } 8117 8118 @Override 8119 protected int computeHorizontalScrollRange() { 8120 if (mLayout != null) { 8121 return mSingleLine && (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT ? 8122 (int) mLayout.getLineWidth(0) : mLayout.getWidth(); 8123 } 8124 8125 return super.computeHorizontalScrollRange(); 8126 } 8127 8128 @Override 8129 protected int computeVerticalScrollRange() { 8130 if (mLayout != null) 8131 return mLayout.getHeight(); 8132 8133 return super.computeVerticalScrollRange(); 8134 } 8135 8136 @Override 8137 protected int computeVerticalScrollExtent() { 8138 return getHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); 8139 } 8140 8141 @Override 8142 public void findViewsWithText(ArrayList<View> outViews, CharSequence searched) { 8143 if (TextUtils.isEmpty(searched)) { 8144 return; 8145 } 8146 CharSequence thisText = getText(); 8147 if (TextUtils.isEmpty(thisText)) { 8148 return; 8149 } 8150 String searchedLowerCase = searched.toString().toLowerCase(); 8151 String thisTextLowerCase = thisText.toString().toLowerCase(); 8152 if (thisTextLowerCase.contains(searchedLowerCase)) { 8153 outViews.add(this); 8154 } 8155 } 8156 8157 public enum BufferType { 8158 NORMAL, SPANNABLE, EDITABLE, 8159 } 8160 8161 /** 8162 * Returns the TextView_textColor attribute from the 8163 * Resources.StyledAttributes, if set, or the TextAppearance_textColor 8164 * from the TextView_textAppearance attribute, if TextView_textColor 8165 * was not set directly. 8166 */ 8167 public static ColorStateList getTextColors(Context context, TypedArray attrs) { 8168 ColorStateList colors; 8169 colors = attrs.getColorStateList(com.android.internal.R.styleable. 8170 TextView_textColor); 8171 8172 if (colors == null) { 8173 int ap = attrs.getResourceId(com.android.internal.R.styleable. 8174 TextView_textAppearance, -1); 8175 if (ap != -1) { 8176 TypedArray appearance; 8177 appearance = context.obtainStyledAttributes(ap, 8178 com.android.internal.R.styleable.TextAppearance); 8179 colors = appearance.getColorStateList(com.android.internal.R.styleable. 8180 TextAppearance_textColor); 8181 appearance.recycle(); 8182 } 8183 } 8184 8185 return colors; 8186 } 8187 8188 /** 8189 * Returns the default color from the TextView_textColor attribute 8190 * from the AttributeSet, if set, or the default color from the 8191 * TextAppearance_textColor from the TextView_textAppearance attribute, 8192 * if TextView_textColor was not set directly. 8193 */ 8194 public static int getTextColor(Context context, 8195 TypedArray attrs, 8196 int def) { 8197 ColorStateList colors = getTextColors(context, attrs); 8198 8199 if (colors == null) { 8200 return def; 8201 } else { 8202 return colors.getDefaultColor(); 8203 } 8204 } 8205 8206 @Override 8207 public boolean onKeyShortcut(int keyCode, KeyEvent event) { 8208 final int filteredMetaState = event.getMetaState() & ~KeyEvent.META_CTRL_MASK; 8209 if (KeyEvent.metaStateHasNoModifiers(filteredMetaState)) { 8210 switch (keyCode) { 8211 case KeyEvent.KEYCODE_A: 8212 if (canSelectText()) { 8213 return onTextContextMenuItem(ID_SELECT_ALL); 8214 } 8215 break; 8216 case KeyEvent.KEYCODE_X: 8217 if (canCut()) { 8218 return onTextContextMenuItem(ID_CUT); 8219 } 8220 break; 8221 case KeyEvent.KEYCODE_C: 8222 if (canCopy()) { 8223 return onTextContextMenuItem(ID_COPY); 8224 } 8225 break; 8226 case KeyEvent.KEYCODE_V: 8227 if (canPaste()) { 8228 return onTextContextMenuItem(ID_PASTE); 8229 } 8230 break; 8231 } 8232 } 8233 return super.onKeyShortcut(keyCode, event); 8234 } 8235 8236 /** 8237 * Unlike {@link #textCanBeSelected()}, this method is based on the <i>current</i> state of the 8238 * TextView. {@link #textCanBeSelected()} has to be true (this is one of the conditions to have 8239 * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient. 8240 */ 8241 private boolean canSelectText() { 8242 return hasSelectionController() && mText.length() != 0; 8243 } 8244 8245 /** 8246 * Test based on the <i>intrinsic</i> charateristics of the TextView. 8247 * The text must be spannable and the movement method must allow for arbitary selection. 8248 * 8249 * See also {@link #canSelectText()}. 8250 */ 8251 private boolean textCanBeSelected() { 8252 // prepareCursorController() relies on this method. 8253 // If you change this condition, make sure prepareCursorController is called anywhere 8254 // the value of this condition might be changed. 8255 if (mMovement == null || !mMovement.canSelectArbitrarily()) return false; 8256 return isTextEditable() || (mTextIsSelectable && mText instanceof Spannable && isEnabled()); 8257 } 8258 8259 private boolean canCut() { 8260 if (hasPasswordTransformationMethod()) { 8261 return false; 8262 } 8263 8264 if (mText.length() > 0 && hasSelection() && mText instanceof Editable && mInput != null) { 8265 return true; 8266 } 8267 8268 return false; 8269 } 8270 8271 private boolean canCopy() { 8272 if (hasPasswordTransformationMethod()) { 8273 return false; 8274 } 8275 8276 if (mText.length() > 0 && hasSelection()) { 8277 return true; 8278 } 8279 8280 return false; 8281 } 8282 8283 private boolean canPaste() { 8284 return (mText instanceof Editable && 8285 mInput != null && 8286 getSelectionStart() >= 0 && 8287 getSelectionEnd() >= 0 && 8288 ((ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE)). 8289 hasPrimaryClip()); 8290 } 8291 8292 private static long packRangeInLong(int start, int end) { 8293 return (((long) start) << 32) | end; 8294 } 8295 8296 private static int extractRangeStartFromLong(long range) { 8297 return (int) (range >>> 32); 8298 } 8299 8300 private static int extractRangeEndFromLong(long range) { 8301 return (int) (range & 0x00000000FFFFFFFFL); 8302 } 8303 8304 private boolean selectAll() { 8305 final int length = mText.length(); 8306 Selection.setSelection((Spannable) mText, 0, length); 8307 return length > 0; 8308 } 8309 8310 /** 8311 * Adjusts selection to the word under last touch offset. 8312 * Return true if the operation was successfully performed. 8313 */ 8314 private boolean selectCurrentWord() { 8315 if (!canSelectText()) { 8316 return false; 8317 } 8318 8319 if (hasPasswordTransformationMethod()) { 8320 // Always select all on a password field. 8321 // Cut/copy menu entries are not available for passwords, but being able to select all 8322 // is however useful to delete or paste to replace the entire content. 8323 return selectAll(); 8324 } 8325 8326 int klass = mInputType & InputType.TYPE_MASK_CLASS; 8327 int variation = mInputType & InputType.TYPE_MASK_VARIATION; 8328 8329 // Specific text field types: select the entire text for these 8330 if (klass == InputType.TYPE_CLASS_NUMBER || 8331 klass == InputType.TYPE_CLASS_PHONE || 8332 klass == InputType.TYPE_CLASS_DATETIME || 8333 variation == InputType.TYPE_TEXT_VARIATION_URI || 8334 variation == InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || 8335 variation == InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS || 8336 variation == InputType.TYPE_TEXT_VARIATION_FILTER) { 8337 return selectAll(); 8338 } 8339 8340 long lastTouchOffsets = getLastTouchOffsets(); 8341 final int minOffset = extractRangeStartFromLong(lastTouchOffsets); 8342 final int maxOffset = extractRangeEndFromLong(lastTouchOffsets); 8343 8344 // Safety check in case standard touch event handling has been bypassed 8345 if (minOffset < 0 || minOffset >= mText.length()) return false; 8346 if (maxOffset < 0 || maxOffset >= mText.length()) return false; 8347 8348 int selectionStart, selectionEnd; 8349 8350 // If a URLSpan (web address, email, phone...) is found at that position, select it. 8351 URLSpan[] urlSpans = ((Spanned) mText).getSpans(minOffset, maxOffset, URLSpan.class); 8352 if (urlSpans.length == 1) { 8353 URLSpan url = urlSpans[0]; 8354 selectionStart = ((Spanned) mText).getSpanStart(url); 8355 selectionEnd = ((Spanned) mText).getSpanEnd(url); 8356 } else { 8357 if (mWordIterator == null) { 8358 mWordIterator = new WordIterator(); 8359 } 8360 // WordIerator handles text changes, this is a no-op if text in unchanged. 8361 mWordIterator.setCharSequence(mText); 8362 8363 selectionStart = mWordIterator.getBeginning(minOffset); 8364 if (selectionStart == BreakIterator.DONE) return false; 8365 8366 selectionEnd = mWordIterator.getEnd(maxOffset); 8367 if (selectionEnd == BreakIterator.DONE) return false; 8368 } 8369 8370 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8371 return true; 8372 } 8373 8374 private long getLastTouchOffsets() { 8375 int minOffset, maxOffset; 8376 8377 if (mContextMenuTriggeredByKey) { 8378 minOffset = getSelectionStart(); 8379 maxOffset = getSelectionEnd(); 8380 } else { 8381 SelectionModifierCursorController selectionController = getSelectionController(); 8382 minOffset = selectionController.getMinTouchOffset(); 8383 maxOffset = selectionController.getMaxTouchOffset(); 8384 } 8385 8386 return packRangeInLong(minOffset, maxOffset); 8387 } 8388 8389 @Override 8390 public void onPopulateAccessibilityEvent(AccessibilityEvent event) { 8391 super.onPopulateAccessibilityEvent(event); 8392 8393 final boolean isPassword = hasPasswordTransformationMethod(); 8394 if (!isPassword) { 8395 CharSequence text = getText(); 8396 if (TextUtils.isEmpty(text)) { 8397 text = getHint(); 8398 } 8399 if (!TextUtils.isEmpty(text)) { 8400 event.getText().add(text); 8401 } 8402 } 8403 } 8404 8405 @Override 8406 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 8407 super.onInitializeAccessibilityEvent(event); 8408 8409 final boolean isPassword = hasPasswordTransformationMethod(); 8410 event.setPassword(isPassword); 8411 8412 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) { 8413 event.setFromIndex(Selection.getSelectionStart(mText)); 8414 event.setToIndex(Selection.getSelectionEnd(mText)); 8415 event.setItemCount(mText.length()); 8416 } 8417 } 8418 8419 @Override 8420 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { 8421 super.onInitializeAccessibilityNodeInfo(info); 8422 8423 final boolean isPassword = hasPasswordTransformationMethod(); 8424 if (!isPassword) { 8425 info.setText(getText()); 8426 } 8427 info.setPassword(isPassword); 8428 } 8429 8430 void sendAccessibilityEventTypeViewTextChanged(CharSequence beforeText, 8431 int fromIndex, int removedCount, int addedCount) { 8432 AccessibilityEvent event = 8433 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED); 8434 event.setFromIndex(fromIndex); 8435 event.setRemovedCount(removedCount); 8436 event.setAddedCount(addedCount); 8437 event.setBeforeText(beforeText); 8438 sendAccessibilityEventUnchecked(event); 8439 } 8440 8441 @Override 8442 protected void onCreateContextMenu(ContextMenu menu) { 8443 super.onCreateContextMenu(menu); 8444 boolean added = false; 8445 mContextMenuTriggeredByKey = mDPadCenterIsDown || mEnterKeyIsDown; 8446 // Problem with context menu on long press: the menu appears while the key in down and when 8447 // the key is released, the view does not receive the key_up event. 8448 // We need two layers of flags: mDPadCenterIsDown and mEnterKeyIsDown are set in key down/up 8449 // events. We cannot simply clear these flags in onTextContextMenuItem since 8450 // it may not be called (if the user/ discards the context menu with the back key). 8451 // We clear these flags here and mContextMenuTriggeredByKey saves that state so that it is 8452 // available in onTextContextMenuItem. 8453 mDPadCenterIsDown = mEnterKeyIsDown = false; 8454 8455 MenuHandler handler = new MenuHandler(); 8456 8457 if (mText instanceof Spanned && hasSelectionController()) { 8458 long lastTouchOffset = getLastTouchOffsets(); 8459 final int selStart = extractRangeStartFromLong(lastTouchOffset); 8460 final int selEnd = extractRangeEndFromLong(lastTouchOffset); 8461 8462 URLSpan[] urls = ((Spanned) mText).getSpans(selStart, selEnd, URLSpan.class); 8463 if (urls.length > 0) { 8464 menu.add(0, ID_COPY_URL, 0, com.android.internal.R.string.copyUrl). 8465 setOnMenuItemClickListener(handler); 8466 8467 added = true; 8468 } 8469 } 8470 8471 // The context menu is not empty, which will prevent the selection mode from starting. 8472 // Add a entry to start it in the context menu. 8473 // TODO Does not handle the case where a subclass does not call super.thisMethod or 8474 // populates the menu AFTER this call. 8475 if (menu.size() > 0) { 8476 menu.add(0, ID_SELECTION_MODE, 0, com.android.internal.R.string.selectTextMode). 8477 setOnMenuItemClickListener(handler); 8478 added = true; 8479 } 8480 8481 if (added) { 8482 menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); 8483 } 8484 } 8485 8486 /** 8487 * Returns whether this text view is a current input method target. The 8488 * default implementation just checks with {@link InputMethodManager}. 8489 */ 8490 public boolean isInputMethodTarget() { 8491 InputMethodManager imm = InputMethodManager.peekInstance(); 8492 return imm != null && imm.isActive(this); 8493 } 8494 8495 // Selection context mode 8496 private static final int ID_SELECT_ALL = android.R.id.selectAll; 8497 private static final int ID_CUT = android.R.id.cut; 8498 private static final int ID_COPY = android.R.id.copy; 8499 private static final int ID_PASTE = android.R.id.paste; 8500 // Context menu entries 8501 private static final int ID_COPY_URL = android.R.id.copyUrl; 8502 private static final int ID_SELECTION_MODE = android.R.id.selectTextMode; 8503 8504 private class MenuHandler implements MenuItem.OnMenuItemClickListener { 8505 public boolean onMenuItemClick(MenuItem item) { 8506 return onTextContextMenuItem(item.getItemId()); 8507 } 8508 } 8509 8510 /** 8511 * Called when a context menu option for the text view is selected. Currently 8512 * this will be {@link android.R.id#copyUrl}, {@link android.R.id#selectTextMode}, 8513 * {@link android.R.id#selectAll}, {@link android.R.id#paste}, {@link android.R.id#cut} 8514 * or {@link android.R.id#copy}. 8515 * 8516 * @return true if the context menu item action was performed. 8517 */ 8518 public boolean onTextContextMenuItem(int id) { 8519 int min = 0; 8520 int max = mText.length(); 8521 8522 if (isFocused()) { 8523 final int selStart = getSelectionStart(); 8524 final int selEnd = getSelectionEnd(); 8525 8526 min = Math.max(0, Math.min(selStart, selEnd)); 8527 max = Math.max(0, Math.max(selStart, selEnd)); 8528 } 8529 8530 switch (id) { 8531 case ID_COPY_URL: 8532 URLSpan[] urls = ((Spanned) mText).getSpans(min, max, URLSpan.class); 8533 if (urls.length >= 1) { 8534 ClipData clip = null; 8535 for (int i=0; i<urls.length; i++) { 8536 Uri uri = Uri.parse(urls[0].getURL()); 8537 if (clip == null) { 8538 clip = ClipData.newRawUri(null, uri); 8539 } else { 8540 clip.addItem(new ClipData.Item(uri)); 8541 } 8542 } 8543 if (clip != null) { 8544 setPrimaryClip(clip); 8545 } 8546 } 8547 stopSelectionActionMode(); 8548 return true; 8549 8550 case ID_SELECTION_MODE: 8551 if (mSelectionActionMode != null) { 8552 // Selection mode is already started, simply change selected part. 8553 selectCurrentWord(); 8554 } else { 8555 startSelectionActionMode(); 8556 } 8557 return true; 8558 8559 case ID_SELECT_ALL: 8560 // This does not enter text selection mode. Text is highlighted, so that it can be 8561 // bulk edited, like selectAllOnFocus does. Returns true even if text is empty. 8562 selectAll(); 8563 return true; 8564 8565 case ID_PASTE: 8566 paste(min, max); 8567 return true; 8568 8569 case ID_CUT: 8570 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8571 ((Editable) mText).delete(min, max); 8572 stopSelectionActionMode(); 8573 return true; 8574 8575 case ID_COPY: 8576 setPrimaryClip(ClipData.newPlainText(null, mTransformed.subSequence(min, max))); 8577 stopSelectionActionMode(); 8578 return true; 8579 } 8580 return false; 8581 } 8582 8583 /** 8584 * Prepare text so that there are not zero or two spaces at beginning and end of region defined 8585 * by [min, max] when replacing this region by paste. 8586 * Note that if there were two spaces (or more) at that position before, they are kept. We just 8587 * make sure we do not add an extra one from the paste content. 8588 */ 8589 private long prepareSpacesAroundPaste(int min, int max, CharSequence paste) { 8590 if (paste.length() > 0) { 8591 if (min > 0) { 8592 final char charBefore = mTransformed.charAt(min - 1); 8593 final char charAfter = paste.charAt(0); 8594 8595 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8596 // Two spaces at beginning of paste: remove one 8597 final int originalLength = mText.length(); 8598 ((Editable) mText).delete(min - 1, min); 8599 // Due to filters, there is no guarantee that exactly one character was 8600 // removed: count instead. 8601 final int delta = mText.length() - originalLength; 8602 min += delta; 8603 max += delta; 8604 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8605 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8606 // No space at beginning of paste: add one 8607 final int originalLength = mText.length(); 8608 ((Editable) mText).replace(min, min, " "); 8609 // Taking possible filters into account as above. 8610 final int delta = mText.length() - originalLength; 8611 min += delta; 8612 max += delta; 8613 } 8614 } 8615 8616 if (max < mText.length()) { 8617 final char charBefore = paste.charAt(paste.length() - 1); 8618 final char charAfter = mTransformed.charAt(max); 8619 8620 if (Character.isSpaceChar(charBefore) && Character.isSpaceChar(charAfter)) { 8621 // Two spaces at end of paste: remove one 8622 ((Editable) mText).delete(max, max + 1); 8623 } else if (!Character.isSpaceChar(charBefore) && charBefore != '\n' && 8624 !Character.isSpaceChar(charAfter) && charAfter != '\n') { 8625 // No space at end of paste: add one 8626 ((Editable) mText).replace(max, max, " "); 8627 } 8628 } 8629 } 8630 8631 return packRangeInLong(min, max); 8632 } 8633 8634 private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) { 8635 TextView shadowView = (TextView) inflate(mContext, 8636 com.android.internal.R.layout.text_drag_thumbnail, null); 8637 8638 if (shadowView == null) { 8639 throw new IllegalArgumentException("Unable to inflate text drag thumbnail"); 8640 } 8641 8642 if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) { 8643 text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH); 8644 } 8645 shadowView.setText(text); 8646 shadowView.setTextColor(getTextColors()); 8647 8648 shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge); 8649 shadowView.setGravity(Gravity.CENTER); 8650 8651 shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 8652 ViewGroup.LayoutParams.WRAP_CONTENT)); 8653 8654 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8655 shadowView.measure(size, size); 8656 8657 shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight()); 8658 shadowView.invalidate(); 8659 return new DragShadowBuilder(shadowView); 8660 } 8661 8662 private static class DragLocalState { 8663 public TextView sourceTextView; 8664 public int start, end; 8665 8666 public DragLocalState(TextView sourceTextView, int start, int end) { 8667 this.sourceTextView = sourceTextView; 8668 this.start = start; 8669 this.end = end; 8670 } 8671 } 8672 8673 @Override 8674 public boolean performLongClick() { 8675 if (super.performLongClick()) { 8676 mDiscardNextActionUp = true; 8677 return true; 8678 } 8679 8680 boolean handled = false; 8681 8682 // Long press in empty space moves cursor and shows the Paste affordance if available. 8683 if (!isPositionOnText(mLastDownPositionX, mLastDownPositionY) && 8684 mInsertionControllerEnabled) { 8685 final int offset = getOffsetForPosition(mLastDownPositionX, mLastDownPositionY); 8686 stopSelectionActionMode(); 8687 Selection.setSelection((Spannable) mText, offset); 8688 getInsertionController().showWithPaste(); 8689 handled = true; 8690 } 8691 8692 if (!handled && mSelectionActionMode != null) { 8693 if (touchPositionIsInSelection()) { 8694 // Start a drag 8695 final int start = getSelectionStart(); 8696 final int end = getSelectionEnd(); 8697 CharSequence selectedText = mTransformed.subSequence(start, end); 8698 ClipData data = ClipData.newPlainText(null, selectedText); 8699 DragLocalState localState = new DragLocalState(this, start, end); 8700 startDrag(data, getTextThumbnailBuilder(selectedText), localState, 0); 8701 stopSelectionActionMode(); 8702 } else { 8703 selectCurrentWord(); 8704 } 8705 handled = true; 8706 } 8707 8708 // Start a new selection 8709 handled |= !handled && startSelectionActionMode(); 8710 8711 if (handled) { 8712 performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 8713 mDiscardNextActionUp = true; 8714 } 8715 8716 return handled; 8717 } 8718 8719 private boolean touchPositionIsInSelection() { 8720 int selectionStart = getSelectionStart(); 8721 int selectionEnd = getSelectionEnd(); 8722 8723 if (selectionStart == selectionEnd) { 8724 return false; 8725 } 8726 8727 if (selectionStart > selectionEnd) { 8728 int tmp = selectionStart; 8729 selectionStart = selectionEnd; 8730 selectionEnd = tmp; 8731 Selection.setSelection((Spannable) mText, selectionStart, selectionEnd); 8732 } 8733 8734 SelectionModifierCursorController selectionController = getSelectionController(); 8735 int minOffset = selectionController.getMinTouchOffset(); 8736 int maxOffset = selectionController.getMaxTouchOffset(); 8737 8738 return ((minOffset >= selectionStart) && (maxOffset < selectionEnd)); 8739 } 8740 8741 private static class SuggestionRangeSpan extends UnderlineSpan { 8742 // TODO themable, would be nice to make it a child class of TextAppearanceSpan, but 8743 // there is no way to have underline and TextAppearanceSpan. 8744 } 8745 8746 private class SuggestionsPopupWindow implements OnClickListener { 8747 private static final int MAX_NUMBER_SUGGESTIONS = 5; 8748 private static final int NO_SUGGESTIONS = -1; 8749 private final PopupWindow mContainer; 8750 private final ViewGroup[] mSuggestionViews = new ViewGroup[2]; 8751 private final int[] mSuggestionViewLayouts = new int[] { 8752 mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout}; 8753 private WordIterator mSuggestionWordIterator; 8754 private TextAppearanceSpan[] mHighlightSpans = new TextAppearanceSpan[0]; 8755 8756 public SuggestionsPopupWindow() { 8757 mContainer = new PopupWindow(TextView.this.mContext, null, 8758 com.android.internal.R.attr.textSuggestionsWindowStyle); 8759 mContainer.setSplitTouchEnabled(true); 8760 mContainer.setClippingEnabled(false); 8761 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 8762 8763 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 8764 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 8765 } 8766 8767 private class SuggestionInfo { 8768 int suggestionStart, suggestionEnd; // range of suggestion item with replacement text 8769 int spanStart, spanEnd; // range in TextView where text should be inserted 8770 SuggestionSpan suggestionSpan; // the SuggestionSpan that this TextView represents 8771 int suggestionIndex; // the index of the suggestion inside suggestionSpan 8772 } 8773 8774 private ViewGroup getViewGroup(boolean under) { 8775 final int viewIndex = under ? 0 : 1; 8776 ViewGroup viewGroup = mSuggestionViews[viewIndex]; 8777 8778 if (viewGroup == null) { 8779 final int layout = mSuggestionViewLayouts[viewIndex]; 8780 LayoutInflater inflater = (LayoutInflater) TextView.this.mContext. 8781 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 8782 8783 if (inflater == null) { 8784 throw new IllegalArgumentException( 8785 "Unable to create TextEdit suggestion window inflater"); 8786 } 8787 8788 View view = inflater.inflate(layout, null); 8789 8790 if (! (view instanceof ViewGroup)) { 8791 throw new IllegalArgumentException( 8792 "Inflated TextEdit suggestion window is not a ViewGroup: " + view); 8793 } 8794 8795 viewGroup = (ViewGroup) view; 8796 8797 // Inflate the suggestion items once and for all. 8798 for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { 8799 View childView = inflater.inflate(mTextEditSuggestionItemLayout, viewGroup, 8800 false); 8801 8802 if (! (childView instanceof TextView)) { 8803 throw new IllegalArgumentException( 8804 "Inflated TextEdit suggestion item is not a TextView: " + childView); 8805 } 8806 8807 childView.setTag(new SuggestionInfo()); 8808 viewGroup.addView(childView); 8809 childView.setOnClickListener(this); 8810 } 8811 8812 mSuggestionViews[viewIndex] = viewGroup; 8813 } 8814 8815 return viewGroup; 8816 } 8817 8818 public void show() { 8819 if (!(mText instanceof Editable)) return; 8820 8821 final int pos = TextView.this.getSelectionStart(); 8822 Spannable spannable = (Spannable)TextView.this.mText; 8823 SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); 8824 final int nbSpans = suggestionSpans.length; 8825 8826 ViewGroup viewGroup = getViewGroup(true); 8827 mContainer.setContentView(viewGroup); 8828 8829 int totalNbSuggestions = 0; 8830 int spanUnionStart = mText.length(); 8831 int spanUnionEnd = 0; 8832 8833 for (int spanIndex = 0; spanIndex < nbSpans; spanIndex++) { 8834 SuggestionSpan suggestionSpan = suggestionSpans[spanIndex]; 8835 final int spanStart = spannable.getSpanStart(suggestionSpan); 8836 final int spanEnd = spannable.getSpanEnd(suggestionSpan); 8837 spanUnionStart = Math.min(spanStart, spanUnionStart); 8838 spanUnionEnd = Math.max(spanEnd, spanUnionEnd); 8839 8840 String[] suggestions = suggestionSpan.getSuggestions(); 8841 int nbSuggestions = suggestions.length; 8842 for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { 8843 TextView textView = (TextView) viewGroup.getChildAt(totalNbSuggestions); 8844 textView.setText(suggestions[suggestionIndex]); 8845 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8846 suggestionInfo.spanStart = spanStart; 8847 suggestionInfo.spanEnd = spanEnd; 8848 suggestionInfo.suggestionSpan = suggestionSpan; 8849 suggestionInfo.suggestionIndex = suggestionIndex; 8850 8851 totalNbSuggestions++; 8852 if (totalNbSuggestions == MAX_NUMBER_SUGGESTIONS) { 8853 // Also end outer for loop 8854 spanIndex = nbSpans; 8855 break; 8856 } 8857 } 8858 } 8859 8860 if (totalNbSuggestions == 0) { 8861 // TODO Replace by final text, use a dedicated layout, add a fade out timer... 8862 TextView textView = (TextView) viewGroup.getChildAt(0); 8863 textView.setText("No suggestions available"); 8864 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8865 suggestionInfo.spanStart = NO_SUGGESTIONS; 8866 totalNbSuggestions++; 8867 } else { 8868 if (mSuggestionRangeSpan == null) mSuggestionRangeSpan = new SuggestionRangeSpan(); 8869 ((Editable) mText).setSpan(mSuggestionRangeSpan, spanUnionStart, spanUnionEnd, 8870 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8871 8872 for (int i = 0; i < totalNbSuggestions; i++) { 8873 final TextView textView = (TextView) viewGroup.getChildAt(i); 8874 highlightTextDifferences(textView, spanUnionStart, spanUnionEnd); 8875 } 8876 } 8877 8878 for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { 8879 viewGroup.getChildAt(i).setVisibility(i < totalNbSuggestions ? VISIBLE : GONE); 8880 } 8881 8882 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 8883 viewGroup.measure(size, size); 8884 8885 positionAtCursor(); 8886 } 8887 8888 private long[] getWordLimits(CharSequence text) { 8889 // TODO locale for mSuggestionWordIterator 8890 if (mSuggestionWordIterator == null) mSuggestionWordIterator = new WordIterator(); 8891 mSuggestionWordIterator.setCharSequence(text); 8892 8893 // First pass will simply count the number of words to be able to create an array 8894 // Not too expensive since previous break positions are cached by the BreakIterator 8895 int nbWords = 0; 8896 int position = mSuggestionWordIterator.following(0); 8897 while (position != BreakIterator.DONE) { 8898 nbWords++; 8899 position = mSuggestionWordIterator.following(position); 8900 } 8901 8902 int index = 0; 8903 long[] result = new long[nbWords]; 8904 8905 position = mSuggestionWordIterator.following(0); 8906 while (position != BreakIterator.DONE) { 8907 int wordStart = mSuggestionWordIterator.getBeginning(position); 8908 result[index++] = packRangeInLong(wordStart, position); 8909 position = mSuggestionWordIterator.following(position); 8910 } 8911 8912 return result; 8913 } 8914 8915 private TextAppearanceSpan highlightSpan(int index) { 8916 final int length = mHighlightSpans.length; 8917 if (index < length) { 8918 return mHighlightSpans[index]; 8919 } 8920 8921 // Assumes indexes are requested in sequence: simply append one more item 8922 TextAppearanceSpan[] newArray = new TextAppearanceSpan[length + 1]; 8923 System.arraycopy(mHighlightSpans, 0, newArray, 0, length); 8924 TextAppearanceSpan highlightSpan = new TextAppearanceSpan(mContext, 8925 android.R.style.TextAppearance_SuggestionHighlight); 8926 newArray[length] = highlightSpan; 8927 mHighlightSpans = newArray; 8928 return highlightSpan; 8929 } 8930 8931 private void highlightTextDifferences(TextView textView, int unionStart, int unionEnd) { 8932 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 8933 final int spanStart = suggestionInfo.spanStart; 8934 final int spanEnd = suggestionInfo.spanEnd; 8935 8936 // Remove all text formating by converting to Strings 8937 final String text = textView.getText().toString(); 8938 final String sourceText = mText.subSequence(spanStart, spanEnd).toString(); 8939 8940 long[] sourceWordLimits = getWordLimits(sourceText); 8941 long[] wordLimits = getWordLimits(text); 8942 8943 SpannableStringBuilder ssb = new SpannableStringBuilder(); 8944 // span [spanStart, spanEnd] is included in union [spanUnionStart, int spanUnionEnd] 8945 // The final result is made of 3 parts: the text before, between and after the span 8946 // This is the text before, provided for context 8947 ssb.append(mText.subSequence(unionStart, spanStart).toString()); 8948 8949 // shift is used to offset spans positions wrt span's beginning 8950 final int shift = spanStart - unionStart; 8951 suggestionInfo.suggestionStart = shift; 8952 suggestionInfo.suggestionEnd = shift + text.length(); 8953 8954 // This is the actual suggestion text, which will be highlighted by the following code 8955 ssb.append(text); 8956 8957 String[] words = new String[wordLimits.length]; 8958 for (int i = 0; i < wordLimits.length; i++) { 8959 int wordStart = extractRangeStartFromLong(wordLimits[i]); 8960 int wordEnd = extractRangeEndFromLong(wordLimits[i]); 8961 words[i] = text.substring(wordStart, wordEnd); 8962 } 8963 8964 // Highlighted word algorithm is based on word matching between source and text 8965 // Matching words are found from left to right. TODO: change for RTL languages 8966 // Characters between matching words are highlighted 8967 int previousCommonWordIndex = -1; 8968 int nbHighlightSpans = 0; 8969 for (int i = 0; i < sourceWordLimits.length; i++) { 8970 int wordStart = extractRangeStartFromLong(sourceWordLimits[i]); 8971 int wordEnd = extractRangeEndFromLong(sourceWordLimits[i]); 8972 String sourceWord = sourceText.substring(wordStart, wordEnd); 8973 8974 for (int j = previousCommonWordIndex + 1; j < words.length; j++) { 8975 if (sourceWord.equals(words[j])) { 8976 if (j != previousCommonWordIndex + 1) { 8977 int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 : 8978 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 8979 int lastDifferentPosition = extractRangeStartFromLong(wordLimits[j]); 8980 ssb.setSpan(highlightSpan(nbHighlightSpans++), 8981 shift + firstDifferentPosition, shift + lastDifferentPosition, 8982 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 8983 } else { 8984 // Compare characters between words 8985 int previousSourceWordEnd = i == 0 ? 0 : 8986 extractRangeEndFromLong(sourceWordLimits[i - 1]); 8987 int sourceWordStart = extractRangeStartFromLong(sourceWordLimits[i]); 8988 String sourceSpaces = sourceText.substring(previousSourceWordEnd, 8989 sourceWordStart); 8990 8991 int previousWordEnd = j == 0 ? 0 : 8992 extractRangeEndFromLong(wordLimits[j - 1]); 8993 int currentWordStart = extractRangeStartFromLong(wordLimits[j]); 8994 String textSpaces = text.substring(previousWordEnd, currentWordStart); 8995 8996 if (!sourceSpaces.equals(textSpaces)) { 8997 ssb.setSpan(highlightSpan(nbHighlightSpans++), 8998 shift + previousWordEnd, shift + currentWordStart, 8999 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9000 } 9001 } 9002 previousCommonWordIndex = j; 9003 break; 9004 } 9005 } 9006 } 9007 9008 // Finally, compare ends of Strings 9009 if (previousCommonWordIndex < words.length - 1) { 9010 int firstDifferentPosition = previousCommonWordIndex < 0 ? 0 : 9011 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 9012 int lastDifferentPosition = textView.length(); 9013 ssb.setSpan(highlightSpan(nbHighlightSpans++), 9014 shift + firstDifferentPosition, shift + lastDifferentPosition, 9015 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9016 } else { 9017 int lastSourceWordEnd = sourceWordLimits.length == 0 ? 0 : 9018 extractRangeEndFromLong(sourceWordLimits[sourceWordLimits.length - 1]); 9019 String sourceSpaces = sourceText.substring(lastSourceWordEnd, sourceText.length()); 9020 9021 int lastCommonTextWordEnd = previousCommonWordIndex < 0 ? 0 : 9022 extractRangeEndFromLong(wordLimits[previousCommonWordIndex]); 9023 String textSpaces = text.substring(lastCommonTextWordEnd, textView.length()); 9024 9025 if (!sourceSpaces.equals(textSpaces) && textSpaces.length() > 0) { 9026 ssb.setSpan(highlightSpan(nbHighlightSpans++), 9027 shift + lastCommonTextWordEnd, shift + textView.length(), 9028 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 9029 } 9030 } 9031 9032 // Final part, text after the current suggestion range. 9033 ssb.append(mText.subSequence(spanEnd, unionEnd).toString()); 9034 textView.setText(ssb); 9035 } 9036 9037 public void hide() { 9038 if ((mText instanceof Editable) && mSuggestionRangeSpan != null) { 9039 ((Editable) mText).removeSpan(mSuggestionRangeSpan); 9040 } 9041 mContainer.dismiss(); 9042 } 9043 9044 @Override 9045 public void onClick(View view) { 9046 if (view instanceof TextView) { 9047 TextView textView = (TextView) view; 9048 SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); 9049 final int spanStart = suggestionInfo.spanStart; 9050 final int spanEnd = suggestionInfo.spanEnd; 9051 if (spanStart != NO_SUGGESTIONS) { 9052 // SuggestionSpans are removed by replace: save them before 9053 Editable editable = ((Editable) mText); 9054 SuggestionSpan[] suggestionSpans = editable.getSpans(spanStart, spanEnd, 9055 SuggestionSpan.class); 9056 final int length = suggestionSpans.length; 9057 int[] suggestionSpansStarts = new int[length]; 9058 int[] suggestionSpansEnds = new int[length]; 9059 int[] suggestionSpansFlags = new int[length]; 9060 for (int i = 0; i < length; i++) { 9061 final SuggestionSpan suggestionSpan = suggestionSpans[i]; 9062 suggestionSpansStarts[i] = editable.getSpanStart(suggestionSpan); 9063 suggestionSpansEnds[i] = editable.getSpanEnd(suggestionSpan); 9064 suggestionSpansFlags[i] = editable.getSpanFlags(suggestionSpan); 9065 } 9066 9067 final int suggestionStart = suggestionInfo.suggestionStart; 9068 final int suggestionEnd = suggestionInfo.suggestionEnd; 9069 final String suggestion = textView.getText().subSequence( 9070 suggestionStart, suggestionEnd).toString(); 9071 final String originalText = mText.subSequence(spanStart, spanEnd).toString(); 9072 ((Editable) mText).replace(spanStart, spanEnd, suggestion); 9073 9074 // Notify source IME of the suggestion pick. Do this before swaping texts. 9075 if (!TextUtils.isEmpty( 9076 suggestionInfo.suggestionSpan.getNotificationTargetClassName())) { 9077 InputMethodManager imm = InputMethodManager.peekInstance(); 9078 imm.notifySuggestionPicked(suggestionInfo.suggestionSpan, originalText, 9079 suggestionInfo.suggestionIndex); 9080 } 9081 9082 // Swap text content between actual text and Suggestion span 9083 String[] suggestions = suggestionInfo.suggestionSpan.getSuggestions(); 9084 suggestions[suggestionInfo.suggestionIndex] = originalText; 9085 9086 // Restore previous SuggestionSpans 9087 final int lengthDifference = suggestion.length() - (spanEnd - spanStart); 9088 for (int i = 0; i < length; i++) { 9089 // Only spans that include the modified region make sense after replacement 9090 // Spans partially included in the replaced region are removed, there is no 9091 // way to assign them a valid range after replacement 9092 if (suggestionSpansStarts[i] <= spanStart && 9093 suggestionSpansEnds[i] >= spanEnd) { 9094 editable.setSpan(suggestionSpans[i], suggestionSpansStarts[i], 9095 suggestionSpansEnds[i] + lengthDifference, 9096 suggestionSpansFlags[i]); 9097 } 9098 } 9099 } 9100 } 9101 hide(); 9102 } 9103 9104 void positionAtCursor() { 9105 View contentView = mContainer.getContentView(); 9106 int width = contentView.getMeasuredWidth(); 9107 int height = contentView.getMeasuredHeight(); 9108 final int offset = TextView.this.getSelectionStart(); 9109 final int line = mLayout.getLineForOffset(offset); 9110 final int lineBottom = mLayout.getLineBottom(line); 9111 float primaryHorizontal = mLayout.getPrimaryHorizontal(offset); 9112 9113 final Rect bounds = sCursorControllerTempRect; 9114 bounds.left = (int) (primaryHorizontal - width / 2.0f); 9115 bounds.top = lineBottom; 9116 9117 bounds.right = bounds.left + width; 9118 bounds.bottom = bounds.top + height; 9119 9120 convertFromViewportToContentCoordinates(bounds); 9121 9122 final int[] coords = mTempCoords; 9123 TextView.this.getLocationInWindow(coords); 9124 coords[0] += bounds.left; 9125 coords[1] += bounds.top; 9126 9127 final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); 9128 final int screenHeight = displayMetrics.heightPixels; 9129 9130 // Vertical clipping 9131 if (coords[1] + height > screenHeight) { 9132 // Try to position above current line instead 9133 // TODO use top layout instead, reverse suggestion order, 9134 // try full screen vertical down if it still does not fit. TBD with designers. 9135 9136 // Update dimensions from new view 9137 contentView = mContainer.getContentView(); 9138 width = contentView.getMeasuredWidth(); 9139 height = contentView.getMeasuredHeight(); 9140 9141 final int lineTop = mLayout.getLineTop(line); 9142 final int lineHeight = lineBottom - lineTop; 9143 coords[1] -= height + lineHeight; 9144 } 9145 9146 // Horizontal clipping 9147 coords[0] = Math.max(0, coords[0]); 9148 coords[0] = Math.min(displayMetrics.widthPixels - width, coords[0]); 9149 9150 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); 9151 } 9152 } 9153 9154 void showSuggestions() { 9155 if (!mSuggestionsEnabled || !isTextEditable()) return; 9156 9157 if (mSuggestionsPopupWindow == null) { 9158 mSuggestionsPopupWindow = new SuggestionsPopupWindow(); 9159 } 9160 hideControllers(); 9161 mSuggestionsPopupWindow.show(); 9162 } 9163 9164 void hideSuggestions() { 9165 if (mSuggestionsPopupWindow != null) { 9166 mSuggestionsPopupWindow.hide(); 9167 } 9168 } 9169 9170 /** 9171 * Some parts of the text can have alternate suggestion text attached. This is typically done by 9172 * the IME by adding {@link SuggestionSpan}s to the text. 9173 * 9174 * When suggestions are enabled (default), this list of suggestions will be displayed when the 9175 * user double taps on these parts of the text. No suggestions are displayed when this value is 9176 * false. Use {@link #setSuggestionsEnabled(boolean)} to change this value. 9177 * 9178 * @return true if the suggestions popup window is enabled. 9179 * 9180 * @attr ref android.R.styleable#TextView_suggestionsEnabled 9181 */ 9182 public boolean isSuggestionsEnabled() { 9183 return mSuggestionsEnabled; 9184 } 9185 9186 /** 9187 * Enables or disables the suggestion popup. See {@link #isSuggestionsEnabled()}. 9188 * 9189 * @param enabled Whether or not suggestions are enabled. 9190 */ 9191 public void setSuggestionsEnabled(boolean enabled) { 9192 mSuggestionsEnabled = enabled; 9193 } 9194 9195 /** 9196 * If provided, this ActionMode.Callback will be used to create the ActionMode when text 9197 * selection is initiated in this View. 9198 * 9199 * The standard implementation populates the menu with a subset of Select All, Cut, Copy and 9200 * Paste actions, depending on what this View supports. 9201 * 9202 * A custom implementation can add new entries in the default menu in its 9203 * {@link ActionMode.Callback#onPrepareActionMode(ActionMode, Menu)} method. The default actions 9204 * can also be removed from the menu using {@link Menu#removeItem(int)} and passing 9205 * {@link android.R.id#selectAll}, {@link android.R.id#cut}, {@link android.R.id#copy} or 9206 * {@link android.R.id#paste} ids as parameters. 9207 * 9208 * Returning false from {@link ActionMode.Callback#onCreateActionMode(ActionMode, Menu)} will 9209 * prevent the action mode from being started. 9210 * 9211 * Action click events should be handled by the custom implementation of 9212 * {@link ActionMode.Callback#onActionItemClicked(ActionMode, MenuItem)}. 9213 * 9214 * Note that text selection mode is not started when a TextView receives focus and the 9215 * {@link android.R.attr#selectAllOnFocus} flag has been set. The content is highlighted in 9216 * that case, to allow for quick replacement. 9217 */ 9218 public void setCustomSelectionActionModeCallback(ActionMode.Callback actionModeCallback) { 9219 mCustomSelectionActionModeCallback = actionModeCallback; 9220 } 9221 9222 /** 9223 * Retrieves the value set in {@link #setCustomSelectionActionModeCallback}. Default is null. 9224 * 9225 * @return The current custom selection callback. 9226 */ 9227 public ActionMode.Callback getCustomSelectionActionModeCallback() { 9228 return mCustomSelectionActionModeCallback; 9229 } 9230 9231 /** 9232 * 9233 * @return true if the selection mode was actually started. 9234 */ 9235 private boolean startSelectionActionMode() { 9236 if (mSelectionActionMode != null) { 9237 // Selection action mode is already started 9238 return false; 9239 } 9240 9241 if (!canSelectText() || !requestFocus()) { 9242 Log.w(LOG_TAG, "TextView does not support text selection. Action mode cancelled."); 9243 return false; 9244 } 9245 9246 if (!hasSelection()) { 9247 // There may already be a selection on device rotation 9248 boolean currentWordSelected = selectCurrentWord(); 9249 if (!currentWordSelected) { 9250 // No word found under cursor or text selection not permitted. 9251 return false; 9252 } 9253 } 9254 9255 ActionMode.Callback actionModeCallback = new SelectionActionModeCallback(); 9256 mSelectionActionMode = startActionMode(actionModeCallback); 9257 final boolean selectionStarted = mSelectionActionMode != null; 9258 9259 if (selectionStarted && !mTextIsSelectable) { 9260 // Show the IME to be able to replace text, except when selecting non editable text. 9261 final InputMethodManager imm = InputMethodManager.peekInstance(); 9262 if (imm != null) imm.showSoftInput(this, 0, null); 9263 } 9264 9265 return selectionStarted; 9266 } 9267 9268 private void stopSelectionActionMode() { 9269 if (mSelectionActionMode != null) { 9270 // This will hide the mSelectionModifierCursorController 9271 mSelectionActionMode.finish(); 9272 } 9273 } 9274 9275 /** 9276 * Paste clipboard content between min and max positions. 9277 */ 9278 private void paste(int min, int max) { 9279 ClipboardManager clipboard = 9280 (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); 9281 ClipData clip = clipboard.getPrimaryClip(); 9282 if (clip != null) { 9283 boolean didFirst = false; 9284 for (int i=0; i<clip.getItemCount(); i++) { 9285 CharSequence paste = clip.getItemAt(i).coerceToText(getContext()); 9286 if (paste != null) { 9287 if (!didFirst) { 9288 long minMax = prepareSpacesAroundPaste(min, max, paste); 9289 min = extractRangeStartFromLong(minMax); 9290 max = extractRangeEndFromLong(minMax); 9291 Selection.setSelection((Spannable) mText, max); 9292 ((Editable) mText).replace(min, max, paste); 9293 didFirst = true; 9294 } else { 9295 ((Editable) mText).insert(getSelectionEnd(), "\n"); 9296 ((Editable) mText).insert(getSelectionEnd(), paste); 9297 } 9298 } 9299 } 9300 stopSelectionActionMode(); 9301 sLastCutOrCopyTime = 0; 9302 } 9303 } 9304 9305 private void setPrimaryClip(ClipData clip) { 9306 ClipboardManager clipboard = (ClipboardManager) getContext(). 9307 getSystemService(Context.CLIPBOARD_SERVICE); 9308 clipboard.setPrimaryClip(clip); 9309 sLastCutOrCopyTime = SystemClock.uptimeMillis(); 9310 } 9311 9312 /** 9313 * An ActionMode Callback class that is used to provide actions while in text selection mode. 9314 * 9315 * The default callback provides a subset of Select All, Cut, Copy and Paste actions, depending 9316 * on which of these this TextView supports. 9317 */ 9318 private class SelectionActionModeCallback implements ActionMode.Callback { 9319 9320 @Override 9321 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 9322 TypedArray styledAttributes = mContext.obtainStyledAttributes(R.styleable.Theme); 9323 9324 boolean allowText = getContext().getResources().getBoolean( 9325 com.android.internal.R.bool.config_allowActionMenuItemTextWithIcon); 9326 9327 mode.setTitle(allowText ? 9328 mContext.getString(com.android.internal.R.string.textSelectionCABTitle) : null); 9329 mode.setSubtitle(null); 9330 9331 int selectAllIconId = 0; // No icon by default 9332 if (!allowText) { 9333 // Provide an icon, text will not be displayed on smaller screens. 9334 selectAllIconId = styledAttributes.getResourceId( 9335 R.styleable.Theme_actionModeSelectAllDrawable, 0); 9336 } 9337 9338 menu.add(0, ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). 9339 setIcon(selectAllIconId). 9340 setAlphabeticShortcut('a'). 9341 setShowAsAction( 9342 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9343 9344 if (canCut()) { 9345 menu.add(0, ID_CUT, 0, com.android.internal.R.string.cut). 9346 setIcon(styledAttributes.getResourceId( 9347 R.styleable.Theme_actionModeCutDrawable, 0)). 9348 setAlphabeticShortcut('x'). 9349 setShowAsAction( 9350 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9351 } 9352 9353 if (canCopy()) { 9354 menu.add(0, ID_COPY, 0, com.android.internal.R.string.copy). 9355 setIcon(styledAttributes.getResourceId( 9356 R.styleable.Theme_actionModeCopyDrawable, 0)). 9357 setAlphabeticShortcut('c'). 9358 setShowAsAction( 9359 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9360 } 9361 9362 if (canPaste()) { 9363 menu.add(0, ID_PASTE, 0, com.android.internal.R.string.paste). 9364 setIcon(styledAttributes.getResourceId( 9365 R.styleable.Theme_actionModePasteDrawable, 0)). 9366 setAlphabeticShortcut('v'). 9367 setShowAsAction( 9368 MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); 9369 } 9370 9371 styledAttributes.recycle(); 9372 9373 if (mCustomSelectionActionModeCallback != null) { 9374 if (!mCustomSelectionActionModeCallback.onCreateActionMode(mode, menu)) { 9375 // The custom mode can choose to cancel the action mode 9376 return false; 9377 } 9378 } 9379 9380 if (menu.hasVisibleItems() || mode.getCustomView() != null) { 9381 getSelectionController().show(); 9382 return true; 9383 } else { 9384 return false; 9385 } 9386 } 9387 9388 @Override 9389 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 9390 if (mCustomSelectionActionModeCallback != null) { 9391 return mCustomSelectionActionModeCallback.onPrepareActionMode(mode, menu); 9392 } 9393 return true; 9394 } 9395 9396 @Override 9397 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 9398 if (mCustomSelectionActionModeCallback != null && 9399 mCustomSelectionActionModeCallback.onActionItemClicked(mode, item)) { 9400 return true; 9401 } 9402 return onTextContextMenuItem(item.getItemId()); 9403 } 9404 9405 @Override 9406 public void onDestroyActionMode(ActionMode mode) { 9407 if (mCustomSelectionActionModeCallback != null) { 9408 mCustomSelectionActionModeCallback.onDestroyActionMode(mode); 9409 } 9410 Selection.setSelection((Spannable) mText, getSelectionEnd()); 9411 9412 if (mSelectionModifierCursorController != null) { 9413 mSelectionModifierCursorController.hide(); 9414 } 9415 9416 mSelectionActionMode = null; 9417 } 9418 } 9419 9420 private class PastePopupWindow implements OnClickListener { 9421 private final PopupWindow mContainer; 9422 private final View[] mPasteViews = new View[4]; 9423 private final int[] mPasteViewLayouts = new int[] { 9424 mTextEditPasteWindowLayout, mTextEditNoPasteWindowLayout, 9425 mTextEditSidePasteWindowLayout, mTextEditSideNoPasteWindowLayout }; 9426 9427 public PastePopupWindow() { 9428 mContainer = new PopupWindow(TextView.this.mContext, null, 9429 com.android.internal.R.attr.textSelectHandleWindowStyle); 9430 mContainer.setSplitTouchEnabled(true); 9431 mContainer.setClippingEnabled(false); 9432 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 9433 9434 mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); 9435 mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 9436 } 9437 9438 private int viewIndex(boolean onTop) { 9439 return (onTop ? 0 : 1<<1) + (canPaste() ? 0 : 1<<0); 9440 } 9441 9442 private void updateContent(boolean onTop) { 9443 final int viewIndex = viewIndex(onTop); 9444 View view = mPasteViews[viewIndex]; 9445 9446 if (view == null) { 9447 final int layout = mPasteViewLayouts[viewIndex]; 9448 LayoutInflater inflater = (LayoutInflater)TextView.this.mContext. 9449 getSystemService(Context.LAYOUT_INFLATER_SERVICE); 9450 if (inflater != null) { 9451 view = inflater.inflate(layout, null); 9452 } 9453 9454 if (view == null) { 9455 throw new IllegalArgumentException("Unable to inflate TextEdit paste window"); 9456 } 9457 9458 final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); 9459 view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 9460 ViewGroup.LayoutParams.WRAP_CONTENT)); 9461 view.measure(size, size); 9462 9463 view.setOnClickListener(this); 9464 9465 mPasteViews[viewIndex] = view; 9466 } 9467 9468 mContainer.setContentView(view); 9469 } 9470 9471 public void show() { 9472 updateContent(true); 9473 positionAtCursor(); 9474 } 9475 9476 public void hide() { 9477 mContainer.dismiss(); 9478 } 9479 9480 public boolean isShowing() { 9481 return mContainer.isShowing(); 9482 } 9483 9484 @Override 9485 public void onClick(View v) { 9486 if (canPaste()) { 9487 onTextContextMenuItem(ID_PASTE); 9488 } 9489 hide(); 9490 } 9491 9492 void positionAtCursor() { 9493 View contentView = mContainer.getContentView(); 9494 int width = contentView.getMeasuredWidth(); 9495 int height = contentView.getMeasuredHeight(); 9496 final int offset = TextView.this.getSelectionStart(); 9497 final int line = mLayout.getLineForOffset(offset); 9498 final int lineTop = mLayout.getLineTop(line); 9499 float primaryHorizontal = mLayout.getPrimaryHorizontal(offset); 9500 9501 final Rect bounds = sCursorControllerTempRect; 9502 bounds.left = (int) (primaryHorizontal - width / 2.0f); 9503 bounds.top = lineTop - height; 9504 9505 bounds.right = bounds.left + width; 9506 bounds.bottom = bounds.top + height; 9507 9508 convertFromViewportToContentCoordinates(bounds); 9509 9510 final int[] coords = mTempCoords; 9511 TextView.this.getLocationInWindow(coords); 9512 coords[0] += bounds.left; 9513 coords[1] += bounds.top; 9514 9515 final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels; 9516 if (coords[1] < 0) { 9517 updateContent(false); 9518 // Update dimensions from new view 9519 contentView = mContainer.getContentView(); 9520 width = contentView.getMeasuredWidth(); 9521 height = contentView.getMeasuredHeight(); 9522 9523 // Vertical clipping, move under edited line and to the side of insertion cursor 9524 // TODO bottom clipping in case there is no system bar 9525 coords[1] += height; 9526 final int lineBottom = mLayout.getLineBottom(line); 9527 final int lineHeight = lineBottom - lineTop; 9528 coords[1] += lineHeight; 9529 9530 // Move to right hand side of insertion cursor by default. TODO RTL text. 9531 final Drawable handle = mContext.getResources().getDrawable(mTextSelectHandleRes); 9532 final int handleHalfWidth = handle.getIntrinsicWidth() / 2; 9533 9534 if (primaryHorizontal + handleHalfWidth + width < screenWidth) { 9535 coords[0] += handleHalfWidth + width / 2; 9536 } else { 9537 coords[0] -= handleHalfWidth + width / 2; 9538 } 9539 } else { 9540 // Horizontal clipping 9541 coords[0] = Math.max(0, coords[0]); 9542 coords[0] = Math.min(screenWidth - width, coords[0]); 9543 } 9544 9545 mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); 9546 } 9547 } 9548 9549 private abstract class HandleView extends View implements ViewTreeObserver.OnPreDrawListener { 9550 protected Drawable mDrawable; 9551 private final PopupWindow mContainer; 9552 // Position with respect to the parent TextView 9553 private int mPositionX, mPositionY; 9554 private boolean mIsDragging; 9555 // Offset from touch position to mPosition 9556 private float mTouchToWindowOffsetX, mTouchToWindowOffsetY; 9557 protected float mHotspotX; 9558 // Offsets the hotspot point up, so that cursor is not hidden by the finger when moving up 9559 private float mTouchOffsetY; 9560 // Where the touch position should be on the handle to ensure a maximum cursor visibility 9561 private float mIdealVerticalOffset; 9562 // Parent's (TextView) previous position in window 9563 private int mLastParentX, mLastParentY; 9564 // PopupWindow container absolute position with respect to the enclosing window 9565 private int mContainerPositionX, mContainerPositionY; 9566 // Visible or not (scrolled off screen), whether or not this handle should be visible 9567 private boolean mIsActive = false; 9568 // Used to detect that setFrame was called 9569 private boolean mNeedsUpdate = true; 9570 9571 public HandleView() { 9572 super(TextView.this.mContext); 9573 mContainer = new PopupWindow(TextView.this.mContext, null, 9574 com.android.internal.R.attr.textSelectHandleWindowStyle); 9575 mContainer.setSplitTouchEnabled(true); 9576 mContainer.setClippingEnabled(false); 9577 mContainer.setWindowLayoutType(WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL); 9578 mContainer.setContentView(this); 9579 9580 initDrawable(); 9581 9582 final int handleHeight = mDrawable.getIntrinsicHeight(); 9583 mTouchOffsetY = -0.3f * handleHeight; 9584 mIdealVerticalOffset = 0.7f * handleHeight; 9585 } 9586 9587 @Override 9588 protected boolean setFrame(int left, int top, int right, int bottom) { 9589 boolean changed = super.setFrame(left, top, right, bottom); 9590 // onPreDraw is called for PhoneWindow before the layout of this view is 9591 // performed. Make sure to update position, even if container didn't move. 9592 if (changed) mNeedsUpdate = true; 9593 return changed; 9594 } 9595 9596 protected abstract void initDrawable(); 9597 9598 // Touch-up filter: number of previous positions remembered 9599 private static final int HISTORY_SIZE = 5; 9600 private static final int TOUCH_UP_FILTER_DELAY_AFTER = 150; 9601 private static final int TOUCH_UP_FILTER_DELAY_BEFORE = 350; 9602 private final long[] mPreviousOffsetsTimes = new long[HISTORY_SIZE]; 9603 private final int[] mPreviousOffsets = new int[HISTORY_SIZE]; 9604 private int mPreviousOffsetIndex = 0; 9605 private int mNumberPreviousOffsets = 0; 9606 9607 private void startTouchUpFilter(int offset) { 9608 mNumberPreviousOffsets = 0; 9609 addPositionToTouchUpFilter(offset); 9610 } 9611 9612 private void addPositionToTouchUpFilter(int offset) { 9613 if (mNumberPreviousOffsets > 0 && 9614 mPreviousOffsets[mPreviousOffsetIndex] == offset) { 9615 // Make sure only actual changes of position are recorded. 9616 return; 9617 } 9618 9619 mPreviousOffsetIndex = (mPreviousOffsetIndex + 1) % HISTORY_SIZE; 9620 mPreviousOffsets[mPreviousOffsetIndex] = offset; 9621 mPreviousOffsetsTimes[mPreviousOffsetIndex] = SystemClock.uptimeMillis(); 9622 mNumberPreviousOffsets++; 9623 } 9624 9625 private void filterOnTouchUp() { 9626 final long now = SystemClock.uptimeMillis(); 9627 int i = 0; 9628 int index = mPreviousOffsetIndex; 9629 final int iMax = Math.min(mNumberPreviousOffsets, HISTORY_SIZE); 9630 while (i < iMax && (now - mPreviousOffsetsTimes[index]) < TOUCH_UP_FILTER_DELAY_AFTER) { 9631 i++; 9632 index = (mPreviousOffsetIndex - i + HISTORY_SIZE) % HISTORY_SIZE; 9633 } 9634 9635 if (i > 0 && i < iMax && 9636 (now - mPreviousOffsetsTimes[index]) > TOUCH_UP_FILTER_DELAY_BEFORE) { 9637 updateOffset(mPreviousOffsets[index]); 9638 } 9639 } 9640 9641 @Override 9642 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 9643 setMeasuredDimension(mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); 9644 } 9645 9646 public void show() { 9647 if (isShowing()) { 9648 mContainer.update(mContainerPositionX, mContainerPositionY, 9649 mRight - mLeft, mBottom - mTop); 9650 } else { 9651 mContainer.showAtLocation(TextView.this, 0, 9652 mContainerPositionX, mContainerPositionY); 9653 9654 mIsActive = true; 9655 9656 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9657 vto.addOnPreDrawListener(this); 9658 } 9659 } 9660 9661 protected void dismiss() { 9662 mIsDragging = false; 9663 mContainer.dismiss(); 9664 } 9665 9666 public void hide() { 9667 dismiss(); 9668 9669 mIsActive = false; 9670 9671 ViewTreeObserver vto = TextView.this.getViewTreeObserver(); 9672 vto.removeOnPreDrawListener(this); 9673 } 9674 9675 public boolean isShowing() { 9676 return mContainer.isShowing(); 9677 } 9678 9679 private boolean isPositionVisible() { 9680 // Always show a dragging handle. 9681 if (mIsDragging) { 9682 return true; 9683 } 9684 9685 if (isInBatchEditMode()) { 9686 return false; 9687 } 9688 9689 final int extendedPaddingTop = getExtendedPaddingTop(); 9690 final int extendedPaddingBottom = getExtendedPaddingBottom(); 9691 final int compoundPaddingLeft = getCompoundPaddingLeft(); 9692 final int compoundPaddingRight = getCompoundPaddingRight(); 9693 9694 final TextView textView = TextView.this; 9695 9696 if (mTempRect == null) mTempRect = new Rect(); 9697 final Rect clip = mTempRect; 9698 clip.left = compoundPaddingLeft; 9699 clip.top = extendedPaddingTop; 9700 clip.right = textView.getWidth() - compoundPaddingRight; 9701 clip.bottom = textView.getHeight() - extendedPaddingBottom; 9702 9703 final ViewParent parent = textView.getParent(); 9704 if (parent == null || !parent.getChildVisibleRect(textView, clip, null)) { 9705 return false; 9706 } 9707 9708 final int[] coords = mTempCoords; 9709 textView.getLocationInWindow(coords); 9710 final int posX = coords[0] + mPositionX + (int) mHotspotX; 9711 final int posY = coords[1] + mPositionY; 9712 9713 // Offset by 1 to take into account 0.5 and int rounding around getPrimaryHorizontal. 9714 return posX >= clip.left - 1 && posX <= clip.right + 1 && 9715 posY >= clip.top && posY <= clip.bottom; 9716 } 9717 9718 public abstract int getCurrentCursorOffset(); 9719 9720 public abstract void updateOffset(int offset); 9721 9722 public abstract void updatePosition(float x, float y); 9723 9724 protected void positionAtCursorOffset(int offset) { 9725 // A HandleView relies on the layout, which may be nulled by external methods. 9726 if (mLayout == null) { 9727 // Will update controllers' state, hiding them and stopping selection mode if needed 9728 prepareCursorControllers(); 9729 return; 9730 } 9731 9732 addPositionToTouchUpFilter(offset); 9733 final int line = mLayout.getLineForOffset(offset); 9734 final int lineBottom = mLayout.getLineBottom(line); 9735 9736 mPositionX = (int) (mLayout.getPrimaryHorizontal(offset) - 0.5f - mHotspotX); 9737 mPositionY = lineBottom; 9738 9739 // Take TextView's padding into account. 9740 mPositionX += viewportToContentHorizontalOffset(); 9741 mPositionY += viewportToContentVerticalOffset(); 9742 } 9743 9744 private void checkForContainerPositionChange() { 9745 positionAtCursorOffset(getCurrentCursorOffset()); 9746 9747 final int previousContainerPositionX = mContainerPositionX; 9748 final int previousContainerPositionY = mContainerPositionY; 9749 9750 TextView.this.getLocationInWindow(mTempCoords); 9751 mContainerPositionX = mTempCoords[0] + mPositionX; 9752 mContainerPositionY = mTempCoords[1] + mPositionY; 9753 9754 mNeedsUpdate |= previousContainerPositionX != mContainerPositionX; 9755 mNeedsUpdate |= previousContainerPositionY != mContainerPositionY; 9756 } 9757 9758 public boolean onPreDraw() { 9759 checkForContainerPositionChange(); 9760 if (mNeedsUpdate) { 9761 if (mIsDragging) { 9762 if (mTempCoords[0] != mLastParentX || mTempCoords[1] != mLastParentY) { 9763 mTouchToWindowOffsetX += mTempCoords[0] - mLastParentX; 9764 mTouchToWindowOffsetY += mTempCoords[1] - mLastParentY; 9765 mLastParentX = mTempCoords[0]; 9766 mLastParentY = mTempCoords[1]; 9767 } 9768 } 9769 9770 onHandleMoved(); 9771 9772 if (isPositionVisible()) { 9773 mContainer.update(mContainerPositionX, mContainerPositionY, 9774 mRight - mLeft, mBottom - mTop); 9775 9776 if (mIsActive && !isShowing()) { 9777 show(); 9778 } 9779 } else { 9780 if (isShowing()) { 9781 dismiss(); 9782 } 9783 } 9784 mNeedsUpdate = false; 9785 } 9786 return true; 9787 } 9788 9789 @Override 9790 protected void onDraw(Canvas c) { 9791 mDrawable.setBounds(0, 0, mRight - mLeft, mBottom - mTop); 9792 mDrawable.draw(c); 9793 } 9794 9795 @Override 9796 public boolean onTouchEvent(MotionEvent ev) { 9797 switch (ev.getActionMasked()) { 9798 case MotionEvent.ACTION_DOWN: { 9799 startTouchUpFilter(getCurrentCursorOffset()); 9800 mTouchToWindowOffsetX = ev.getRawX() - mPositionX; 9801 mTouchToWindowOffsetY = ev.getRawY() - mPositionY; 9802 9803 final int[] coords = mTempCoords; 9804 TextView.this.getLocationInWindow(coords); 9805 mLastParentX = coords[0]; 9806 mLastParentY = coords[1]; 9807 mIsDragging = true; 9808 break; 9809 } 9810 9811 case MotionEvent.ACTION_MOVE: { 9812 final float rawX = ev.getRawX(); 9813 final float rawY = ev.getRawY(); 9814 9815 // Vertical hysteresis: vertical down movement tends to snap to ideal offset 9816 final float previousVerticalOffset = mTouchToWindowOffsetY - mLastParentY; 9817 final float currentVerticalOffset = rawY - mPositionY - mLastParentY; 9818 float newVerticalOffset; 9819 if (previousVerticalOffset < mIdealVerticalOffset) { 9820 newVerticalOffset = Math.min(currentVerticalOffset, mIdealVerticalOffset); 9821 newVerticalOffset = Math.max(newVerticalOffset, previousVerticalOffset); 9822 } else { 9823 newVerticalOffset = Math.max(currentVerticalOffset, mIdealVerticalOffset); 9824 newVerticalOffset = Math.min(newVerticalOffset, previousVerticalOffset); 9825 } 9826 mTouchToWindowOffsetY = newVerticalOffset + mLastParentY; 9827 9828 final float newPosX = rawX - mTouchToWindowOffsetX + mHotspotX; 9829 final float newPosY = rawY - mTouchToWindowOffsetY + mTouchOffsetY; 9830 9831 updatePosition(newPosX, newPosY); 9832 break; 9833 } 9834 9835 case MotionEvent.ACTION_UP: 9836 filterOnTouchUp(); 9837 mIsDragging = false; 9838 break; 9839 9840 case MotionEvent.ACTION_CANCEL: 9841 mIsDragging = false; 9842 break; 9843 } 9844 return true; 9845 } 9846 9847 public boolean isDragging() { 9848 return mIsDragging; 9849 } 9850 9851 void onHandleMoved() { 9852 // Does nothing by default 9853 } 9854 9855 public void onDetached() { 9856 // Should be overriden to clean possible Runnable 9857 } 9858 } 9859 9860 private class InsertionHandleView extends HandleView { 9861 private static final int DELAY_BEFORE_FADE_OUT = 4000; 9862 private static final int RECENT_CUT_COPY_DURATION = 15 * 1000; // seconds 9863 9864 // Used to detect taps on the insertion handle, which will affect the PastePopupWindow 9865 private float mDownPositionX, mDownPositionY; 9866 private PastePopupWindow mPastePopupWindow; 9867 private Runnable mHider; 9868 private Runnable mPastePopupShower; 9869 9870 @Override 9871 public void show() { 9872 super.show(); 9873 hideDelayed(); 9874 hidePastePopupWindow(); 9875 } 9876 9877 public void show(int delayBeforePaste) { 9878 show(); 9879 9880 final long durationSinceCutOrCopy = SystemClock.uptimeMillis() - sLastCutOrCopyTime; 9881 if (durationSinceCutOrCopy < RECENT_CUT_COPY_DURATION) { 9882 delayBeforePaste = 0; 9883 } 9884 if (delayBeforePaste == 0 || canPaste()) { 9885 if (mPastePopupShower == null) { 9886 mPastePopupShower = new Runnable() { 9887 public void run() { 9888 showPastePopupWindow(); 9889 } 9890 }; 9891 } 9892 TextView.this.postDelayed(mPastePopupShower, delayBeforePaste); 9893 } 9894 } 9895 9896 @Override 9897 protected void dismiss() { 9898 super.dismiss(); 9899 onDetached(); 9900 } 9901 9902 private void hideDelayed() { 9903 removeHiderCallback(); 9904 if (mHider == null) { 9905 mHider = new Runnable() { 9906 public void run() { 9907 hide(); 9908 } 9909 }; 9910 } 9911 TextView.this.postDelayed(mHider, DELAY_BEFORE_FADE_OUT); 9912 } 9913 9914 private void removeHiderCallback() { 9915 if (mHider != null) { 9916 TextView.this.removeCallbacks(mHider); 9917 } 9918 } 9919 9920 @Override 9921 protected void initDrawable() { 9922 if (mSelectHandleCenter == null) { 9923 mSelectHandleCenter = mContext.getResources().getDrawable( 9924 mTextSelectHandleRes); 9925 } 9926 mDrawable = mSelectHandleCenter; 9927 mHotspotX = mDrawable.getIntrinsicWidth() / 2.0f; 9928 } 9929 9930 @Override 9931 public boolean onTouchEvent(MotionEvent ev) { 9932 final boolean result = super.onTouchEvent(ev); 9933 9934 switch (ev.getActionMasked()) { 9935 case MotionEvent.ACTION_DOWN: 9936 mDownPositionX = ev.getRawX(); 9937 mDownPositionY = ev.getRawY(); 9938 break; 9939 9940 case MotionEvent.ACTION_UP: 9941 final float deltaX = mDownPositionX - ev.getRawX(); 9942 final float deltaY = mDownPositionY - ev.getRawY(); 9943 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 9944 if (distanceSquared < mSquaredTouchSlopDistance) { 9945 if (mPastePopupWindow != null && mPastePopupWindow.isShowing()) { 9946 // Tapping on the handle dismisses the displayed paste view, 9947 mPastePopupWindow.hide(); 9948 } else { 9949 show(0); 9950 } 9951 } 9952 hideDelayed(); 9953 break; 9954 9955 case MotionEvent.ACTION_CANCEL: 9956 hideDelayed(); 9957 break; 9958 9959 default: 9960 break; 9961 } 9962 9963 return result; 9964 } 9965 9966 @Override 9967 public int getCurrentCursorOffset() { 9968 return TextView.this.getSelectionStart(); 9969 } 9970 9971 @Override 9972 public void updateOffset(int offset) { 9973 Selection.setSelection((Spannable) mText, offset); 9974 } 9975 9976 @Override 9977 public void updatePosition(float x, float y) { 9978 updateOffset(getOffsetForPosition(x, y)); 9979 } 9980 9981 void showPastePopupWindow() { 9982 if (mPastePopupWindow == null) { 9983 mPastePopupWindow = new PastePopupWindow(); 9984 } 9985 mPastePopupWindow.show(); 9986 } 9987 9988 @Override 9989 void onHandleMoved() { 9990 removeHiderCallback(); 9991 hidePastePopupWindow(); 9992 } 9993 9994 void hidePastePopupWindow() { 9995 if (mPastePopupShower != null) { 9996 TextView.this.removeCallbacks(mPastePopupShower); 9997 } 9998 if (mPastePopupWindow != null) { 9999 mPastePopupWindow.hide(); 10000 } 10001 } 10002 10003 @Override 10004 public void onDetached() { 10005 removeHiderCallback(); 10006 hidePastePopupWindow(); 10007 } 10008 } 10009 10010 private class SelectionStartHandleView extends HandleView { 10011 @Override 10012 protected void initDrawable() { 10013 if (mSelectHandleLeft == null) { 10014 mSelectHandleLeft = mContext.getResources().getDrawable( 10015 mTextSelectHandleLeftRes); 10016 } 10017 mDrawable = mSelectHandleLeft; 10018 mHotspotX = mDrawable.getIntrinsicWidth() * 3.0f / 4.0f; 10019 } 10020 10021 @Override 10022 public int getCurrentCursorOffset() { 10023 return TextView.this.getSelectionStart(); 10024 } 10025 10026 @Override 10027 public void updateOffset(int offset) { 10028 Selection.setSelection((Spannable) mText, offset, getSelectionEnd()); 10029 } 10030 10031 @Override 10032 public void updatePosition(float x, float y) { 10033 final int selectionStart = getSelectionStart(); 10034 final int selectionEnd = getSelectionEnd(); 10035 10036 int offset = getOffsetForPosition(x, y); 10037 10038 // No need to redraw when the offset is unchanged 10039 if (offset == selectionStart) return; 10040 // Handles can not cross and selection is at least one character 10041 if (offset >= selectionEnd) offset = selectionEnd - 1; 10042 10043 Selection.setSelection((Spannable) mText, offset, selectionEnd); 10044 } 10045 } 10046 10047 private class SelectionEndHandleView extends HandleView { 10048 @Override 10049 protected void initDrawable() { 10050 if (mSelectHandleRight == null) { 10051 mSelectHandleRight = mContext.getResources().getDrawable( 10052 mTextSelectHandleRightRes); 10053 } 10054 mDrawable = mSelectHandleRight; 10055 mHotspotX = mDrawable.getIntrinsicWidth() / 4.0f; 10056 } 10057 10058 @Override 10059 public int getCurrentCursorOffset() { 10060 return TextView.this.getSelectionEnd(); 10061 } 10062 10063 @Override 10064 public void updateOffset(int offset) { 10065 Selection.setSelection((Spannable) mText, getSelectionStart(), offset); 10066 } 10067 10068 @Override 10069 public void updatePosition(float x, float y) { 10070 final int selectionStart = getSelectionStart(); 10071 final int selectionEnd = getSelectionEnd(); 10072 10073 int offset = getOffsetForPosition(x, y); 10074 10075 // No need to redraw when the offset is unchanged 10076 if (offset == selectionEnd) return; 10077 // Handles can not cross and selection is at least one character 10078 if (offset <= selectionStart) offset = selectionStart + 1; 10079 10080 Selection.setSelection((Spannable) mText, selectionStart, offset); 10081 } 10082 } 10083 10084 /** 10085 * A CursorController instance can be used to control a cursor in the text. 10086 * It is not used outside of {@link TextView}. 10087 * @hide 10088 */ 10089 private interface CursorController extends ViewTreeObserver.OnTouchModeChangeListener { 10090 /** 10091 * Makes the cursor controller visible on screen. Will be drawn by {@link #draw(Canvas)}. 10092 * See also {@link #hide()}. 10093 */ 10094 public void show(); 10095 10096 /** 10097 * Hide the cursor controller from screen. 10098 * See also {@link #show()}. 10099 */ 10100 public void hide(); 10101 10102 /** 10103 * Called when the view is detached from window. Perform house keeping task, such as 10104 * stopping Runnable thread that would otherwise keep a reference on the context, thus 10105 * preventing the activity from being recycled. 10106 */ 10107 public void onDetached(); 10108 } 10109 10110 private class InsertionPointCursorController implements CursorController { 10111 private static final int DELAY_BEFORE_PASTE = 2000; 10112 10113 private InsertionHandleView mHandle; 10114 10115 public void show() { 10116 ((InsertionHandleView) getHandle()).show(DELAY_BEFORE_PASTE); 10117 } 10118 10119 public void showWithPaste() { 10120 ((InsertionHandleView) getHandle()).show(0); 10121 } 10122 10123 public void hide() { 10124 if (mHandle != null) { 10125 mHandle.hide(); 10126 } 10127 } 10128 10129 public void onTouchModeChanged(boolean isInTouchMode) { 10130 if (!isInTouchMode) { 10131 hide(); 10132 } 10133 } 10134 10135 private HandleView getHandle() { 10136 if (mHandle == null) { 10137 mHandle = new InsertionHandleView(); 10138 } 10139 return mHandle; 10140 } 10141 10142 @Override 10143 public void onDetached() { 10144 final ViewTreeObserver observer = getViewTreeObserver(); 10145 observer.removeOnTouchModeChangeListener(this); 10146 10147 if (mHandle != null) mHandle.onDetached(); 10148 } 10149 } 10150 10151 private class SelectionModifierCursorController implements CursorController { 10152 // The cursor controller handles, lazily created when shown. 10153 private SelectionStartHandleView mStartHandle; 10154 private SelectionEndHandleView mEndHandle; 10155 // The offsets of that last touch down event. Remembered to start selection there. 10156 private int mMinTouchOffset, mMaxTouchOffset; 10157 10158 // Double tap detection 10159 private long mPreviousTapUpTime = 0; 10160 private float mPreviousTapPositionX, mPreviousTapPositionY; 10161 10162 SelectionModifierCursorController() { 10163 resetTouchOffsets(); 10164 } 10165 10166 public void show() { 10167 if (isInBatchEditMode()) { 10168 return; 10169 } 10170 10171 // Lazy object creation has to be done before updatePosition() is called. 10172 if (mStartHandle == null) mStartHandle = new SelectionStartHandleView(); 10173 if (mEndHandle == null) mEndHandle = new SelectionEndHandleView(); 10174 10175 mStartHandle.show(); 10176 mEndHandle.show(); 10177 10178 hideInsertionPointCursorController(); 10179 hideSuggestions(); 10180 } 10181 10182 public void hide() { 10183 if (mStartHandle != null) mStartHandle.hide(); 10184 if (mEndHandle != null) mEndHandle.hide(); 10185 } 10186 10187 public void onTouchEvent(MotionEvent event) { 10188 // This is done even when the View does not have focus, so that long presses can start 10189 // selection and tap can move cursor from this tap position. 10190 switch (event.getActionMasked()) { 10191 case MotionEvent.ACTION_DOWN: 10192 final float x = event.getX(); 10193 final float y = event.getY(); 10194 10195 // Remember finger down position, to be able to start selection from there 10196 mMinTouchOffset = mMaxTouchOffset = getOffsetForPosition(x, y); 10197 10198 // Double tap detection 10199 long duration = SystemClock.uptimeMillis() - mPreviousTapUpTime; 10200 if (duration <= ViewConfiguration.getDoubleTapTimeout() && 10201 isPositionOnText(x, y)) { 10202 final float deltaX = x - mPreviousTapPositionX; 10203 final float deltaY = y - mPreviousTapPositionY; 10204 final float distanceSquared = deltaX * deltaX + deltaY * deltaY; 10205 if (distanceSquared < mSquaredTouchSlopDistance) { 10206 showSuggestions(); 10207 mDiscardNextActionUp = true; 10208 } 10209 } 10210 10211 mPreviousTapPositionX = x; 10212 mPreviousTapPositionY = y; 10213 10214 break; 10215 10216 case MotionEvent.ACTION_POINTER_DOWN: 10217 case MotionEvent.ACTION_POINTER_UP: 10218 // Handle multi-point gestures. Keep min and max offset positions. 10219 // Only activated for devices that correctly handle multi-touch. 10220 if (mContext.getPackageManager().hasSystemFeature( 10221 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT)) { 10222 updateMinAndMaxOffsets(event); 10223 } 10224 break; 10225 10226 case MotionEvent.ACTION_UP: 10227 mPreviousTapUpTime = SystemClock.uptimeMillis(); 10228 break; 10229 } 10230 } 10231 10232 /** 10233 * @param event 10234 */ 10235 private void updateMinAndMaxOffsets(MotionEvent event) { 10236 int pointerCount = event.getPointerCount(); 10237 for (int index = 0; index < pointerCount; index++) { 10238 int offset = getOffsetForPosition(event.getX(index), event.getY(index)); 10239 if (offset < mMinTouchOffset) mMinTouchOffset = offset; 10240 if (offset > mMaxTouchOffset) mMaxTouchOffset = offset; 10241 } 10242 } 10243 10244 public int getMinTouchOffset() { 10245 return mMinTouchOffset; 10246 } 10247 10248 public int getMaxTouchOffset() { 10249 return mMaxTouchOffset; 10250 } 10251 10252 public void resetTouchOffsets() { 10253 mMinTouchOffset = mMaxTouchOffset = -1; 10254 } 10255 10256 /** 10257 * @return true iff this controller is currently used to move the selection start. 10258 */ 10259 public boolean isSelectionStartDragged() { 10260 return mStartHandle != null && mStartHandle.isDragging(); 10261 } 10262 10263 public void onTouchModeChanged(boolean isInTouchMode) { 10264 if (!isInTouchMode) { 10265 hide(); 10266 } 10267 } 10268 10269 @Override 10270 public void onDetached() { 10271 final ViewTreeObserver observer = getViewTreeObserver(); 10272 observer.removeOnTouchModeChangeListener(this); 10273 10274 if (mStartHandle != null) mStartHandle.onDetached(); 10275 if (mEndHandle != null) mEndHandle.onDetached(); 10276 } 10277 } 10278 10279 private void hideInsertionPointCursorController() { 10280 // No need to create the controller to hide it. 10281 if (mInsertionPointCursorController != null) { 10282 mInsertionPointCursorController.hide(); 10283 } 10284 } 10285 10286 /** 10287 * Hides the insertion controller and stops text selection mode, hiding the selection controller 10288 */ 10289 private void hideControllers() { 10290 hideInsertionPointCursorController(); 10291 stopSelectionActionMode(); 10292 hideSuggestions(); 10293 } 10294 10295 /** 10296 * Get the character offset closest to the specified absolute position. A typical use case is to 10297 * pass the result of {@link MotionEvent#getX()} and {@link MotionEvent#getY()} to this method. 10298 * 10299 * @param x The horizontal absolute position of a point on screen 10300 * @param y The vertical absolute position of a point on screen 10301 * @return the character offset for the character whose position is closest to the specified 10302 * position. Returns -1 if there is no layout. 10303 */ 10304 public int getOffsetForPosition(float x, float y) { 10305 if (getLayout() == null) return -1; 10306 final int line = getLineAtCoordinate(y); 10307 final int offset = getOffsetAtCoordinate(line, x); 10308 return offset; 10309 } 10310 10311 private float convertToLocalHorizontalCoordinate(float x) { 10312 x -= getTotalPaddingLeft(); 10313 // Clamp the position to inside of the view. 10314 x = Math.max(0.0f, x); 10315 x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 10316 x += getScrollX(); 10317 return x; 10318 } 10319 10320 private int getLineAtCoordinate(float y) { 10321 y -= getTotalPaddingTop(); 10322 // Clamp the position to inside of the view. 10323 y = Math.max(0.0f, y); 10324 y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 10325 y += getScrollY(); 10326 return getLayout().getLineForVertical((int) y); 10327 } 10328 10329 private int getOffsetAtCoordinate(int line, float x) { 10330 x = convertToLocalHorizontalCoordinate(x); 10331 return getLayout().getOffsetForHorizontal(line, x); 10332 } 10333 10334 /** Returns true if the screen coordinates position (x,y) corresponds to a character displayed 10335 * in the view. Returns false when the position is in the empty space of left/right of text. 10336 */ 10337 private boolean isPositionOnText(float x, float y) { 10338 if (getLayout() == null) return false; 10339 10340 final int line = getLineAtCoordinate(y); 10341 x = convertToLocalHorizontalCoordinate(x); 10342 10343 if (x < getLayout().getLineLeft(line)) return false; 10344 if (x > getLayout().getLineRight(line)) return false; 10345 return true; 10346 } 10347 10348 @Override 10349 public boolean onDragEvent(DragEvent event) { 10350 switch (event.getAction()) { 10351 case DragEvent.ACTION_DRAG_STARTED: 10352 return hasInsertionController(); 10353 10354 case DragEvent.ACTION_DRAG_ENTERED: 10355 TextView.this.requestFocus(); 10356 return true; 10357 10358 case DragEvent.ACTION_DRAG_LOCATION: 10359 final int offset = getOffsetForPosition(event.getX(), event.getY()); 10360 Selection.setSelection((Spannable)mText, offset); 10361 return true; 10362 10363 case DragEvent.ACTION_DROP: 10364 onDrop(event); 10365 return true; 10366 10367 case DragEvent.ACTION_DRAG_ENDED: 10368 case DragEvent.ACTION_DRAG_EXITED: 10369 default: 10370 return true; 10371 } 10372 } 10373 10374 private void onDrop(DragEvent event) { 10375 StringBuilder content = new StringBuilder(""); 10376 ClipData clipData = event.getClipData(); 10377 final int itemCount = clipData.getItemCount(); 10378 for (int i=0; i < itemCount; i++) { 10379 Item item = clipData.getItemAt(i); 10380 content.append(item.coerceToText(TextView.this.mContext)); 10381 } 10382 10383 final int offset = getOffsetForPosition(event.getX(), event.getY()); 10384 10385 Object localState = event.getLocalState(); 10386 DragLocalState dragLocalState = null; 10387 if (localState instanceof DragLocalState) { 10388 dragLocalState = (DragLocalState) localState; 10389 } 10390 boolean dragDropIntoItself = dragLocalState != null && 10391 dragLocalState.sourceTextView == this; 10392 10393 if (dragDropIntoItself) { 10394 if (offset >= dragLocalState.start && offset < dragLocalState.end) { 10395 // A drop inside the original selection discards the drop. 10396 return; 10397 } 10398 } 10399 10400 final int originalLength = mText.length(); 10401 long minMax = prepareSpacesAroundPaste(offset, offset, content); 10402 int min = extractRangeStartFromLong(minMax); 10403 int max = extractRangeEndFromLong(minMax); 10404 10405 Selection.setSelection((Spannable) mText, max); 10406 ((Editable) mText).replace(min, max, content); 10407 10408 if (dragDropIntoItself) { 10409 int dragSourceStart = dragLocalState.start; 10410 int dragSourceEnd = dragLocalState.end; 10411 if (max <= dragSourceStart) { 10412 // Inserting text before selection has shifted positions 10413 final int shift = mText.length() - originalLength; 10414 dragSourceStart += shift; 10415 dragSourceEnd += shift; 10416 } 10417 10418 // Delete original selection 10419 ((Editable) mText).delete(dragSourceStart, dragSourceEnd); 10420 10421 // Make sure we do not leave two adjacent spaces. 10422 if ((dragSourceStart == 0 || 10423 Character.isSpaceChar(mTransformed.charAt(dragSourceStart - 1))) && 10424 (dragSourceStart == mText.length() || 10425 Character.isSpaceChar(mTransformed.charAt(dragSourceStart)))) { 10426 final int pos = dragSourceStart == mText.length() ? 10427 dragSourceStart - 1 : dragSourceStart; 10428 ((Editable) mText).delete(pos, pos + 1); 10429 } 10430 } 10431 } 10432 10433 /** 10434 * @return True if this view supports insertion handles. 10435 */ 10436 boolean hasInsertionController() { 10437 return mInsertionControllerEnabled; 10438 } 10439 10440 /** 10441 * @return True if this view supports selection handles. 10442 */ 10443 boolean hasSelectionController() { 10444 return mSelectionControllerEnabled; 10445 } 10446 10447 InsertionPointCursorController getInsertionController() { 10448 if (!mInsertionControllerEnabled) { 10449 return null; 10450 } 10451 10452 if (mInsertionPointCursorController == null) { 10453 mInsertionPointCursorController = new InsertionPointCursorController(); 10454 10455 final ViewTreeObserver observer = getViewTreeObserver(); 10456 observer.addOnTouchModeChangeListener(mInsertionPointCursorController); 10457 } 10458 10459 return mInsertionPointCursorController; 10460 } 10461 10462 SelectionModifierCursorController getSelectionController() { 10463 if (!mSelectionControllerEnabled) { 10464 return null; 10465 } 10466 10467 if (mSelectionModifierCursorController == null) { 10468 mSelectionModifierCursorController = new SelectionModifierCursorController(); 10469 10470 final ViewTreeObserver observer = getViewTreeObserver(); 10471 observer.addOnTouchModeChangeListener(mSelectionModifierCursorController); 10472 } 10473 10474 return mSelectionModifierCursorController; 10475 } 10476 10477 boolean isInBatchEditMode() { 10478 final InputMethodState ims = mInputMethodState; 10479 if (ims != null) { 10480 return ims.mBatchEditNesting > 0; 10481 } 10482 return mInBatchEditControllers; 10483 } 10484 10485 private class TextViewDirectionHeuristic extends TextDirectionHeuristicImpl { 10486 private TextViewDirectionHeuristic(TextDirectionAlgorithm algorithm) { 10487 super(algorithm); 10488 } 10489 @Override 10490 protected boolean defaultIsRtl() { 10491 return getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL; 10492 } 10493 } 10494 10495 /** 10496 * Resolve the text direction. 10497 * 10498 * Text direction of paragraphs in a TextView is determined using a heuristic. If the correct 10499 * text direction cannot be determined by the heuristic, the view's resolved layout direction 10500 * determines the direction. 10501 * 10502 * This heuristic and result is applied individually to each paragraph in a TextView, based on 10503 * the text and style content of that paragraph. Paragraph text styles can also be used to force 10504 * a particular direction. 10505 */ 10506 @Override 10507 protected void resolveTextDirection() { 10508 super.resolveTextDirection(); 10509 10510 int textDir = getResolvedTextDirection(); 10511 switch (textDir) { 10512 default: 10513 case TEXT_DIRECTION_FIRST_STRONG: 10514 mTextDir = new TextViewDirectionHeuristic(FirstStrong.INSTANCE); 10515 break; 10516 case TEXT_DIRECTION_ANY_RTL: 10517 mTextDir = new TextViewDirectionHeuristic(AnyStrong.INSTANCE_RTL); 10518 break; 10519 case TEXT_DIRECTION_CHAR_COUNT: 10520 mTextDir = new TextViewDirectionHeuristic(CharCount.INSTANCE_DEFAULT); 10521 break; 10522 case TEXT_DIRECTION_LTR: 10523 mTextDir = TextDirectionHeuristics.LTR; 10524 break; 10525 case TEXT_DIRECTION_RTL: 10526 mTextDir = TextDirectionHeuristics.RTL; 10527 break; 10528 } 10529 } 10530 10531 /** 10532 * Subclasses will need to override this method to implement their own way of resolving 10533 * drawables depending on the layout direction. 10534 * 10535 * A call to the super method will be required from the subclasses implementation. 10536 * 10537 */ 10538 protected void resolveDrawables() { 10539 // No need to resolve twice 10540 if (mResolvedDrawables) { 10541 return; 10542 } 10543 // No drawable to resolve 10544 if (mDrawables == null) { 10545 return; 10546 } 10547 // No relative drawable to resolve 10548 if (mDrawables.mDrawableStart == null && mDrawables.mDrawableEnd == null) { 10549 mResolvedDrawables = true; 10550 return; 10551 } 10552 10553 Drawables dr = mDrawables; 10554 switch(getResolvedLayoutDirection()) { 10555 case LAYOUT_DIRECTION_RTL: 10556 if (dr.mDrawableStart != null) { 10557 dr.mDrawableRight = dr.mDrawableStart; 10558 10559 dr.mDrawableSizeRight = dr.mDrawableSizeStart; 10560 dr.mDrawableHeightRight = dr.mDrawableHeightStart; 10561 } 10562 if (dr.mDrawableEnd != null) { 10563 dr.mDrawableLeft = dr.mDrawableEnd; 10564 10565 dr.mDrawableSizeLeft = dr.mDrawableSizeEnd; 10566 dr.mDrawableHeightLeft = dr.mDrawableHeightEnd; 10567 } 10568 break; 10569 10570 case LAYOUT_DIRECTION_LTR: 10571 default: 10572 if (dr.mDrawableStart != null) { 10573 dr.mDrawableLeft = dr.mDrawableStart; 10574 10575 dr.mDrawableSizeLeft = dr.mDrawableSizeStart; 10576 dr.mDrawableHeightLeft = dr.mDrawableHeightStart; 10577 } 10578 if (dr.mDrawableEnd != null) { 10579 dr.mDrawableRight = dr.mDrawableEnd; 10580 10581 dr.mDrawableSizeRight = dr.mDrawableSizeEnd; 10582 dr.mDrawableHeightRight = dr.mDrawableHeightEnd; 10583 } 10584 break; 10585 } 10586 mResolvedDrawables = true; 10587 } 10588 10589 protected void resetResolvedDrawables() { 10590 mResolvedDrawables = false; 10591 } 10592 10593 @ViewDebug.ExportedProperty(category = "text") 10594 private CharSequence mText; 10595 private CharSequence mTransformed; 10596 private BufferType mBufferType = BufferType.NORMAL; 10597 10598 private int mInputType = EditorInfo.TYPE_NULL; 10599 private CharSequence mHint; 10600 private Layout mHintLayout; 10601 10602 private KeyListener mInput; 10603 10604 private MovementMethod mMovement; 10605 private TransformationMethod mTransformation; 10606 private boolean mAllowTransformationLengthChange; 10607 private ChangeWatcher mChangeWatcher; 10608 10609 private ArrayList<TextWatcher> mListeners = null; 10610 10611 // display attributes 10612 private final TextPaint mTextPaint; 10613 private boolean mUserSetTextScaleX; 10614 private final Paint mHighlightPaint; 10615 private int mHighlightColor = 0xCC475925; 10616 /** 10617 * This is temporarily visible to fix bug 3085564 in webView. Do not rely on 10618 * this field being protected. Will be restored as private when lineHeight 10619 * feature request 3215097 is implemented 10620 * @hide 10621 */ 10622 protected Layout mLayout; 10623 10624 private long mShowCursor; 10625 private Blink mBlink; 10626 private boolean mCursorVisible = true; 10627 10628 // Cursor Controllers. 10629 private InsertionPointCursorController mInsertionPointCursorController; 10630 private SelectionModifierCursorController mSelectionModifierCursorController; 10631 private ActionMode mSelectionActionMode; 10632 private boolean mInsertionControllerEnabled; 10633 private boolean mSelectionControllerEnabled; 10634 private boolean mInBatchEditControllers; 10635 10636 // These are needed to desambiguate a long click. If the long click comes from ones of these, we 10637 // select from the current cursor position. Otherwise, select from long pressed position. 10638 private boolean mDPadCenterIsDown = false; 10639 private boolean mEnterKeyIsDown = false; 10640 private boolean mContextMenuTriggeredByKey = false; 10641 // Created once and shared by different CursorController helper methods. 10642 // Only one cursor controller is active at any time which prevent race conditions. 10643 private static Rect sCursorControllerTempRect = new Rect(); 10644 10645 private boolean mSelectAllOnFocus = false; 10646 10647 private int mGravity = Gravity.TOP | Gravity.START; 10648 private boolean mHorizontallyScrolling; 10649 10650 private int mAutoLinkMask; 10651 private boolean mLinksClickable = true; 10652 10653 private float mSpacingMult = 1; 10654 private float mSpacingAdd = 0; 10655 private boolean mTextIsSelectable = false; 10656 10657 private static final int LINES = 1; 10658 private static final int EMS = LINES; 10659 private static final int PIXELS = 2; 10660 10661 private int mMaximum = Integer.MAX_VALUE; 10662 private int mMaxMode = LINES; 10663 private int mMinimum = 0; 10664 private int mMinMode = LINES; 10665 10666 private int mMaxWidth = Integer.MAX_VALUE; 10667 private int mMaxWidthMode = PIXELS; 10668 private int mMinWidth = 0; 10669 private int mMinWidthMode = PIXELS; 10670 10671 private boolean mSingleLine; 10672 private int mDesiredHeightAtMeasure = -1; 10673 private boolean mIncludePad = true; 10674 10675 // tmp primitives, so we don't alloc them on each draw 10676 private Path mHighlightPath; 10677 private boolean mHighlightPathBogus = true; 10678 private static final RectF sTempRect = new RectF(); 10679 10680 // XXX should be much larger 10681 private static final int VERY_WIDE = 16384; 10682 10683 private static final int BLINK = 500; 10684 10685 private static final int ANIMATED_SCROLL_GAP = 250; 10686 private long mLastScroll; 10687 private Scroller mScroller = null; 10688 10689 private BoringLayout.Metrics mBoring; 10690 private BoringLayout.Metrics mHintBoring; 10691 10692 private BoringLayout mSavedLayout, mSavedHintLayout; 10693 10694 private TextDirectionHeuristic mTextDir = null; 10695 10696 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 10697 private InputFilter[] mFilters = NO_FILTERS; 10698 private static final Spanned EMPTY_SPANNED = new SpannedString(""); 10699 private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20; 10700 // System wide time for last cut or copy action. 10701 private static long sLastCutOrCopyTime; 10702 // Used to highlight a word when it is corrected by the IME 10703 private CorrectionHighlighter mCorrectionHighlighter; 10704 // New state used to change background based on whether this TextView is multiline. 10705 private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline }; 10706} 10707