-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
TextInputLayout.java
2147 lines (1892 loc) · 76.5 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 com.google.android.material.textfield.IndicatorViewController.COUNTER_INDEX;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
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.DrawableContainer;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.annotation.VisibleForTesting;
import com.google.android.material.animation.AnimationUtils;
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.DrawableUtils;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.TintTypedArray;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStructure;
import android.view.accessibility.AccessibilityEvent;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* 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)}
* <li>Showing helper text via {@link #setHelperTextEnabled(boolean)} and {@link
* #setHelperText(CharSequence)}
* <li>Showing a character counter via {@link #setCounterEnabled(boolean)} and {@link
* #setCounterMaxLength(int)}
* <li>Password visibility toggling via the {@link #setPasswordVisibilityToggleEnabled(boolean)}
* API and related attribute. If enabled, 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.
* <p><strong>Note:</strong> When using the password toggle functionality, the 'end' compound
* drawable of the EditText will be overridden while the toggle is enabled. To ensure that any
* existing drawables are restored correctly, you should set those compound drawables
* relatively (start/end), as opposed to absolutely (left/right).
* </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.
* An example usage is as so:
*
* <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><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 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)}.
*/
public class TextInputLayout extends LinearLayout {
/** Duration for the label's scale up and down animations. */
private static final int LABEL_SCALE_ANIMATION_DURATION = 167;
private static final int INVALID_MAX_LENGTH = -1;
private static final String LOG_TAG = "TextInputLayout";
private final FrameLayout inputFrame;
EditText editText;
private CharSequence originalHint;
private final IndicatorViewController indicatorViewController = new IndicatorViewController(this);
boolean counterEnabled;
private int counterMaxLength;
private boolean counterOverflowed;
private TextView counterView;
private final int counterOverflowTextAppearance;
private final int counterTextAppearance;
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;
private GradientDrawable boxBackground;
private final int boxBottomOffsetPx;
private final int boxLabelCutoutPaddingPx;
@BoxBackgroundMode private int boxBackgroundMode;
private final int boxCollapsedPaddingTopPx;
private float boxCornerRadiusTopStart;
private float boxCornerRadiusTopEnd;
private float boxCornerRadiusBottomEnd;
private float boxCornerRadiusBottomStart;
private int boxStrokeWidthPx;
private final int boxStrokeWidthDefaultPx;
private final int boxStrokeWidthFocusedPx;
@ColorInt private int boxStrokeColor;
@ColorInt private int boxBackgroundColor;
private Drawable editTextOriginalDrawable;
/**
* 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 RectF tmpRectF = new RectF();
private Typeface typeface;
private boolean passwordToggleEnabled;
private Drawable passwordToggleDrawable;
private CharSequence passwordToggleContentDesc;
private CheckableImageButton passwordToggleView;
private boolean passwordToggledVisible;
private Drawable passwordToggleDummyDrawable;
private Drawable originalEditTextEndDrawable;
private ColorStateList passwordToggleTintList;
private boolean hasPasswordToggleTintList;
private PorterDuff.Mode passwordToggleTintMode;
private boolean hasPasswordToggleTintMode;
private ColorStateList defaultHintTextColor;
private ColorStateList focusedTextColor;
@ColorInt private final int defaultStrokeColor;
@ColorInt private final int hoveredStrokeColor;
@ColorInt private int focusedStrokeColor;
@ColorInt private final int disabledColor;
// Only used for testing
private boolean hintExpanded;
final CollapsingTextHelper collapsingTextHelper = new CollapsingTextHelper(this);
private boolean hintAnimationEnabled;
private ValueAnimator animator;
private boolean hasReconstructedEditTextBackground;
private boolean inDrawableStateChanged;
private boolean restoringSavedState;
public TextInputLayout(Context context) {
this(context, null);
}
public TextInputLayout(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.textInputStyle);
}
public TextInputLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setOrientation(VERTICAL);
setWillNotDraw(false);
setAddStatesFromChildren(true);
inputFrame = new FrameLayout(context);
inputFrame.setAddStatesFromChildren(true);
addView(inputFrame);
collapsingTextHelper.setTextSizeInterpolator(AnimationUtils.LINEAR_INTERPOLATOR);
collapsingTextHelper.setPositionInterpolator(AnimationUtils.LINEAR_INTERPOLATOR);
collapsingTextHelper.setCollapsedTextGravity(Gravity.TOP | GravityCompat.START);
final TintTypedArray a =
ThemeEnforcement.obtainTintedStyledAttributes(
context,
attrs,
R.styleable.TextInputLayout,
defStyleAttr,
R.style.Widget_Design_TextInputLayout);
hintEnabled = a.getBoolean(R.styleable.TextInputLayout_hintEnabled, true);
setHint(a.getText(R.styleable.TextInputLayout_android_hint));
hintAnimationEnabled = a.getBoolean(R.styleable.TextInputLayout_hintAnimationEnabled, true);
boxBottomOffsetPx =
context.getResources().getDimensionPixelOffset(R.dimen.mtrl_textinput_box_bottom_offset);
boxLabelCutoutPaddingPx =
context
.getResources()
.getDimensionPixelOffset(R.dimen.mtrl_textinput_box_label_cutout_padding);
boxCollapsedPaddingTopPx =
a.getDimensionPixelOffset(R.styleable.TextInputLayout_boxCollapsedPaddingTop, 0);
boxCornerRadiusTopStart =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusTopStart, 0f);
boxCornerRadiusTopEnd = a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusTopEnd, 0f);
boxCornerRadiusBottomEnd =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusBottomEnd, 0f);
boxCornerRadiusBottomStart =
a.getDimension(R.styleable.TextInputLayout_boxCornerRadiusBottomStart, 0f);
boxBackgroundColor =
a.getColor(R.styleable.TextInputLayout_boxBackgroundColor, Color.TRANSPARENT);
focusedStrokeColor = a.getColor(R.styleable.TextInputLayout_boxStrokeColor, Color.TRANSPARENT);
boxStrokeWidthDefaultPx =
context
.getResources()
.getDimensionPixelSize(R.dimen.mtrl_textinput_box_stroke_width_default);
boxStrokeWidthFocusedPx =
context
.getResources()
.getDimensionPixelSize(R.dimen.mtrl_textinput_box_stroke_width_focused);
boxStrokeWidthPx = boxStrokeWidthDefaultPx;
@BoxBackgroundMode
final int boxBackgroundMode =
a.getInt(R.styleable.TextInputLayout_boxBackgroundMode, BOX_BACKGROUND_NONE);
setBoxBackgroundMode(boxBackgroundMode);
if (a.hasValue(R.styleable.TextInputLayout_android_textColorHint)) {
defaultHintTextColor =
focusedTextColor = a.getColorStateList(R.styleable.TextInputLayout_android_textColorHint);
}
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);
final int hintAppearance = a.getResourceId(R.styleable.TextInputLayout_hintTextAppearance, -1);
if (hintAppearance != -1) {
setHintTextAppearance(a.getResourceId(R.styleable.TextInputLayout_hintTextAppearance, 0));
}
final int errorTextAppearance =
a.getResourceId(R.styleable.TextInputLayout_errorTextAppearance, 0);
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 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);
passwordToggleEnabled = a.getBoolean(R.styleable.TextInputLayout_passwordToggleEnabled, false);
passwordToggleDrawable = a.getDrawable(R.styleable.TextInputLayout_passwordToggleDrawable);
passwordToggleContentDesc =
a.getText(R.styleable.TextInputLayout_passwordToggleContentDescription);
if (a.hasValue(R.styleable.TextInputLayout_passwordToggleTint)) {
hasPasswordToggleTintList = true;
passwordToggleTintList = a.getColorStateList(R.styleable.TextInputLayout_passwordToggleTint);
}
if (a.hasValue(R.styleable.TextInputLayout_passwordToggleTintMode)) {
hasPasswordToggleTintMode = true;
passwordToggleTintMode =
ViewUtils.parseTintMode(
a.getInt(R.styleable.TextInputLayout_passwordToggleTintMode, -1), null);
}
a.recycle();
setHelperTextEnabled(helperTextEnabled);
setHelperText(helperText);
setHelperTextTextAppearance(helperTextTextAppearance);
setErrorEnabled(errorEnabled);
setErrorTextAppearance(errorTextAppearance);
setCounterEnabled(counterEnabled);
applyPasswordToggleTint();
// For accessibility, consider TextInputLayout itself to be a simple container for an EditText,
// and do not expose it to accessibility services.
ViewCompat.setImportantForAccessibility(this, ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO);
}
@Override
public void addView(View child, int index, 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
private Drawable getBoxBackground() {
if (boxBackgroundMode == BOX_BACKGROUND_FILLED || boxBackgroundMode == BOX_BACKGROUND_OUTLINE) {
return boxBackground;
}
throw new IllegalStateException();
}
/**
* Set the mode for the box's background (filled, outline, or none).
*
* @param boxBackgroundMode the box's background mode.
*/
public void setBoxBackgroundMode(@BoxBackgroundMode int boxBackgroundMode) {
if (boxBackgroundMode == this.boxBackgroundMode) {
return;
}
this.boxBackgroundMode = boxBackgroundMode;
onApplyBoxBackgroundMode();
}
private void onApplyBoxBackgroundMode() {
assignBoxBackgroundByMode();
if (boxBackgroundMode != BOX_BACKGROUND_NONE) {
updateInputLayoutMargins();
}
updateTextInputBoxBounds();
}
private void assignBoxBackgroundByMode() {
if (boxBackgroundMode == BOX_BACKGROUND_NONE) {
boxBackground = null;
} else if (boxBackgroundMode == BOX_BACKGROUND_OUTLINE
&& hintEnabled
&& !(boxBackground instanceof CutoutDrawable)) {
// Make boxBackground a CutoutDrawable if in outline mode, there is a hint, and
// boxBackground isn't already a CutoutDrawable.
boxBackground = new CutoutDrawable();
} else if (!(boxBackground instanceof GradientDrawable)) {
// Otherwise, make boxBackground a GradientDrawable if it isn't already.
boxBackground = new GradientDrawable();
}
}
/**
* Set the outline box's stroke color.
*
* <p>Calling this method when not in outline box mode will do nothing.
*
* @param boxStrokeColor the color to use for the box's stroke
* @see #getBoxStrokeColor()
*/
public void setBoxStrokeColor(@ColorInt int boxStrokeColor) {
if (focusedStrokeColor != boxStrokeColor) {
focusedStrokeColor = boxStrokeColor;
updateTextInputBoxState();
}
}
/**
* Returns the box's stroke color.
*
* @return the color used for the box's stroke
* @see #setBoxStrokeColor(int)
*/
public int getBoxStrokeColor() {
return focusedStrokeColor;
}
/**
* Set the resource used for the filled box's background color.
*
* @param boxBackgroundColorId the resource to use for the box's background color
*/
public void setBoxBackgroundColorResource(@ColorRes int boxBackgroundColorId) {
setBoxBackgroundColor(ContextCompat.getColor(getContext(), boxBackgroundColorId));
}
/**
* Set the filled box's background color.
*
* @param boxBackgroundColor the color to use for the filled box's background
* @see #getBoxBackgroundColor()
*/
public void setBoxBackgroundColor(@ColorInt int boxBackgroundColor) {
if (this.boxBackgroundColor != boxBackgroundColor) {
this.boxBackgroundColor = boxBackgroundColor;
applyBoxAttributes();
}
}
/**
* Returns the box's background color.
*
* @return the color used for the box's background
* @see #setBoxBackgroundColor(int)
*/
public int getBoxBackgroundColor() {
return boxBackgroundColor;
}
/**
* Set the resources used for the box's corner radii.
*
* @param boxCornerRadiusTopStartId the resource to use for the box's top start corner radius
* @param boxCornerRadiusTopEndId the resource to use for the box's top end corner radius
* @param boxCornerRadiusBottomEndId the resource to use for the box's bottom end corner radius
* @param boxCornerRadiusBottomStartId the resource to use for the box's bottom start corner
* radius
*/
public void setBoxCornerRadiiResources(
@DimenRes int boxCornerRadiusTopStartId,
@DimenRes int boxCornerRadiusTopEndId,
@DimenRes int boxCornerRadiusBottomEndId,
@DimenRes int boxCornerRadiusBottomStartId) {
setBoxCornerRadii(
getContext().getResources().getDimension(boxCornerRadiusTopStartId),
getContext().getResources().getDimension(boxCornerRadiusTopEndId),
getContext().getResources().getDimension(boxCornerRadiusBottomEndId),
getContext().getResources().getDimension(boxCornerRadiusBottomStartId));
}
/**
* Set the box's corner radii.
*
* @param boxCornerRadiusTopStart the value to use for the box's top start corner radius
* @param boxCornerRadiusTopEnd the value to use for the box's top end corner radius
* @param boxCornerRadiusBottomEnd the value to use for the box's bottom end corner radius
* @param boxCornerRadiusBottomStart the value to use for the box's bottom start corner radius
* @see #getBoxCornerRadiusTopStart()
* @see #getBoxCornerRadiusTopEnd()
* @see #getBoxCornerRadiusBottomEnd()
* @see #getBoxCornerRadiusBottomStart()
*/
public void setBoxCornerRadii(
float boxCornerRadiusTopStart,
float boxCornerRadiusTopEnd,
float boxCornerRadiusBottomStart,
float boxCornerRadiusBottomEnd) {
if (this.boxCornerRadiusTopStart != boxCornerRadiusTopStart
|| this.boxCornerRadiusTopEnd != boxCornerRadiusTopEnd
|| this.boxCornerRadiusBottomEnd != boxCornerRadiusBottomEnd
|| this.boxCornerRadiusBottomStart != boxCornerRadiusBottomStart) {
this.boxCornerRadiusTopStart = boxCornerRadiusTopStart;
this.boxCornerRadiusTopEnd = boxCornerRadiusTopEnd;
this.boxCornerRadiusBottomEnd = boxCornerRadiusBottomEnd;
this.boxCornerRadiusBottomStart = boxCornerRadiusBottomStart;
applyBoxAttributes();
}
}
/**
* Returns the box's top start corner radius.
*
* @return the value used for the box's top start corner radius
* @see #setBoxCornerRadii(float, float, float, float)
*/
public float getBoxCornerRadiusTopStart() {
return boxCornerRadiusTopStart;
}
/**
* Returns the box's top end corner radius.
*
* @return the value used for the box's top end corner radius
* @see #setBoxCornerRadii(float, float, float, float)
*/
public float getBoxCornerRadiusTopEnd() {
return boxCornerRadiusTopEnd;
}
/**
* Returns the box's bottom end corner radius.
*
* @return the value used for the box's bottom end corner radius
* @see #setBoxCornerRadii(float, float, float, float)
*/
public float getBoxCornerRadiusBottomEnd() {
return boxCornerRadiusBottomEnd;
}
/**
* Returns the box's bottom start corner radius.
*
* @return the value used for the box's bottom start corner radius
* @see #setBoxCornerRadii(float, float, float, float)
*/
public float getBoxCornerRadiusBottomStart() {
return boxCornerRadiusBottomStart;
}
private float[] getCornerRadiiAsArray() {
if (!ViewUtils.isLayoutRtl(this)) {
return new float[] {
boxCornerRadiusTopStart,
boxCornerRadiusTopStart,
boxCornerRadiusTopEnd,
boxCornerRadiusTopEnd,
boxCornerRadiusBottomEnd,
boxCornerRadiusBottomEnd,
boxCornerRadiusBottomStart,
boxCornerRadiusBottomStart,
};
} else {
return new float[] {
boxCornerRadiusTopEnd,
boxCornerRadiusTopEnd,
boxCornerRadiusTopStart,
boxCornerRadiusTopStart,
boxCornerRadiusBottomStart,
boxCornerRadiusBottomStart,
boxCornerRadiusBottomEnd,
boxCornerRadiusBottomEnd
};
}
}
/**
* Set the typeface to use for the hint and any label views (such as counter and error views).
*
* @param typeface typeface to use, or {@code null} to use the default.
*/
@SuppressWarnings("ReferenceEquality") // Matches the Typeface comparison in TextView
public void setTypeface(@Nullable Typeface typeface) {
if (typeface != this.typeface) {
this.typeface = typeface;
collapsingTextHelper.setTypefaces(typeface);
indicatorViewController.setTypefaces(typeface);
if (counterView != null) {
counterView.setTypeface(typeface);
}
}
}
/**
* Returns the typeface used for the hint and any label views (such as counter and error views).
*/
@Nullable
public Typeface getTypeface() {
return typeface;
}
@Override
public void dispatchProvideAutofillStructure(ViewStructure structure, int flags) {
if (originalHint == null || editText == null) {
super.dispatchProvideAutofillStructure(structure, flags);
return;
}
// Temporarily sets child's hint to its original value so it is properly set in the
// child's ViewStructure.
boolean wasProvidingHint = isProvidingHint;
// Ensures a child TextInputEditText does not retrieve its hint from this TextInputLayout.
isProvidingHint = false;
final CharSequence hint = editText.getHint();
editText.setHint(originalHint);
try {
super.dispatchProvideAutofillStructure(structure, flags);
} finally {
editText.setHint(hint);
isProvidingHint = wasProvidingHint;
}
}
private void setEditText(EditText editText) {
// If we already have an EditText, throw an exception
if (this.editText != null) {
throw new IllegalArgumentException("We already have an EditText, can only have one");
}
if (!(editText instanceof TextInputEditText)) {
Log.i(
LOG_TAG,
"EditText added is not a TextInputEditText. Please switch to using that"
+ " class instead.");
}
this.editText = editText;
onApplyBoxBackgroundMode();
setTextInputAccessibilityDelegate(new AccessibilityDelegate(this));
final boolean hasPasswordTransformation = hasPasswordTransformation();
// Use the EditText's typeface, and its text size for our expanded text.
if (!hasPasswordTransformation) {
// We don't want a monospace font just because we have a password field
collapsingTextHelper.setTypefaces(this.editText.getTypeface());
}
collapsingTextHelper.setExpandedTextSize(this.editText.getTextSize());
final int editTextGravity = this.editText.getGravity();
collapsingTextHelper.setCollapsedTextGravity(
Gravity.TOP | (editTextGravity & ~Gravity.VERTICAL_GRAVITY_MASK));
collapsingTextHelper.setExpandedTextGravity(editTextGravity);
// Add a TextWatcher so that we know when the text input has changed.
this.editText.addTextChangedListener(
new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
updateLabelState(!restoringSavedState);
if (counterEnabled) {
updateCounter(s.length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
// Use the EditText's hint colors if we don't have one set
if (defaultHintTextColor == null) {
defaultHintTextColor = this.editText.getHintTextColors();
}
// If we do not have a valid hint, try and retrieve it from the EditText, if enabled
if (hintEnabled) {
if (TextUtils.isEmpty(hint)) {
// Save the hint so it can be restored on dispatchProvideAutofillStructure();
originalHint = this.editText.getHint();
setHint(originalHint);
// Clear the EditText's hint as we will display it ourselves
this.editText.setHint(null);
}
this.isProvidingHint = true;
}
if (counterView != null) {
updateCounter(this.editText.getText().length());
}
indicatorViewController.adjustIndicatorPadding();
updatePasswordToggleView();
// Update the label visibility with no animation, but force a state change
updateLabelState(false, true);
}
private void updateInputLayoutMargins() {
// Create/update the LayoutParams so that we can add enough top margin
// to the EditText to make room for the label.
final LayoutParams lp = (LayoutParams) inputFrame.getLayoutParams();
final int newTopMargin = calculateLabelMarginTop();
if (newTopMargin != lp.topMargin) {
lp.topMargin = newTopMargin;
inputFrame.requestLayout();
}
}
void updateLabelState(boolean animate) {
updateLabelState(animate, false);
}
private void updateLabelState(boolean animate, boolean force) {
final boolean isEnabled = isEnabled();
final boolean hasText = editText != null && !TextUtils.isEmpty(editText.getText());
final boolean hasFocus = editText != null && editText.hasFocus();
final boolean errorShouldBeShown = indicatorViewController.errorShouldBeShown();
// Set the expanded and collapsed labels to the default text color.
if (defaultHintTextColor != null) {
collapsingTextHelper.setCollapsedTextColor(defaultHintTextColor);
collapsingTextHelper.setExpandedTextColor(defaultHintTextColor);
}
// Set the collapsed and expanded label text colors based on the current state.
if (!isEnabled) {
collapsingTextHelper.setCollapsedTextColor(ColorStateList.valueOf(disabledColor));
collapsingTextHelper.setExpandedTextColor(ColorStateList.valueOf(disabledColor));
} else if (errorShouldBeShown) {
collapsingTextHelper.setCollapsedTextColor(indicatorViewController.getErrorViewTextColors());
} else if (counterOverflowed && counterView != null) {
collapsingTextHelper.setCollapsedTextColor(counterView.getTextColors());
} else if (hasFocus && focusedTextColor != null) {
collapsingTextHelper.setCollapsedTextColor(focusedTextColor);
} // If none of these states apply, leave the expanded and collapsed colors as they are.
if (hasText || (isEnabled() && (hasFocus || errorShouldBeShown))) {
// We should be showing the label so do so if it isn't already
if (force || hintExpanded) {
collapseHint(animate);
}
} else {
// We should not be showing the label so hide it
if (force || !hintExpanded) {
expandHint(animate);
}
}
}
/** Returns the {@link android.widget.EditText} used for text input. */
@Nullable
public EditText getEditText() {
return editText;
}
/**
* Set the hint to be displayed in the floating label, if enabled.
*
* @see #setHintEnabled(boolean)
* @attr ref com.google.android.material.R.styleable#TextInputLayout_android_hint
*/
public void setHint(@Nullable CharSequence hint) {
if (hintEnabled) {
setHintInternal(hint);
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
}
}
private void setHintInternal(CharSequence hint) {
if (!TextUtils.equals(hint, this.hint)) {
this.hint = hint;
collapsingTextHelper.setText(hint);
// Reset the cutout to make room for a larger hint.
if (!hintExpanded) {
openCutout();
}
}
}
/**
* Returns the hint which is displayed in the floating label, if enabled.
*
* @return the hint, or null if there isn't one set, or the hint is not enabled.
* @attr ref com.google.android.material.R.styleable#TextInputLayout_android_hint
*/
@Nullable
public CharSequence getHint() {
return hintEnabled ? hint : null;
}
/**
* Sets whether the floating label functionality is enabled or not in this layout.
*
* <p>If enabled, any non-empty hint in the child EditText will be moved into the floating hint,
* and its existing hint will be cleared. If disabled, then any non-empty floating hint in this
* layout will be moved into the EditText, and this layout's hint will be cleared.
*
* @see #setHint(CharSequence)
* @see #isHintEnabled()
* @attr ref com.google.android.material.R.styleable#TextInputLayout_hintEnabled
*/
public void setHintEnabled(boolean enabled) {
if (enabled != hintEnabled) {
hintEnabled = enabled;
if (!hintEnabled) {
// Ensures a child TextInputEditText provides its internal hint, not this TextInputLayout's.
isProvidingHint = false;
if (!TextUtils.isEmpty(hint) && TextUtils.isEmpty(editText.getHint())) {
// If the child EditText has no hint, but this layout does, restore it on the child.
editText.setHint(hint);
}
// Now clear out any set hint
setHintInternal(null);
} else {
final CharSequence editTextHint = editText.getHint();
if (!TextUtils.isEmpty(editTextHint)) {
// If the hint is now enabled and the EditText has one set, we'll use it if
// we don't already have one, and clear the EditText's
if (TextUtils.isEmpty(hint)) {
setHint(editTextHint);
}
editText.setHint(null);
}
isProvidingHint = true;
}
// Now update the EditText top margin
if (editText != null) {
updateInputLayoutMargins();
}
}
}
/**
* Returns whether the floating label functionality is enabled or not in this layout.
*
* @see #setHintEnabled(boolean)
* @attr ref com.google.android.material.R.styleable#TextInputLayout_hintEnabled
*/
public boolean isHintEnabled() {
return hintEnabled;
}
/**
* Returns whether or not this layout is actively managing a child {@link EditText}'s hint. If the
* child is an instance of {@link TextInputEditText}, this value defines the behavior of {@link
* TextInputEditText#getHint()}.
*/
boolean isProvidingHint() {
return isProvidingHint;
}
/**
* Sets the hint text color, size, style from the specified TextAppearance resource.
*
* @attr ref com.google.android.material.R.styleable#TextInputLayout_hintTextAppearance
*/
public void setHintTextAppearance(@StyleRes int resId) {
collapsingTextHelper.setCollapsedTextAppearance(resId);
focusedTextColor = collapsingTextHelper.getCollapsedTextColor();
if (editText != null) {
updateLabelState(false);
// Text size might have changed so update the top margin
updateInputLayoutMargins();
}
}
/** Sets the text color used by the hint in both the collapsed and expanded states. */
public void setDefaultHintTextColor(@Nullable ColorStateList textColor) {
defaultHintTextColor = textColor;
focusedTextColor = textColor;
if (editText != null) {
updateLabelState(false);
}
}
/**
* Returns the text color used by the hint in both the collapsed and expanded states, or null if
* no color has been set.
*/
@Nullable
public ColorStateList getDefaultHintTextColor() {
return defaultHintTextColor;
}
/**
* Whether the error functionality is enabled or not in this layout. Enabling this functionality
* before setting an error message via {@link #setError(CharSequence)}, will mean that this layout
* will not change size when an error is displayed.
*
* @attr ref com.google.android.material.R.styleable#TextInputLayout_errorEnabled
*/
public void setErrorEnabled(boolean enabled) {
indicatorViewController.setErrorEnabled(enabled);
}
/**
* Sets the text color and size for the error message from the specified TextAppearance resource.
*
* @attr ref com.google.android.material.R.styleable#TextInputLayout_errorTextAppearance
*/
public void setErrorTextAppearance(@StyleRes int resId) {
indicatorViewController.setErrorTextAppearance(resId);
}
/** Sets the text color used by the error message in all states. */
public void setErrorTextColor(@Nullable ColorStateList textColors) {
indicatorViewController.setErrorViewTextColor(textColors);
}
/** Returns the text color used by the error message in current state. */
@ColorInt
public int getErrorCurrentTextColors() {
return indicatorViewController.getErrorViewCurrentTextColor();
}
/**
* Sets the text color and size for the helper text from the specified TextAppearance resource.
*
* @attr ref com.google.android.material.R.styleable#TextInputLayout_helperTextTextAppearance
*/
public void setHelperTextTextAppearance(@StyleRes int resId) {
indicatorViewController.setHelperTextAppearance(resId);
}
/**
* Returns whether the error functionality is enabled or not in this layout.
*
* @attr ref com.google.android.material.R.styleable#TextInputLayout_errorEnabled
* @see #setErrorEnabled(boolean)
*/
public boolean isErrorEnabled() {
return indicatorViewController.isErrorEnabled();
}
/**
* Whether the helper text functionality is enabled or not in this layout. Enabling this
* functionality before setting a helper message via {@link #setHelperText(CharSequence)} will
* mean that this layout will not change size when a helper message is displayed.
*
* @attr ref com.google.android.material.R.styleable#TextInputLayout_helperTextEnabled
*/
public void setHelperTextEnabled(boolean enabled) {
indicatorViewController.setHelperTextEnabled(enabled);
}
/**
* Sets a helper message that will be displayed below the {@link EditText}. If the {@code helper}
* is {@code null}, the helper text functionality will be disabled and the helper message will be
* hidden.
*
* <p>If the helper text functionality has not been enabled via {@link
* #setHelperTextEnabled(boolean)}, then it will be automatically enabled if {@code helper} is not
* empty.
*
* @param helperText Helper text to display