-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
TextInputLayout.java
4701 lines (4221 loc) · 174 KB
/
TextInputLayout.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) 2015 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 com.google.android.material.textfield;
import com.google.android.material.R;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static com.google.android.material.textfield.EditTextUtils.isEditable;
import static com.google.android.material.textfield.IndicatorViewController.COUNTER_INDEX;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.AppCompatDrawableManager;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.TintTypedArray;
import android.text.Editable;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStructure;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.accessibility.AccessibilityEvent;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RequiresApi;
import androidx.annotation.RestrictTo;
import androidx.annotation.StringRes;
import androidx.annotation.StyleRes;
import androidx.annotation.VisibleForTesting;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.core.text.BidiFormatter;
import androidx.core.view.AccessibilityDelegateCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat;
import androidx.core.widget.TextViewCompat;
import androidx.customview.view.AbsSavedState;
import androidx.transition.Fade;
import androidx.transition.TransitionManager;
import com.google.android.material.animation.AnimationUtils;
import com.google.android.material.color.MaterialColors;
import com.google.android.material.internal.CheckableImageButton;
import com.google.android.material.internal.CollapsingTextHelper;
import com.google.android.material.internal.DescendantOffsetUtils;
import com.google.android.material.internal.StaticLayoutBuilderCompat;
import com.google.android.material.internal.StaticLayoutBuilderCompat.StaticLayoutBuilderCompatException;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.motion.MotionUtils;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shape.CornerFamily;
import com.google.android.material.shape.CornerTreatment;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.ShapeAppearanceModel;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.LinkedHashSet;
/**
* Layout which wraps a {@link TextInputEditText}, {@link android.widget.EditText}, or descendant to
* show a floating label when the hint is hidden while the user inputs text.
*
* <p>Also supports:
*
* <ul>
* <li>Showing an error via {@link #setErrorEnabled(boolean)} and {@link #setError(CharSequence)},
* along with showing an error icon via {@link #setErrorIconDrawable}
* <li>Showing helper text via {@link #setHelperTextEnabled(boolean)} and {@link
* #setHelperText(CharSequence)}
* <li>Showing placeholder text via {@link #setPlaceholderText(CharSequence)}
* <li>Showing prefix text via {@link #setPrefixText(CharSequence)}
* <li>Showing suffix text via {@link #setSuffixText(CharSequence)}
* <li>Showing a character counter via {@link #setCounterEnabled(boolean)} and {@link
* #setCounterMaxLength(int)}
* <li>Password visibility toggling via {@link #setEndIconMode(int)} API and related attribute. If
* set, a button is displayed to toggle between the password being displayed as plain-text or
* disguised, when your EditText is set to display a password.
* <li>Clearing text functionality via {@link #setEndIconMode(int)} API and related attribute. If
* set, a button is displayed when text is present and clicking it clears the EditText field.
* <li>Showing a custom icon specified via {@link #setEndIconMode(int)} API and related attribute.
* You should specify a drawable and content description for the icon. Optionally, you can
* also specify an {@link android.view.View.OnClickListener}, an {@link
* OnEditTextAttachedListener} and an {@link OnEndIconChangedListener}.
* <p><strong>Note:</strong> When using an end icon, the 'end' compound drawable of the
* EditText will be overridden while the end icon view is visible. To ensure that any existing
* drawables are restored correctly, you should set those compound drawables relatively
* (start/end), as opposed to absolutely (left/right).
* <li>Showing a start icon via {@link #setStartIconDrawable(Drawable)} API and related attribute.
* You should specify a content description for the icon. Optionally, you can also specify an
* {@link android.view.View.OnClickListener} for it.
* <p><strong>Note:</strong> Use the {@link #setStartIconDrawable(Drawable)} API in place of
* setting a start/left compound drawable on the EditText. When using a start icon, the
* 'start/left' compound drawable of the EditText will be overridden.
* <li>Showing a button that when clicked displays a dropdown menu. The selected option is
* displayed above the dropdown. You need to use an {@link AutoCompleteTextView} instead of a
* {@link TextInputEditText} as the input text child, and a
* Widget.MaterialComponents.TextInputLayout.(...).ExposedDropdownMenu style.
* <p>To disable user input you should set
* <pre>android:editable="false"</pre>
* on the {@link AutoCompleteTextView}.
* </ul>
*
* <p>The {@link TextInputEditText} class is provided to be used as the input text child of this
* layout. Using TextInputEditText instead of an EditText provides accessibility support for the
* text field and allows TextInputLayout greater control over the visual aspects of the text field.
* This is an example usage:
*
* <pre>
* <com.google.android.material.textfield.TextInputLayout
* android:layout_width="match_parent"
* android:layout_height="wrap_content"
* android:hint="@string/form_username">
*
* <com.google.android.material.textfield.TextInputEditText
* android:layout_width="match_parent"
* android:layout_height="wrap_content"/>
*
* </com.google.android.material.textfield.TextInputLayout>
* </pre>
*
* The hint should be set on the TextInputLayout, rather than the EditText. If a hint is specified
* on the child EditText in XML, the TextInputLayout might still work correctly; TextInputLayout
* will use the EditText's hint as its floating label. However, future calls to modify the hint will
* not update TextInputLayout's hint. To avoid unintended behavior, call {@link
* TextInputLayout#setHint(CharSequence)} and {@link TextInputLayout#getHint()} on TextInputLayout,
* instead of on EditText.
*
* <p>If you construct the {@link TextInputEditText} child of a {@link TextInputLayout}
* programmatically, you should use {@link TextInputLayout}'s {@code context} to create the view.
* This will allow {@link TextInputLayout} to pass along the appropriate styling to the {@link
* TextInputEditText}.
*
* <p>If the {@link EditText} child is not a {@link TextInputEditText}, make sure to set the {@link
* EditText}'s {@code android:background} to {@code null} when using an outlined or filled text
* field. This allows {@link TextInputLayout} to set the {@link EditText}'s background to an
* outlined or filled box, respectively.
*
* <p><strong>Note:</strong> The actual view hierarchy present under TextInputLayout is
* <strong>NOT</strong> guaranteed to match the view hierarchy as written in XML. As a result, calls
* to {@code getParent()} on children of the TextInputLayout -- such as a TextInputEditText -- may
* not return the TextInputLayout itself, but rather an intermediate View. If you need to access a
* View directly, set an {@code android:id} and use {@link View#findViewById(int)}.
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/TextField.md">component
* developer guidance</a> and <a href="https://material.io/components/text-fields/overview">design
* guidelines</a>.
*/
public class TextInputLayout extends LinearLayout implements OnGlobalLayoutListener {
private static final String TAG = "TextInputLayout";
private static final int DEF_STYLE_RES = R.style.Widget_Design_TextInputLayout;
/** Duration for the label's scale up and down animations. */
private static final int LABEL_SCALE_ANIMATION_DURATION = 167;
private static final int DEFAULT_PLACEHOLDER_FADE_DURATION = 87;
private static final int PLACEHOLDER_START_DELAY = 67;
private static final int INVALID_MAX_LENGTH = -1;
private static final int NO_WIDTH = -1;
private static final int[][] EDIT_TEXT_BACKGROUND_RIPPLE_STATE =
new int[][] {
new int[] {android.R.attr.state_pressed}, new int[] {},
};
private static final String LOG_TAG = "TextInputLayout";
@NonNull private final FrameLayout inputFrame;
@NonNull private final StartCompoundLayout startLayout;
@NonNull private final EndCompoundLayout endLayout;
private final int extraSpaceBetweenPlaceholderAndHint;
EditText editText;
private CharSequence originalHint;
private int minEms = NO_WIDTH;
private int maxEms = NO_WIDTH;
private int minWidth = NO_WIDTH;
private int maxWidth = NO_WIDTH;
private final IndicatorViewController indicatorViewController = new IndicatorViewController(this);
/** Interface definition for a length counter. */
public interface LengthCounter {
/**
* Counts the length of the text and returns it.
*
* @param text The text to count the length for.
* @return The count that the counter should be updated with.
*/
int countLength(@Nullable Editable text);
}
boolean counterEnabled;
private int counterMaxLength;
private boolean counterOverflowed;
@NonNull
private LengthCounter lengthCounter = (Editable text) -> text != null ? text.length() : 0;
@Nullable private TextView counterView;
private int counterOverflowTextAppearance;
private int counterTextAppearance;
private CharSequence placeholderText;
private boolean placeholderEnabled;
private TextView placeholderTextView;
@Nullable private ColorStateList placeholderTextColor;
private int placeholderTextAppearance;
@Nullable private Fade placeholderFadeIn;
@Nullable private Fade placeholderFadeOut;
@Nullable private ColorStateList counterTextColor;
@Nullable private ColorStateList counterOverflowTextColor;
@Nullable private ColorStateList cursorColor;
@Nullable private ColorStateList cursorErrorColor;
private boolean hintEnabled;
private CharSequence hint;
/**
* {@code true} when providing a hint on behalf of a child {@link EditText}. If the child is an
* instance of {@link TextInputEditText}, this value defines the behavior of its {@link
* TextInputEditText#getHint()} method.
*/
private boolean isProvidingHint;
@Nullable private MaterialShapeDrawable boxBackground;
private MaterialShapeDrawable outlinedDropDownMenuBackground;
private StateListDrawable filledDropDownMenuBackground;
private boolean boxBackgroundApplied;
@Nullable private MaterialShapeDrawable boxUnderlineDefault;
@Nullable private MaterialShapeDrawable boxUnderlineFocused;
@NonNull private ShapeAppearanceModel shapeAppearanceModel;
private boolean areCornerRadiiRtl;
private final int boxLabelCutoutPaddingPx;
@BoxBackgroundMode private int boxBackgroundMode;
private int boxCollapsedPaddingTopPx;
private int boxStrokeWidthPx;
private int boxStrokeWidthDefaultPx;
private int boxStrokeWidthFocusedPx;
@ColorInt private int boxStrokeColor;
@ColorInt private int boxBackgroundColor;
/**
* Values for box background mode. There is either a filled background, an outline background, or
* no background.
*/
@IntDef({BOX_BACKGROUND_NONE, BOX_BACKGROUND_FILLED, BOX_BACKGROUND_OUTLINE})
@Retention(RetentionPolicy.SOURCE)
public @interface BoxBackgroundMode {}
public static final int BOX_BACKGROUND_NONE = 0;
public static final int BOX_BACKGROUND_FILLED = 1;
public static final int BOX_BACKGROUND_OUTLINE = 2;
private final Rect tmpRect = new Rect();
private final Rect tmpBoundsRect = new Rect();
private final RectF tmpRectF = new RectF();
private Typeface typeface;
@Nullable private Drawable startDummyDrawable;
private int startDummyDrawableWidth;
/**
* Values for the end icon mode.
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@IntDef({
END_ICON_CUSTOM,
END_ICON_NONE,
END_ICON_PASSWORD_TOGGLE,
END_ICON_CLEAR_TEXT,
END_ICON_DROPDOWN_MENU
})
@Retention(RetentionPolicy.SOURCE)
public @interface EndIconMode {}
/**
* The TextInputLayout will show a custom icon specified by the user.
*
* @see #setEndIconMode(int)
* @see #getEndIconMode()
* @see #setEndIconDrawable(Drawable)
* @see #setEndIconContentDescription(CharSequence)
* @see #setEndIconOnClickListener(OnClickListener) (optionally)
* @see #addOnEditTextAttachedListener(OnEditTextAttachedListener) (optionally)
* @see #addOnEndIconChangedListener(OnEndIconChangedListener) (optionally)
*/
public static final int END_ICON_CUSTOM = -1;
/**
* Default for the TextInputLayout. It will not display an end icon.
*
* @see #setEndIconMode(int)
* @see #getEndIconMode()
*/
public static final int END_ICON_NONE = 0;
/**
* The TextInputLayout will show a password toggle button if its EditText displays a password.
* When this end icon is clicked, the password is shown as plain-text if it was disguised, or
* vice-versa.
*
* @see #setEndIconMode(int)
* @see #getEndIconMode()
*/
public static final int END_ICON_PASSWORD_TOGGLE = 1;
/**
* The TextInputLayout will show a clear text button while there is input in the EditText.
* Clicking it will clear out the text and hide the icon.
*
* @see #setEndIconMode(int)
* @see #getEndIconMode()
*/
public static final int END_ICON_CLEAR_TEXT = 2;
/**
* The TextInputLayout will show a dropdown button if the EditText is an {@link
* AutoCompleteTextView} and a {@code
* Widget.MaterialComponents.TextInputLayout.(...).ExposedDropdownMenu} style is being used.
*
* <p>Clicking the button will display a popup with a list of options. The current selected option
* is displayed on the EditText.
*/
public static final int END_ICON_DROPDOWN_MENU = 3;
/**
* Callback interface invoked when the view's {@link EditText} is attached, or from {@link
* #addOnEditTextAttachedListener(OnEditTextAttachedListener)} if the edit text is already
* present.
*
* @see #addOnEditTextAttachedListener(OnEditTextAttachedListener)
*/
public interface OnEditTextAttachedListener {
/**
* Called when the {@link EditText} is attached, or from {@link
* #addOnEditTextAttachedListener(OnEditTextAttachedListener)} if the edit text is already
* present.
*
* @param textInputLayout the {@link TextInputLayout}
*/
void onEditTextAttached(@NonNull TextInputLayout textInputLayout);
}
/**
* Callback interface invoked when the view's end icon changes.
*
* @see #setEndIconMode(int)
*/
public interface OnEndIconChangedListener {
/**
* Called when the end icon changes.
*
* @param textInputLayout the {@link TextInputLayout}
* @param previousIcon the end icon mode the view previously had set
*/
void onEndIconChanged(@NonNull TextInputLayout textInputLayout, @EndIconMode int previousIcon);
}
private final LinkedHashSet<OnEditTextAttachedListener> editTextAttachedListeners =
new LinkedHashSet<>();
@Nullable private Drawable endDummyDrawable;
private int endDummyDrawableWidth;
private Drawable originalEditTextEndDrawable;
private ColorStateList defaultHintTextColor;
private ColorStateList focusedTextColor;
@ColorInt private int defaultStrokeColor;
@ColorInt private int hoveredStrokeColor;
@ColorInt private int focusedStrokeColor;
private ColorStateList strokeErrorColor;
@ColorInt private int defaultFilledBackgroundColor;
@ColorInt private int disabledFilledBackgroundColor;
@ColorInt private int focusedFilledBackgroundColor;
@ColorInt private int hoveredFilledBackgroundColor;
@ColorInt private int disabledColor;
int originalEditTextMinimumHeight;
// Only used for testing
private boolean hintExpanded;
final CollapsingTextHelper collapsingTextHelper = new CollapsingTextHelper(this);
private boolean expandedHintEnabled;
private boolean hintAnimationEnabled;
private ValueAnimator animator;
private boolean inDrawableStateChanged;
private boolean restoringSavedState;
private boolean globalLayoutListenerAdded = false;
public TextInputLayout(@NonNull Context context) {
this(context, null);
}
public TextInputLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.textInputStyle);
}
public TextInputLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(wrap(context, attrs, defStyleAttr, DEF_STYLE_RES), attrs, defStyleAttr);
// Ensure we are using the correctly themed context rather than the context that was passed in.
context = getContext();
setOrientation(VERTICAL);
setWillNotDraw(false);
setAddStatesFromChildren(true);
inputFrame = new FrameLayout(context);
inputFrame.setAddStatesFromChildren(true);
collapsingTextHelper.setTextSizeInterpolator(AnimationUtils.LINEAR_INTERPOLATOR);
collapsingTextHelper.setPositionInterpolator(AnimationUtils.LINEAR_INTERPOLATOR);
collapsingTextHelper.setCollapsedTextGravity(Gravity.TOP | Gravity.START);
final TintTypedArray a =
ThemeEnforcement.obtainTintedStyledAttributes(
context,
attrs,
R.styleable.TextInputLayout,
defStyleAttr,
DEF_STYLE_RES,
R.styleable.TextInputLayout_counterTextAppearance,
R.styleable.TextInputLayout_counterOverflowTextAppearance,
R.styleable.TextInputLayout_errorTextAppearance,
R.styleable.TextInputLayout_helperTextTextAppearance,
R.styleable.TextInputLayout_hintTextAppearance);
startLayout = new StartCompoundLayout(this, a);
hintEnabled = a.getBoolean(R.styleable.TextInputLayout_hintEnabled, true);
setHint(a.getText(R.styleable.TextInputLayout_android_hint));
hintAnimationEnabled = a.getBoolean(R.styleable.TextInputLayout_hintAnimationEnabled, true);
expandedHintEnabled = a.getBoolean(R.styleable.TextInputLayout_expandedHintEnabled, true);
if (a.hasValue(R.styleable.TextInputLayout_android_minEms)) {
setMinEms(a.getInt(R.styleable.TextInputLayout_android_minEms, NO_WIDTH));
} else if (a.hasValue(R.styleable.TextInputLayout_android_minWidth)) {
setMinWidth(a.getDimensionPixelSize(R.styleable.TextInputLayout_android_minWidth, NO_WIDTH));
}
if (a.hasValue(R.styleable.TextInputLayout_android_maxEms)) {
setMaxEms(a.getInt(R.styleable.TextInputLayout_android_maxEms, NO_WIDTH));
} else if (a.hasValue(R.styleable.TextInputLayout_android_maxWidth)) {
setMaxWidth(a.getDimensionPixelSize(R.styleable.TextInputLayout_android_maxWidth, NO_WIDTH));
}
shapeAppearanceModel =
ShapeAppearanceModel.builder(context, attrs, defStyleAttr, DEF_STYLE_RES).build();
boxLabelCutoutPaddingPx =
context
.getResources()
.getDimensionPixelOffset(R.dimen.mtrl_textinput_box_label_cutout_padding);
boxCollapsedPaddingTopPx =
a.getDimensionPixelOffset(R.styleable.TextInputLayout_boxCollapsedPaddingTop, 0);
extraSpaceBetweenPlaceholderAndHint =
getResources().getDimensionPixelSize(R.dimen.m3_multiline_hint_filled_text_extra_space);
boxStrokeWidthDefaultPx =
a.getDimensionPixelSize(
R.styleable.TextInputLayout_boxStrokeWidth,
context
.getResources()
.getDimensionPixelSize(R.dimen.mtrl_textinput_box_stroke_width_default));
boxStrokeWidthFocusedPx =
a.getDimensionPixelSize(
R.styleable.TextInputLayout_boxStrokeWidthFocused,
context
.getResources()
.getDimensionPixelSize(R.dimen.mtrl_textinput_box_stroke_width_focused));
boxStrokeWidthPx = boxStrokeWidthDefaultPx;
float boxCornerRadiusTopStart =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusTopStart, -1f);
float boxCornerRadiusTopEnd =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusTopEnd, -1f);
float boxCornerRadiusBottomEnd =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusBottomEnd, -1f);
float boxCornerRadiusBottomStart =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusBottomStart, -1f);
ShapeAppearanceModel.Builder shapeBuilder = shapeAppearanceModel.toBuilder();
if (boxCornerRadiusTopStart >= 0) {
shapeBuilder.setTopLeftCornerSize(boxCornerRadiusTopStart);
}
if (boxCornerRadiusTopEnd >= 0) {
shapeBuilder.setTopRightCornerSize(boxCornerRadiusTopEnd);
}
if (boxCornerRadiusBottomEnd >= 0) {
shapeBuilder.setBottomRightCornerSize(boxCornerRadiusBottomEnd);
}
if (boxCornerRadiusBottomStart >= 0) {
shapeBuilder.setBottomLeftCornerSize(boxCornerRadiusBottomStart);
}
shapeAppearanceModel = shapeBuilder.build();
ColorStateList filledBackgroundColorStateList =
MaterialResources.getColorStateList(
context, a, R.styleable.TextInputLayout_boxBackgroundColor);
if (filledBackgroundColorStateList != null) {
defaultFilledBackgroundColor = filledBackgroundColorStateList.getDefaultColor();
boxBackgroundColor = defaultFilledBackgroundColor;
if (filledBackgroundColorStateList.isStateful()) {
disabledFilledBackgroundColor =
filledBackgroundColorStateList.getColorForState(
new int[] {-android.R.attr.state_enabled}, -1);
focusedFilledBackgroundColor =
filledBackgroundColorStateList.getColorForState(
new int[] {android.R.attr.state_focused, android.R.attr.state_enabled}, -1);
hoveredFilledBackgroundColor =
filledBackgroundColorStateList.getColorForState(
new int[] {android.R.attr.state_hovered, android.R.attr.state_enabled}, -1);
} else {
focusedFilledBackgroundColor = defaultFilledBackgroundColor;
ColorStateList mtrlFilledBackgroundColorStateList =
AppCompatResources.getColorStateList(context, R.color.mtrl_filled_background_color);
disabledFilledBackgroundColor =
mtrlFilledBackgroundColorStateList.getColorForState(
new int[] {-android.R.attr.state_enabled}, -1);
hoveredFilledBackgroundColor =
mtrlFilledBackgroundColorStateList.getColorForState(
new int[] {android.R.attr.state_hovered}, -1);
}
} else {
boxBackgroundColor = Color.TRANSPARENT;
defaultFilledBackgroundColor = Color.TRANSPARENT;
disabledFilledBackgroundColor = Color.TRANSPARENT;
focusedFilledBackgroundColor = Color.TRANSPARENT;
hoveredFilledBackgroundColor = Color.TRANSPARENT;
}
if (a.hasValue(R.styleable.TextInputLayout_android_textColorHint)) {
defaultHintTextColor =
focusedTextColor = a.getColorStateList(R.styleable.TextInputLayout_android_textColorHint);
}
ColorStateList boxStrokeColorStateList =
MaterialResources.getColorStateList(context, a, R.styleable.TextInputLayout_boxStrokeColor);
// Default values for stroke colors if boxStrokeColorStateList is not stateful
focusedStrokeColor = a.getColor(R.styleable.TextInputLayout_boxStrokeColor, Color.TRANSPARENT);
defaultStrokeColor =
ContextCompat.getColor(context, R.color.mtrl_textinput_default_box_stroke_color);
disabledColor = ContextCompat.getColor(context, R.color.mtrl_textinput_disabled_color);
hoveredStrokeColor =
ContextCompat.getColor(context, R.color.mtrl_textinput_hovered_box_stroke_color);
// Values from boxStrokeColorStateList
if (boxStrokeColorStateList != null) {
setBoxStrokeColorStateList(boxStrokeColorStateList);
}
if (a.hasValue(R.styleable.TextInputLayout_boxStrokeErrorColor)) {
setBoxStrokeErrorColor(
MaterialResources.getColorStateList(
context, a, R.styleable.TextInputLayout_boxStrokeErrorColor));
}
final int hintAppearance = a.getResourceId(R.styleable.TextInputLayout_hintTextAppearance, -1);
if (hintAppearance != -1) {
setHintTextAppearance(a.getResourceId(R.styleable.TextInputLayout_hintTextAppearance, 0));
}
cursorColor = a.getColorStateList(R.styleable.TextInputLayout_cursorColor);
cursorErrorColor = a.getColorStateList(R.styleable.TextInputLayout_cursorErrorColor);
final int errorTextAppearance =
a.getResourceId(R.styleable.TextInputLayout_errorTextAppearance, 0);
final CharSequence errorContentDescription =
a.getText(R.styleable.TextInputLayout_errorContentDescription);
final int errorAccessibilityLiveRegion =
a.getInt(
R.styleable.TextInputLayout_errorAccessibilityLiveRegion,
ViewCompat.ACCESSIBILITY_LIVE_REGION_POLITE);
final boolean errorEnabled = a.getBoolean(R.styleable.TextInputLayout_errorEnabled, false);
final int helperTextTextAppearance =
a.getResourceId(R.styleable.TextInputLayout_helperTextTextAppearance, 0);
final boolean helperTextEnabled =
a.getBoolean(R.styleable.TextInputLayout_helperTextEnabled, false);
final CharSequence helperText = a.getText(R.styleable.TextInputLayout_helperText);
final int placeholderTextAppearance =
a.getResourceId(R.styleable.TextInputLayout_placeholderTextAppearance, 0);
final CharSequence placeholderText = a.getText(R.styleable.TextInputLayout_placeholderText);
final boolean counterEnabled = a.getBoolean(R.styleable.TextInputLayout_counterEnabled, false);
setCounterMaxLength(a.getInt(R.styleable.TextInputLayout_counterMaxLength, INVALID_MAX_LENGTH));
counterTextAppearance = a.getResourceId(R.styleable.TextInputLayout_counterTextAppearance, 0);
counterOverflowTextAppearance =
a.getResourceId(R.styleable.TextInputLayout_counterOverflowTextAppearance, 0);
setBoxBackgroundMode(
a.getInt(R.styleable.TextInputLayout_boxBackgroundMode, BOX_BACKGROUND_NONE));
setErrorContentDescription(errorContentDescription);
setErrorAccessibilityLiveRegion(errorAccessibilityLiveRegion);
setCounterOverflowTextAppearance(counterOverflowTextAppearance);
setHelperTextTextAppearance(helperTextTextAppearance);
setErrorTextAppearance(errorTextAppearance);
setCounterTextAppearance(counterTextAppearance);
setPlaceholderText(placeholderText);
setPlaceholderTextAppearance(placeholderTextAppearance);
if (a.hasValue(R.styleable.TextInputLayout_errorTextColor)) {
setErrorTextColor(a.getColorStateList(R.styleable.TextInputLayout_errorTextColor));
}
if (a.hasValue(R.styleable.TextInputLayout_helperTextTextColor)) {
setHelperTextColor(a.getColorStateList(R.styleable.TextInputLayout_helperTextTextColor));
}
if (a.hasValue(R.styleable.TextInputLayout_hintTextColor)) {
setHintTextColor(a.getColorStateList(R.styleable.TextInputLayout_hintTextColor));
}
if (a.hasValue(R.styleable.TextInputLayout_counterTextColor)) {
setCounterTextColor(a.getColorStateList(R.styleable.TextInputLayout_counterTextColor));
}
if (a.hasValue(R.styleable.TextInputLayout_counterOverflowTextColor)) {
setCounterOverflowTextColor(
a.getColorStateList(R.styleable.TextInputLayout_counterOverflowTextColor));
}
if (a.hasValue(R.styleable.TextInputLayout_placeholderTextColor)) {
setPlaceholderTextColor(
a.getColorStateList(R.styleable.TextInputLayout_placeholderTextColor));
}
endLayout = new EndCompoundLayout(this, a);
final boolean enabled = a.getBoolean(R.styleable.TextInputLayout_android_enabled, true);
setHintMaxLines(a.getInt(R.styleable.TextInputLayout_hintMaxLines, 1));
a.recycle();
// For accessibility, consider TextInputLayout itself to be a simple container for an EditText,
// and do not expose it to accessibility services.
setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
// For autofill to work as intended, TextInputLayout needs to pass the hint text to the nested
// EditText so marking it as IMPORTANT_FOR_AUTOFILL_YES.
if (VERSION.SDK_INT >= VERSION_CODES.O) {
setImportantForAutofill(View.IMPORTANT_FOR_AUTOFILL_YES);
}
inputFrame.addView(startLayout);
inputFrame.addView(endLayout);
addView(inputFrame);
// TextInputLayout#setEnabled sets the enabled state not only for TextInputLayout itself but
// also for child views, so the method is called (and should be called) only after all child
// views have been added.
setEnabled(enabled);
setHelperTextEnabled(helperTextEnabled);
setErrorEnabled(errorEnabled);
setCounterEnabled(counterEnabled);
setHelperText(helperText);
}
@Override
public void onGlobalLayout() {
endLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
globalLayoutListenerAdded = false;
boolean updatedHeight = updateEditTextHeightBasedOnIcon();
boolean updatedIcon = updateDummyDrawables();
if (updatedHeight || updatedIcon) {
editText.post(() -> editText.requestLayout());
}
}
@Override
public void addView(
@NonNull View child, int index, @NonNull final ViewGroup.LayoutParams params) {
if (child instanceof EditText) {
// Make sure that the EditText is vertically at the bottom, so that it sits on the
// EditText's underline
FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(params);
flp.gravity = Gravity.CENTER_VERTICAL | (flp.gravity & ~Gravity.VERTICAL_GRAVITY_MASK);
inputFrame.addView(child, flp);
// Now use the EditText's LayoutParams as our own and update them to make enough space
// for the label
inputFrame.setLayoutParams(params);
updateInputLayoutMargins();
setEditText((EditText) child);
} else {
// Carry on adding the View...
super.addView(child, index, params);
}
}
@NonNull
MaterialShapeDrawable getBoxBackground() {
if (boxBackgroundMode == BOX_BACKGROUND_FILLED || boxBackgroundMode == BOX_BACKGROUND_OUTLINE) {
return boxBackground;
}
throw new IllegalStateException();
}
/**
* Set the box background mode (filled, outline, or none).
*
* <p>May be one of {@link #BOX_BACKGROUND_NONE}, {@link #BOX_BACKGROUND_FILLED}, or {@link
* #BOX_BACKGROUND_OUTLINE}.
*
* <p>Note: This method defines TextInputLayout's internal behavior (for example, it allows the
* hint to be displayed inline with the stroke in a cutout), but doesn't set all attributes that
* are set in the styles provided for the box background modes. To achieve the look of an outlined
* or filled text field, supplement this method with other methods that modify the box, such as
* {@link #setBoxStrokeColor(int)} and {@link #setBoxBackgroundColor(int)}.
*
* @param boxBackgroundMode box's background mode
* @throws IllegalArgumentException if boxBackgroundMode is not a @BoxBackgroundMode constant
*/
public void setBoxBackgroundMode(@BoxBackgroundMode int boxBackgroundMode) {
if (boxBackgroundMode == this.boxBackgroundMode) {
return;
}
this.boxBackgroundMode = boxBackgroundMode;
if (editText != null) {
onApplyBoxBackgroundMode();
}
}
/**
* Get the box background mode (filled, outline, or none).
*
* <p>May be one of {@link #BOX_BACKGROUND_NONE}, {@link #BOX_BACKGROUND_FILLED}, or {@link
* #BOX_BACKGROUND_OUTLINE}.
*/
@BoxBackgroundMode
public int getBoxBackgroundMode() {
return boxBackgroundMode;
}
private void onApplyBoxBackgroundMode() {
assignBoxBackgroundByMode();
updateEditTextBoxBackgroundIfNeeded();
updateTextInputBoxState();
updateBoxCollapsedPaddingTop();
adjustFilledEditTextPaddingForLargeFont();
if (boxBackgroundMode != BOX_BACKGROUND_NONE) {
updateInputLayoutMargins();
}
setDropDownMenuBackgroundIfNeeded();
}
private void assignBoxBackgroundByMode() {
switch (boxBackgroundMode) {
case BOX_BACKGROUND_FILLED:
boxBackground = new MaterialShapeDrawable(shapeAppearanceModel);
boxUnderlineDefault = new MaterialShapeDrawable();
boxUnderlineFocused = new MaterialShapeDrawable();
break;
case BOX_BACKGROUND_OUTLINE:
if (hintEnabled && !(boxBackground instanceof CutoutDrawable)) {
boxBackground = CutoutDrawable.create(shapeAppearanceModel);
} else {
boxBackground = new MaterialShapeDrawable(shapeAppearanceModel);
}
boxUnderlineDefault = null;
boxUnderlineFocused = null;
break;
case BOX_BACKGROUND_NONE:
boxBackground = null;
boxUnderlineDefault = null;
boxUnderlineFocused = null;
break;
default:
throw new IllegalArgumentException(
boxBackgroundMode + " is illegal; only @BoxBackgroundMode constants are supported.");
}
}
void updateEditTextBoxBackgroundIfNeeded() {
if (editText == null
|| boxBackground == null
// Only set boxBackground when edit text doesn't provide its own background.
|| (!boxBackgroundApplied && editText.getBackground() != null)
|| boxBackgroundMode == BOX_BACKGROUND_NONE) {
return;
}
updateEditTextBoxBackground();
boxBackgroundApplied = true;
}
private void updateEditTextBoxBackground() {
Drawable editTextBoxBackground = getEditTextBoxBackground();
editText.setBackground(editTextBoxBackground);
}
@Nullable
private Drawable getEditTextBoxBackground() {
if (!(editText instanceof AutoCompleteTextView) || isEditable(editText)) {
return boxBackground;
}
int rippleColor = MaterialColors.getColor(editText, R.attr.colorControlHighlight);
if (boxBackgroundMode == TextInputLayout.BOX_BACKGROUND_OUTLINE) {
return getOutlinedBoxBackgroundWithRipple(
getContext(), boxBackground, rippleColor, EDIT_TEXT_BACKGROUND_RIPPLE_STATE);
} else if (boxBackgroundMode == TextInputLayout.BOX_BACKGROUND_FILLED) {
return getFilledBoxBackgroundWithRipple(
boxBackground, boxBackgroundColor, rippleColor, EDIT_TEXT_BACKGROUND_RIPPLE_STATE);
}
// Should not happen.
return null;
}
private static Drawable getOutlinedBoxBackgroundWithRipple(
Context context, MaterialShapeDrawable boxBackground, int rippleColor, int[][] states) {
LayerDrawable editTextBackground;
int surfaceColor = MaterialColors.getColor(context, R.attr.colorSurface, "TextInputLayout");
MaterialShapeDrawable rippleBackground =
new MaterialShapeDrawable(boxBackground.getShapeAppearanceModel());
int pressedBackgroundColor = MaterialColors.layer(rippleColor, surfaceColor, 0.1f);
int[] rippleBackgroundColors = new int[] { pressedBackgroundColor, Color.TRANSPARENT };
rippleBackground.setFillColor(new ColorStateList(states, rippleBackgroundColors));
rippleBackground.setTint(surfaceColor);
int[] colors = new int[] {pressedBackgroundColor, surfaceColor};
ColorStateList rippleColorStateList = new ColorStateList(states, colors);
MaterialShapeDrawable mask =
new MaterialShapeDrawable(boxBackground.getShapeAppearanceModel());
mask.setTint(Color.WHITE);
Drawable rippleDrawable = new RippleDrawable(rippleColorStateList, rippleBackground, mask);
Drawable[] layers = {rippleDrawable, boxBackground};
editTextBackground = new LayerDrawable(layers);
return editTextBackground;
}
private static Drawable getFilledBoxBackgroundWithRipple(
MaterialShapeDrawable boxBackground,
int boxBackgroundColor,
int rippleColor,
int[][] states) {
int pressedBackgroundColor = MaterialColors.layer(rippleColor, boxBackgroundColor, 0.1f);
int[] colors = new int[] { pressedBackgroundColor, boxBackgroundColor };
ColorStateList rippleColorStateList = new ColorStateList(states, colors);
return new RippleDrawable(rippleColorStateList, boxBackground, boxBackground);
}
private void setDropDownMenuBackgroundIfNeeded() {
if (!(editText instanceof AutoCompleteTextView)) {
return;
}
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) editText;
if (autoCompleteTextView.getDropDownBackground() == null) {
if (boxBackgroundMode == BOX_BACKGROUND_OUTLINE) {
autoCompleteTextView.setDropDownBackgroundDrawable(
getOrCreateOutlinedDropDownMenuBackground());
} else if (boxBackgroundMode == BOX_BACKGROUND_FILLED) {
autoCompleteTextView.setDropDownBackgroundDrawable(
getOrCreateFilledDropDownMenuBackground());
}
}
}
private Drawable getOrCreateOutlinedDropDownMenuBackground() {
if (outlinedDropDownMenuBackground == null) {
outlinedDropDownMenuBackground = getDropDownMaterialShapeDrawable(true);
}
return outlinedDropDownMenuBackground;
}
private Drawable getOrCreateFilledDropDownMenuBackground() {
if (filledDropDownMenuBackground == null) {
filledDropDownMenuBackground = new StateListDrawable();
filledDropDownMenuBackground.addState(
new int[] {android.R.attr.state_above_anchor},
getOrCreateOutlinedDropDownMenuBackground());
filledDropDownMenuBackground.addState(new int[] {}, getDropDownMaterialShapeDrawable(false));
}
return filledDropDownMenuBackground;
}
private MaterialShapeDrawable getDropDownMaterialShapeDrawable(boolean roundedTopCorners) {
float cornerRadius =
getResources().getDimensionPixelOffset(R.dimen.mtrl_shape_corner_size_small_component);
float topCornerRadius = roundedTopCorners ? cornerRadius : 0;
float elevation =
editText instanceof MaterialAutoCompleteTextView
? ((MaterialAutoCompleteTextView) editText).getPopupElevation()
: getResources().getDimensionPixelOffset(
R.dimen.m3_comp_outlined_autocomplete_menu_container_elevation);
int verticalPadding =
getResources()
.getDimensionPixelOffset(R.dimen.mtrl_exposed_dropdown_menu_popup_vertical_padding);
ShapeAppearanceModel shapeAppearanceModel =
ShapeAppearanceModel.builder()
.setTopLeftCornerSize(topCornerRadius)
.setTopRightCornerSize(topCornerRadius)
.setBottomLeftCornerSize(cornerRadius)
.setBottomRightCornerSize(cornerRadius)
.build();
ColorStateList dropDownBackgroundTint = null;
if (editText instanceof MaterialAutoCompleteTextView) {
MaterialAutoCompleteTextView materialAutoCompleteTextView =
((MaterialAutoCompleteTextView) editText);
dropDownBackgroundTint = materialAutoCompleteTextView.getDropDownBackgroundTintList();
}
MaterialShapeDrawable popupDrawable =
MaterialShapeDrawable.createWithElevationOverlay(
getContext(), elevation, dropDownBackgroundTint);
popupDrawable.setShapeAppearanceModel(shapeAppearanceModel);
popupDrawable.setPadding(0, verticalPadding, 0, verticalPadding);
return popupDrawable;
}
private void updateBoxCollapsedPaddingTop() {
if (boxBackgroundMode == BOX_BACKGROUND_FILLED) {
if (MaterialResources.isFontScaleAtLeast2_0(getContext())) {
boxCollapsedPaddingTopPx =
getResources()
.getDimensionPixelSize(R.dimen.material_font_2_0_box_collapsed_padding_top);
} else if (MaterialResources.isFontScaleAtLeast1_3(getContext())) {
boxCollapsedPaddingTopPx =
getResources()
.getDimensionPixelSize(R.dimen.material_font_1_3_box_collapsed_padding_top);
}
}
}
private void adjustFilledEditTextPaddingForLargeFont() {
if (editText == null || boxBackgroundMode != BOX_BACKGROUND_FILLED) {