This repository has been archived by the owner on Nov 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
TextView.java
13705 lines (12239 loc) · 527 KB
/
TextView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.widget;
import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_RENDERING_INFO_KEY;
import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_LENGTH;
import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_ARG_START_INDEX;
import static android.view.accessibility.AccessibilityNodeInfo.EXTRA_DATA_TEXT_CHARACTER_LOCATION_KEY;
import static android.view.inputmethod.CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION;
import android.R;
import android.annotation.CallSuper;
import android.annotation.CheckResult;
import android.annotation.ColorInt;
import android.annotation.DrawableRes;
import android.annotation.FloatRange;
import android.annotation.IntDef;
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.Px;
import android.annotation.RequiresPermission;
import android.annotation.Size;
import android.annotation.StringRes;
import android.annotation.StyleRes;
import android.annotation.XmlRes;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.assist.AssistStructure;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.UndoManager;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.CompatibilityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.graphics.BaseCanvas;
import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Insets;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.fonts.FontStyle;
import android.graphics.fonts.FontVariationAxis;
import android.icu.text.DecimalFormatSymbols;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.LocaleList;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.ParcelableParcel;
import android.os.Process;
import android.os.SystemClock;
import android.os.UserHandle;
import android.provider.Settings;
import android.text.BoringLayout;
import android.text.DynamicLayout;
import android.text.Editable;
import android.text.GetChars;
import android.text.GraphicsOperations;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Layout;
import android.text.ParcelableSpan;
import android.text.PrecomputedText;
import android.text.Selection;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.StaticLayout;
import android.text.TextDirectionHeuristic;
import android.text.TextDirectionHeuristics;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.TextWatcher;
import android.text.method.AllCapsTransformationMethod;
import android.text.method.ArrowKeyMovementMethod;
import android.text.method.DateKeyListener;
import android.text.method.DateTimeKeyListener;
import android.text.method.DialerKeyListener;
import android.text.method.DigitsKeyListener;
import android.text.method.KeyListener;
import android.text.method.LinkMovementMethod;
import android.text.method.MetaKeyKeyListener;
import android.text.method.MovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.text.method.TextKeyListener;
import android.text.method.TimeKeyListener;
import android.text.method.TransformationMethod;
import android.text.method.TransformationMethod2;
import android.text.method.WordIterator;
import android.text.style.CharacterStyle;
import android.text.style.ClickableSpan;
import android.text.style.ParagraphStyle;
import android.text.style.SpellCheckSpan;
import android.text.style.SuggestionSpan;
import android.text.style.URLSpan;
import android.text.style.UpdateAppearance;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.IntArray;
import android.util.Log;
import android.util.SparseIntArray;
import android.util.TypedValue;
import android.view.AccessibilityIterators.TextSegmentIterator;
import android.view.ActionMode;
import android.view.Choreographer;
import android.view.ContextMenu;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.PointerIcon;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewDebug;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewHierarchyEncoder;
import android.view.ViewParent;
import android.view.ViewRootImpl;
import android.view.ViewStructure;
import android.view.ViewTreeObserver;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.animation.AnimationUtils;
import android.view.autofill.AutofillManager;
import android.view.autofill.AutofillValue;
import android.view.contentcapture.ContentCaptureManager;
import android.view.contentcapture.ContentCaptureSession;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.CorrectionInfo;
import android.view.inputmethod.CursorAnchorInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.view.inspector.InspectableProperty;
import android.view.inspector.InspectableProperty.EnumEntry;
import android.view.inspector.InspectableProperty.FlagEntry;
import android.view.textclassifier.TextClassification;
import android.view.textclassifier.TextClassificationContext;
import android.view.textclassifier.TextClassificationManager;
import android.view.textclassifier.TextClassifier;
import android.view.textclassifier.TextLinks;
import android.view.textservice.SpellCheckerSubtype;
import android.view.textservice.TextServicesManager;
import android.widget.RemoteViews.RemoteView;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.util.FastMath;
import com.android.internal.util.Preconditions;
import com.android.internal.widget.EditableInputConnection;
import libcore.util.EmptyArray;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* A user interface element that displays text to the user.
* To provide user-editable text, see {@link EditText}.
* <p>
* The following code sample shows a typical use, with an XML layout
* and code to modify the contents of the text view:
* </p>
* <pre>
* <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
* <TextView
* android:id="@+id/text_view_id"
* android:layout_height="wrap_content"
* android:layout_width="wrap_content"
* android:text="@string/hello" />
* </LinearLayout>
* </pre>
* <p>
* This code sample demonstrates how to modify the contents of the text view
* defined in the previous XML layout:
* </p>
* <pre>
* public class MainActivity extends Activity {
*
* protected void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* setContentView(R.layout.activity_main);
* final TextView helloTextView = (TextView) findViewById(R.id.text_view_id);
* helloTextView.setText(R.string.user_greeting);
* }
* }
* </pre>
* <p>
* To customize the appearance of TextView, see <a href="https://developer.android.com/guide/topics/ui/themes.html">Styles and Themes</a>.
* </p>
* <p>
* <b>XML attributes</b>
* <p>
* See {@link android.R.styleable#TextView TextView Attributes},
* {@link android.R.styleable#View View Attributes}
*
* @attr ref android.R.styleable#TextView_text
* @attr ref android.R.styleable#TextView_bufferType
* @attr ref android.R.styleable#TextView_hint
* @attr ref android.R.styleable#TextView_textColor
* @attr ref android.R.styleable#TextView_textColorHighlight
* @attr ref android.R.styleable#TextView_textColorHint
* @attr ref android.R.styleable#TextView_textAppearance
* @attr ref android.R.styleable#TextView_textColorLink
* @attr ref android.R.styleable#TextView_textFontWeight
* @attr ref android.R.styleable#TextView_textSize
* @attr ref android.R.styleable#TextView_textScaleX
* @attr ref android.R.styleable#TextView_fontFamily
* @attr ref android.R.styleable#TextView_typeface
* @attr ref android.R.styleable#TextView_textStyle
* @attr ref android.R.styleable#TextView_cursorVisible
* @attr ref android.R.styleable#TextView_maxLines
* @attr ref android.R.styleable#TextView_maxHeight
* @attr ref android.R.styleable#TextView_lines
* @attr ref android.R.styleable#TextView_height
* @attr ref android.R.styleable#TextView_minLines
* @attr ref android.R.styleable#TextView_minHeight
* @attr ref android.R.styleable#TextView_maxEms
* @attr ref android.R.styleable#TextView_maxWidth
* @attr ref android.R.styleable#TextView_ems
* @attr ref android.R.styleable#TextView_width
* @attr ref android.R.styleable#TextView_minEms
* @attr ref android.R.styleable#TextView_minWidth
* @attr ref android.R.styleable#TextView_gravity
* @attr ref android.R.styleable#TextView_scrollHorizontally
* @attr ref android.R.styleable#TextView_password
* @attr ref android.R.styleable#TextView_singleLine
* @attr ref android.R.styleable#TextView_selectAllOnFocus
* @attr ref android.R.styleable#TextView_includeFontPadding
* @attr ref android.R.styleable#TextView_maxLength
* @attr ref android.R.styleable#TextView_shadowColor
* @attr ref android.R.styleable#TextView_shadowDx
* @attr ref android.R.styleable#TextView_shadowDy
* @attr ref android.R.styleable#TextView_shadowRadius
* @attr ref android.R.styleable#TextView_autoLink
* @attr ref android.R.styleable#TextView_linksClickable
* @attr ref android.R.styleable#TextView_numeric
* @attr ref android.R.styleable#TextView_digits
* @attr ref android.R.styleable#TextView_phoneNumber
* @attr ref android.R.styleable#TextView_inputMethod
* @attr ref android.R.styleable#TextView_capitalize
* @attr ref android.R.styleable#TextView_autoText
* @attr ref android.R.styleable#TextView_editable
* @attr ref android.R.styleable#TextView_freezesText
* @attr ref android.R.styleable#TextView_ellipsize
* @attr ref android.R.styleable#TextView_drawableTop
* @attr ref android.R.styleable#TextView_drawableBottom
* @attr ref android.R.styleable#TextView_drawableRight
* @attr ref android.R.styleable#TextView_drawableLeft
* @attr ref android.R.styleable#TextView_drawableStart
* @attr ref android.R.styleable#TextView_drawableEnd
* @attr ref android.R.styleable#TextView_drawablePadding
* @attr ref android.R.styleable#TextView_drawableTint
* @attr ref android.R.styleable#TextView_drawableTintMode
* @attr ref android.R.styleable#TextView_lineSpacingExtra
* @attr ref android.R.styleable#TextView_lineSpacingMultiplier
* @attr ref android.R.styleable#TextView_justificationMode
* @attr ref android.R.styleable#TextView_marqueeRepeatLimit
* @attr ref android.R.styleable#TextView_inputType
* @attr ref android.R.styleable#TextView_imeOptions
* @attr ref android.R.styleable#TextView_privateImeOptions
* @attr ref android.R.styleable#TextView_imeActionLabel
* @attr ref android.R.styleable#TextView_imeActionId
* @attr ref android.R.styleable#TextView_editorExtras
* @attr ref android.R.styleable#TextView_elegantTextHeight
* @attr ref android.R.styleable#TextView_fallbackLineSpacing
* @attr ref android.R.styleable#TextView_letterSpacing
* @attr ref android.R.styleable#TextView_fontFeatureSettings
* @attr ref android.R.styleable#TextView_fontVariationSettings
* @attr ref android.R.styleable#TextView_breakStrategy
* @attr ref android.R.styleable#TextView_hyphenationFrequency
* @attr ref android.R.styleable#TextView_autoSizeTextType
* @attr ref android.R.styleable#TextView_autoSizeMinTextSize
* @attr ref android.R.styleable#TextView_autoSizeMaxTextSize
* @attr ref android.R.styleable#TextView_autoSizeStepGranularity
* @attr ref android.R.styleable#TextView_autoSizePresetSizes
* @attr ref android.R.styleable#TextView_textCursorDrawable
* @attr ref android.R.styleable#TextView_textSelectHandle
* @attr ref android.R.styleable#TextView_textSelectHandleLeft
* @attr ref android.R.styleable#TextView_textSelectHandleRight
* @attr ref android.R.styleable#TextView_allowUndo
* @attr ref android.R.styleable#TextView_enabled
*/
@RemoteView
public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {
static final String LOG_TAG = "TextView";
static final boolean DEBUG_EXTRACT = false;
static final boolean DEBUG_CURSOR = false;
private static final float[] TEMP_POSITION = new float[2];
// Enum for the "typeface" XML parameter.
// TODO: How can we get this from the XML instead of hardcoding it here?
/** @hide */
@IntDef(value = {DEFAULT_TYPEFACE, SANS, SERIF, MONOSPACE})
@Retention(RetentionPolicy.SOURCE)
public @interface XMLTypefaceAttr{}
private static final int DEFAULT_TYPEFACE = -1;
private static final int SANS = 1;
private static final int SERIF = 2;
private static final int MONOSPACE = 3;
// Enum for the "ellipsize" XML parameter.
private static final int ELLIPSIZE_NOT_SET = -1;
private static final int ELLIPSIZE_NONE = 0;
private static final int ELLIPSIZE_START = 1;
private static final int ELLIPSIZE_MIDDLE = 2;
private static final int ELLIPSIZE_END = 3;
private static final int ELLIPSIZE_MARQUEE = 4;
// Bitfield for the "numeric" XML parameter.
// TODO: How can we get this from the XML instead of hardcoding it here?
private static final int SIGNED = 2;
private static final int DECIMAL = 4;
/**
* Draw marquee text with fading edges as usual
*/
private static final int MARQUEE_FADE_NORMAL = 0;
/**
* Draw marquee text as ellipsize end while inactive instead of with the fade.
* (Useful for devices where the fade can be expensive if overdone)
*/
private static final int MARQUEE_FADE_SWITCH_SHOW_ELLIPSIS = 1;
/**
* Draw marquee text with fading edges because it is currently active/animating.
*/
private static final int MARQUEE_FADE_SWITCH_SHOW_FADE = 2;
@UnsupportedAppUsage
private static final int LINES = 1;
private static final int EMS = LINES;
private static final int PIXELS = 2;
// Maximum text length for single line input.
private static final int MAX_LENGTH_FOR_SINGLE_LINE_EDIT_TEXT = 5000;
private InputFilter.LengthFilter mSingleLineLengthFilter = null;
private static final RectF TEMP_RECTF = new RectF();
/** @hide */
static final int VERY_WIDE = 1024 * 1024; // XXX should be much larger
private static final int ANIMATED_SCROLL_GAP = 250;
private static final InputFilter[] NO_FILTERS = new InputFilter[0];
private static final Spanned EMPTY_SPANNED = new SpannedString("");
private static final int CHANGE_WATCHER_PRIORITY = 100;
// New state used to change background based on whether this TextView is multiline.
private static final int[] MULTILINE_STATE_SET = { R.attr.state_multiline };
// Accessibility action to share selected text.
private static final int ACCESSIBILITY_ACTION_SHARE = 0x10000000;
/**
* @hide
*/
// Accessibility action start id for "process text" actions.
static final int ACCESSIBILITY_ACTION_PROCESS_TEXT_START_ID = 0x10000100;
/**
* @hide
*/
static final int PROCESS_TEXT_REQUEST_CODE = 100;
/**
* Return code of {@link #doKeyDown}.
*/
private static final int KEY_EVENT_NOT_HANDLED = 0;
private static final int KEY_EVENT_HANDLED = -1;
private static final int KEY_DOWN_HANDLED_BY_KEY_LISTENER = 1;
private static final int KEY_DOWN_HANDLED_BY_MOVEMENT_METHOD = 2;
private static final int FLOATING_TOOLBAR_SELECT_ALL_REFRESH_DELAY = 500;
// System wide time for last cut, copy or text changed action.
static long sLastCutCopyOrTextChangedTime;
private ColorStateList mTextColor;
private ColorStateList mHintTextColor;
private ColorStateList mLinkTextColor;
@ViewDebug.ExportedProperty(category = "text")
/**
* {@link #setTextColor(int)} or {@link #getCurrentTextColor()} should be used instead.
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private int mCurTextColor;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
private int mCurHintTextColor;
private boolean mFreezesText;
@UnsupportedAppUsage
private Editable.Factory mEditableFactory = Editable.Factory.getInstance();
@UnsupportedAppUsage
private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance();
@UnsupportedAppUsage
private float mShadowRadius;
@UnsupportedAppUsage
private float mShadowDx;
@UnsupportedAppUsage
private float mShadowDy;
private int mShadowColor;
private boolean mPreDrawRegistered;
private boolean mPreDrawListenerDetached;
private TextClassifier mTextClassifier;
private TextClassifier mTextClassificationSession;
private TextClassificationContext mTextClassificationContext;
// A flag to prevent repeated movements from escaping the enclosing text view. The idea here is
// that if a user is holding down a movement key to traverse text, we shouldn't also traverse
// the view hierarchy. On the other hand, if the user is using the movement key to traverse
// views (i.e. the first movement was to traverse out of this view, or this view was traversed
// into by the user holding the movement key down) then we shouldn't prevent the focus from
// changing.
private boolean mPreventDefaultMovement;
private TextUtils.TruncateAt mEllipsize;
static class Drawables {
static final int LEFT = 0;
static final int TOP = 1;
static final int RIGHT = 2;
static final int BOTTOM = 3;
static final int DRAWABLE_NONE = -1;
static final int DRAWABLE_RIGHT = 0;
static final int DRAWABLE_LEFT = 1;
final Rect mCompoundRect = new Rect();
final Drawable[] mShowing = new Drawable[4];
ColorStateList mTintList;
BlendMode mBlendMode;
boolean mHasTint;
boolean mHasTintMode;
Drawable mDrawableStart, mDrawableEnd, mDrawableError, mDrawableTemp;
Drawable mDrawableLeftInitial, mDrawableRightInitial;
boolean mIsRtlCompatibilityMode;
boolean mOverride;
int mDrawableSizeTop, mDrawableSizeBottom, mDrawableSizeLeft, mDrawableSizeRight,
mDrawableSizeStart, mDrawableSizeEnd, mDrawableSizeError, mDrawableSizeTemp;
int mDrawableWidthTop, mDrawableWidthBottom, mDrawableHeightLeft, mDrawableHeightRight,
mDrawableHeightStart, mDrawableHeightEnd, mDrawableHeightError, mDrawableHeightTemp;
int mDrawablePadding;
int mDrawableSaved = DRAWABLE_NONE;
public Drawables(Context context) {
final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;
mIsRtlCompatibilityMode = targetSdkVersion < VERSION_CODES.JELLY_BEAN_MR1
|| !context.getApplicationInfo().hasRtlSupport();
mOverride = false;
}
/**
* @return {@code true} if this object contains metadata that needs to
* be retained, {@code false} otherwise
*/
public boolean hasMetadata() {
return mDrawablePadding != 0 || mHasTintMode || mHasTint;
}
/**
* Updates the list of displayed drawables to account for the current
* layout direction.
*
* @param layoutDirection the current layout direction
* @return {@code true} if the displayed drawables changed
*/
public boolean resolveWithLayoutDirection(int layoutDirection) {
final Drawable previousLeft = mShowing[Drawables.LEFT];
final Drawable previousRight = mShowing[Drawables.RIGHT];
// First reset "left" and "right" drawables to their initial values
mShowing[Drawables.LEFT] = mDrawableLeftInitial;
mShowing[Drawables.RIGHT] = mDrawableRightInitial;
if (mIsRtlCompatibilityMode) {
// Use "start" drawable as "left" drawable if the "left" drawable was not defined
if (mDrawableStart != null && mShowing[Drawables.LEFT] == null) {
mShowing[Drawables.LEFT] = mDrawableStart;
mDrawableSizeLeft = mDrawableSizeStart;
mDrawableHeightLeft = mDrawableHeightStart;
}
// Use "end" drawable as "right" drawable if the "right" drawable was not defined
if (mDrawableEnd != null && mShowing[Drawables.RIGHT] == null) {
mShowing[Drawables.RIGHT] = mDrawableEnd;
mDrawableSizeRight = mDrawableSizeEnd;
mDrawableHeightRight = mDrawableHeightEnd;
}
} else {
// JB-MR1+ normal case: "start" / "end" drawables are overriding "left" / "right"
// drawable if and only if they have been defined
switch(layoutDirection) {
case LAYOUT_DIRECTION_RTL:
if (mOverride) {
mShowing[Drawables.RIGHT] = mDrawableStart;
mDrawableSizeRight = mDrawableSizeStart;
mDrawableHeightRight = mDrawableHeightStart;
mShowing[Drawables.LEFT] = mDrawableEnd;
mDrawableSizeLeft = mDrawableSizeEnd;
mDrawableHeightLeft = mDrawableHeightEnd;
}
break;
case LAYOUT_DIRECTION_LTR:
default:
if (mOverride) {
mShowing[Drawables.LEFT] = mDrawableStart;
mDrawableSizeLeft = mDrawableSizeStart;
mDrawableHeightLeft = mDrawableHeightStart;
mShowing[Drawables.RIGHT] = mDrawableEnd;
mDrawableSizeRight = mDrawableSizeEnd;
mDrawableHeightRight = mDrawableHeightEnd;
}
break;
}
}
applyErrorDrawableIfNeeded(layoutDirection);
return mShowing[Drawables.LEFT] != previousLeft
|| mShowing[Drawables.RIGHT] != previousRight;
}
public void setErrorDrawable(Drawable dr, TextView tv) {
if (mDrawableError != dr && mDrawableError != null) {
mDrawableError.setCallback(null);
}
mDrawableError = dr;
if (mDrawableError != null) {
final Rect compoundRect = mCompoundRect;
final int[] state = tv.getDrawableState();
mDrawableError.setState(state);
mDrawableError.copyBounds(compoundRect);
mDrawableError.setCallback(tv);
mDrawableSizeError = compoundRect.width();
mDrawableHeightError = compoundRect.height();
} else {
mDrawableSizeError = mDrawableHeightError = 0;
}
}
private void applyErrorDrawableIfNeeded(int layoutDirection) {
// first restore the initial state if needed
switch (mDrawableSaved) {
case DRAWABLE_LEFT:
mShowing[Drawables.LEFT] = mDrawableTemp;
mDrawableSizeLeft = mDrawableSizeTemp;
mDrawableHeightLeft = mDrawableHeightTemp;
break;
case DRAWABLE_RIGHT:
mShowing[Drawables.RIGHT] = mDrawableTemp;
mDrawableSizeRight = mDrawableSizeTemp;
mDrawableHeightRight = mDrawableHeightTemp;
break;
case DRAWABLE_NONE:
default:
}
// then, if needed, assign the Error drawable to the correct location
if (mDrawableError != null) {
switch(layoutDirection) {
case LAYOUT_DIRECTION_RTL:
mDrawableSaved = DRAWABLE_LEFT;
mDrawableTemp = mShowing[Drawables.LEFT];
mDrawableSizeTemp = mDrawableSizeLeft;
mDrawableHeightTemp = mDrawableHeightLeft;
mShowing[Drawables.LEFT] = mDrawableError;
mDrawableSizeLeft = mDrawableSizeError;
mDrawableHeightLeft = mDrawableHeightError;
break;
case LAYOUT_DIRECTION_LTR:
default:
mDrawableSaved = DRAWABLE_RIGHT;
mDrawableTemp = mShowing[Drawables.RIGHT];
mDrawableSizeTemp = mDrawableSizeRight;
mDrawableHeightTemp = mDrawableHeightRight;
mShowing[Drawables.RIGHT] = mDrawableError;
mDrawableSizeRight = mDrawableSizeError;
mDrawableHeightRight = mDrawableHeightError;
break;
}
}
}
}
@UnsupportedAppUsage
Drawables mDrawables;
@UnsupportedAppUsage
private CharWrapper mCharWrapper;
@UnsupportedAppUsage(trackingBug = 124050217)
private Marquee mMarquee;
@UnsupportedAppUsage
private boolean mRestartMarquee;
private int mMarqueeRepeatLimit = 3;
private int mLastLayoutDirection = -1;
/**
* On some devices the fading edges add a performance penalty if used
* extensively in the same layout. This mode indicates how the marquee
* is currently being shown, if applicable. (mEllipsize will == MARQUEE)
*/
@UnsupportedAppUsage
private int mMarqueeFadeMode = MARQUEE_FADE_NORMAL;
/**
* When mMarqueeFadeMode is not MARQUEE_FADE_NORMAL, this stores
* the layout that should be used when the mode switches.
*/
@UnsupportedAppUsage
private Layout mSavedMarqueeModeLayout;
// Do not update following mText/mSpannable/mPrecomputed except for setTextInternal()
@ViewDebug.ExportedProperty(category = "text")
@UnsupportedAppUsage
private @Nullable CharSequence mText;
private @Nullable Spannable mSpannable;
private @Nullable PrecomputedText mPrecomputed;
@UnsupportedAppUsage
private CharSequence mTransformed;
@UnsupportedAppUsage
private BufferType mBufferType = BufferType.NORMAL;
private CharSequence mHint;
@UnsupportedAppUsage
private Layout mHintLayout;
private MovementMethod mMovement;
private TransformationMethod mTransformation;
@UnsupportedAppUsage
private boolean mAllowTransformationLengthChange;
@UnsupportedAppUsage
private ChangeWatcher mChangeWatcher;
@UnsupportedAppUsage(trackingBug = 123769451)
private ArrayList<TextWatcher> mListeners;
// display attributes
@UnsupportedAppUsage
private final TextPaint mTextPaint;
@UnsupportedAppUsage
private boolean mUserSetTextScaleX;
@UnsupportedAppUsage
private Layout mLayout;
private boolean mLocalesChanged = false;
private int mTextSizeUnit = -1;
// True if setKeyListener() has been explicitly called
private boolean mListenerChanged = false;
// True if internationalized input should be used for numbers and date and time.
private final boolean mUseInternationalizedInput;
// True if fallback fonts that end up getting used should be allowed to affect line spacing.
/* package */ boolean mUseFallbackLineSpacing;
@ViewDebug.ExportedProperty(category = "text")
@UnsupportedAppUsage
private int mGravity = Gravity.TOP | Gravity.START;
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
private boolean mHorizontallyScrolling;
private int mAutoLinkMask;
private boolean mLinksClickable = true;
@UnsupportedAppUsage
private float mSpacingMult = 1.0f;
@UnsupportedAppUsage
private float mSpacingAdd = 0.0f;
private int mBreakStrategy;
private int mHyphenationFrequency;
private int mJustificationMode;
@UnsupportedAppUsage
private int mMaximum = Integer.MAX_VALUE;
@UnsupportedAppUsage
private int mMaxMode = LINES;
@UnsupportedAppUsage
private int mMinimum = 0;
@UnsupportedAppUsage
private int mMinMode = LINES;
@UnsupportedAppUsage
private int mOldMaximum = mMaximum;
@UnsupportedAppUsage
private int mOldMaxMode = mMaxMode;
@UnsupportedAppUsage
private int mMaxWidth = Integer.MAX_VALUE;
@UnsupportedAppUsage
private int mMaxWidthMode = PIXELS;
@UnsupportedAppUsage
private int mMinWidth = 0;
@UnsupportedAppUsage
private int mMinWidthMode = PIXELS;
@UnsupportedAppUsage
private boolean mSingleLine;
@UnsupportedAppUsage
private int mDesiredHeightAtMeasure = -1;
@UnsupportedAppUsage
private boolean mIncludePad = true;
private int mDeferScroll = -1;
// tmp primitives, so we don't alloc them on each draw
private Rect mTempRect;
private long mLastScroll;
private Scroller mScroller;
private TextPaint mTempTextPaint;
@UnsupportedAppUsage
private BoringLayout.Metrics mBoring;
@UnsupportedAppUsage
private BoringLayout.Metrics mHintBoring;
@UnsupportedAppUsage
private BoringLayout mSavedLayout;
@UnsupportedAppUsage
private BoringLayout mSavedHintLayout;
@UnsupportedAppUsage
private TextDirectionHeuristic mTextDir;
private InputFilter[] mFilters = NO_FILTERS;
/**
* {@link UserHandle} that represents the logical owner of the text. {@code null} when it is
* the same as {@link Process#myUserHandle()}.
*
* <p>Most of applications should not worry about this. Some privileged apps that host UI for
* other apps may need to set this so that the system can use right user's resources and
* services such as input methods and spell checkers.</p>
*
* @see #setTextOperationUser(UserHandle)
*/
@Nullable
private UserHandle mTextOperationUser;
private volatile Locale mCurrentSpellCheckerLocaleCache;
// It is possible to have a selection even when mEditor is null (programmatically set, like when
// a link is pressed). These highlight-related fields do not go in mEditor.
@UnsupportedAppUsage
int mHighlightColor = 0x6633B5E5;
private Path mHighlightPath;
@UnsupportedAppUsage
private final Paint mHighlightPaint;
@UnsupportedAppUsage
private boolean mHighlightPathBogus = true;
// Although these fields are specific to editable text, they are not added to Editor because
// they are defined by the TextView's style and are theme-dependent.
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
int mCursorDrawableRes;
private Drawable mCursorDrawable;
// Note: this might be stale if setTextSelectHandleLeft is used. We could simplify the code
// by removing it, but we would break apps targeting <= P that use it by reflection.
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
int mTextSelectHandleLeftRes;
private Drawable mTextSelectHandleLeft;
// Note: this might be stale if setTextSelectHandleRight is used. We could simplify the code
// by removing it, but we would break apps targeting <= P that use it by reflection.
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
int mTextSelectHandleRightRes;
private Drawable mTextSelectHandleRight;
// Note: this might be stale if setTextSelectHandle is used. We could simplify the code
// by removing it, but we would break apps targeting <= P that use it by reflection.
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
int mTextSelectHandleRes;
private Drawable mTextSelectHandle;
int mTextEditSuggestionItemLayout;
int mTextEditSuggestionContainerLayout;
int mTextEditSuggestionHighlightStyle;
private static final int NO_POINTER_ID = -1;
/**
* The prime (the 1st finger) pointer id which is used as a lock to prevent multi touch among
* TextView and the handle views which are rendered on popup windows.
*/
private int mPrimePointerId = NO_POINTER_ID;
/**
* Whether the prime pointer is from the event delivered to selection handle or insertion
* handle.
*/
private boolean mIsPrimePointerFromHandleView;
/**
* {@link EditText} specific data, created on demand when one of the Editor fields is used.
* See {@link #createEditorIfNeeded()}.
*/
@UnsupportedAppUsage
private Editor mEditor;
private static final int DEVICE_PROVISIONED_UNKNOWN = 0;
private static final int DEVICE_PROVISIONED_NO = 1;
private static final int DEVICE_PROVISIONED_YES = 2;
/**
* Some special options such as sharing selected text should only be shown if the device
* is provisioned. Only check the provisioned state once for a given view instance.
*/
private int mDeviceProvisionedState = DEVICE_PROVISIONED_UNKNOWN;
/**
* The TextView does not auto-size text (default).
*/
public static final int AUTO_SIZE_TEXT_TYPE_NONE = 0;
/**
* The TextView scales text size both horizontally and vertically to fit within the
* container.
*/
public static final int AUTO_SIZE_TEXT_TYPE_UNIFORM = 1;
/** @hide */
@IntDef(prefix = { "AUTO_SIZE_TEXT_TYPE_" }, value = {
AUTO_SIZE_TEXT_TYPE_NONE,
AUTO_SIZE_TEXT_TYPE_UNIFORM
})
@Retention(RetentionPolicy.SOURCE)
public @interface AutoSizeTextType {}
// Default minimum size for auto-sizing text in scaled pixels.
private static final int DEFAULT_AUTO_SIZE_MIN_TEXT_SIZE_IN_SP = 12;
// Default maximum size for auto-sizing text in scaled pixels.
private static final int DEFAULT_AUTO_SIZE_MAX_TEXT_SIZE_IN_SP = 112;
// Default value for the step size in pixels.
private static final int DEFAULT_AUTO_SIZE_GRANULARITY_IN_PX = 1;
// Use this to specify that any of the auto-size configuration int values have not been set.
private static final float UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE = -1f;
// Auto-size text type.
private int mAutoSizeTextType = AUTO_SIZE_TEXT_TYPE_NONE;
// Specify if auto-size text is needed.
private boolean mNeedsAutoSizeText = false;
// Step size for auto-sizing in pixels.
private float mAutoSizeStepGranularityInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE;
// Minimum text size for auto-sizing in pixels.
private float mAutoSizeMinTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE;
// Maximum text size for auto-sizing in pixels.
private float mAutoSizeMaxTextSizeInPx = UNSET_AUTO_SIZE_UNIFORM_CONFIGURATION_VALUE;
// Contains a (specified or computed) distinct sorted set of text sizes in pixels to pick from
// when auto-sizing text.
private int[] mAutoSizeTextSizesInPx = EmptyArray.INT;
// Specifies whether auto-size should use the provided auto size steps set or if it should
// build the steps set using mAutoSizeMinTextSizeInPx, mAutoSizeMaxTextSizeInPx and
// mAutoSizeStepGranularityInPx.
private boolean mHasPresetAutoSizeValues = false;
// Autofill-related attributes
//
// Indicates whether the text was set statically or dynamically, so it can be used to
// sanitize autofill requests.
private boolean mTextSetFromXmlOrResourceId = false;
// Resource id used to set the text.
private @StringRes int mTextId = Resources.ID_NULL;
// Resource id used to set the hint.
private @StringRes int mHintId = Resources.ID_NULL;
//
// End of autofill-related attributes
/**
* Kick-start the font cache for the zygote process (to pay the cost of
* initializing freetype for our default font only once).
* @hide
*/
public static void preloadFontCache() {
Paint p = new Paint();
p.setAntiAlias(true);
// Ensure that the Typeface is loaded here.
// Typically, Typeface is preloaded by zygote but not on all devices, e.g. Android Auto.
// So, sets Typeface.DEFAULT explicitly here for ensuring that the Typeface is loaded here
// since Paint.measureText can not be called without Typeface static initializer.
p.setTypeface(Typeface.DEFAULT);
// We don't care about the result, just the side-effect of measuring.
p.measureText("H");
}
/**
* Interface definition for a callback to be invoked when an action is
* performed on the editor.
*/
public interface OnEditorActionListener {
/**
* Called when an action is being performed.
*
* @param v The view that was clicked.
* @param actionId Identifier of the action. This will be either the
* identifier you supplied, or {@link EditorInfo#IME_NULL
* EditorInfo.IME_NULL} if being called due to the enter key
* being pressed.
* @param event If triggered by an enter key, this is the event;
* otherwise, this is null.
* @return Return true if you have consumed the action, else false.
*/
boolean onEditorAction(TextView v, int actionId, KeyEvent event);
}
public TextView(Context context) {
this(context, null);
}
public TextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.textViewStyle);
}
public TextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
@SuppressWarnings("deprecation")
public TextView(
Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);