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