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