-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathMaterialButton.java
1708 lines (1526 loc) · 56.8 KB
/
MaterialButton.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) 2017 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.button;
import com.google.android.material.R;
import static android.view.Gravity.CENTER_HORIZONTAL;
import static android.view.Gravity.END;
import static android.view.Gravity.LEFT;
import static android.view.Gravity.RIGHT;
import static android.view.Gravity.START;
import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
import static com.google.android.material.theme.overlay.MaterialThemeOverlay.wrap;
import static java.lang.Math.ceil;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
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.AppCompatButton;
import android.text.Layout.Alignment;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import androidx.annotation.AttrRes;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.Dimension;
import androidx.annotation.DrawableRes;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Px;
import androidx.annotation.RestrictTo;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.customview.view.AbsSavedState;
import androidx.dynamicanimation.animation.FloatPropertyCompat;
import androidx.dynamicanimation.animation.SpringAnimation;
import androidx.dynamicanimation.animation.SpringForce;
import com.google.android.material.internal.ThemeEnforcement;
import com.google.android.material.internal.ViewUtils;
import com.google.android.material.motion.MotionUtils;
import androidx.resourceinspection.annotation.Attribute;
import com.google.android.material.resources.MaterialResources;
import com.google.android.material.shape.MaterialShapeDrawable;
import com.google.android.material.shape.MaterialShapeUtils;
import com.google.android.material.shape.ShapeAppearanceModel;
import com.google.android.material.shape.Shapeable;
import com.google.android.material.shape.StateListShapeAppearanceModel;
import com.google.android.material.shape.StateListSizeChange;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.LinkedHashSet;
/**
* A convenience class for creating a new Material button.
*
* <p>This class supplies updated Material styles for the button in the constructor. The widget will
* display the correct default Material styles without the use of the style flag.
*
* <p>All attributes from {@code com.google.android.material.R.styleable#MaterialButton} are
* supported. Do not use the {@code android:background} attribute. MaterialButton manages its own
* background drawable, and setting a new background means {@link MaterialButton} can no longer
* guarantee that the new attributes it introduces will function properly. If the default background
* is changed, {@link MaterialButton} cannot guarantee well-defined behavior.
*
* <p>For filled buttons, this class uses your theme's {@code ?attr/colorPrimary} for the background
* tint color and {@code ?attr/colorOnPrimary} for the text color. For unfilled buttons, this class
* uses {@code ?attr/colorPrimary} for the text color and transparent for the background tint.
*
* <p>Add icons to the start, center, or end of this button using the {@code app:icon}, {@code
* app:iconPadding}, {@code app:iconTint}, {@code app:iconTintMode} and {@code app:iconGravity}
* attributes.
*
* <p>If a start-aligned icon is added to this button, please use a style like one of the ".Icon"
* styles specified in the default MaterialButton styles. The ".Icon" styles adjust padding slightly
* to achieve a better visual balance. This style should only be used with a start-aligned icon
* button. If your icon is end-aligned, you cannot use a ".Icon" style and must instead manually
* adjust your padding such that the visual adjustment is mirrored.
*
* <p>Specify background tint using the {@code app:backgroundTint} and {@code
* app:backgroundTintMode} attributes, which accepts either a color or a color state list.
*
* <p>Ripple color / press state color can be specified using the {@code app:rippleColor} attribute.
* Ripple opacity will be determined by the Android framework when available. Otherwise, this color
* will be overlaid on the button at a 50% opacity when button is pressed.
*
* <p>Set the stroke color using the {@code app:strokeColor} attribute, which accepts either a color
* or a color state list. Stroke width can be set using the {@code app:strokeWidth} attribute.
*
* <p>Specify the radius of all four corners of the button using the {@code app:cornerRadius}
* attribute.
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/Button.md">component
* developer guidance</a> and <a href="https://material.io/components/buttons/overview">design
* guidelines</a>.
*/
public class MaterialButton extends AppCompatButton implements Checkable, Shapeable {
/** Interface definition for a callback to be invoked when the button checked state changes. */
public interface OnCheckedChangeListener {
/**
* Called when the checked state of a MaterialButton has changed.
*
* @param button The MaterialButton whose state has changed.
* @param isChecked The new checked state of MaterialButton.
*/
void onCheckedChanged(MaterialButton button, boolean isChecked);
}
/** Interface to listen for press state changes on this button. Internal use only. */
interface OnPressedChangeListener {
void onPressedChanged(MaterialButton button, boolean isPressed);
}
private static final int[] CHECKABLE_STATE_SET = {android.R.attr.state_checkable};
private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
/**
* Gravity used to position the icon at the start of the view.
*
* @see #setIconGravity(int)
* @see #getIconGravity()
*/
public static final int ICON_GRAVITY_START = 0x1;
/**
* Gravity used to position the icon in the center of the view at the start of the text
*
* @see #setIconGravity(int)
* @see #getIconGravity()
*/
public static final int ICON_GRAVITY_TEXT_START = 0x2;
/**
* Gravity used to position the icon at the end of the view.
*
* @see #setIconGravity(int)
* @see #getIconGravity()
*/
public static final int ICON_GRAVITY_END = 0x3;
/**
* Gravity used to position the icon in the center of the view at the end of the text
*
* @see #setIconGravity(int)
* @see #getIconGravity()
*/
public static final int ICON_GRAVITY_TEXT_END = 0x4;
/**
* Gravity used to position the icon at the top of the view.
*
* @see #setIconGravity(int)
* @see #getIconGravity()
*/
public static final int ICON_GRAVITY_TOP = 0x10;
/**
* Gravity used to position the icon in the center of the view at the top of the text
*
* @see #setIconGravity(int)
* @see #getIconGravity()
*/
public static final int ICON_GRAVITY_TEXT_TOP = 0x20;
/** Positions the icon can be set to. */
@IntDef({
ICON_GRAVITY_START,
ICON_GRAVITY_TEXT_START,
ICON_GRAVITY_END,
ICON_GRAVITY_TEXT_END,
ICON_GRAVITY_TOP,
ICON_GRAVITY_TEXT_TOP
})
@Retention(RetentionPolicy.SOURCE)
public @interface IconGravity {}
private static final String LOG_TAG = "MaterialButton";
private static final int DEF_STYLE_RES = R.style.Widget_MaterialComponents_Button;
@AttrRes private static final int MATERIAL_SIZE_OVERLAY_ATTR = R.attr.materialSizeOverlay;
private static final float OPTICAL_CENTER_RATIO = 0.11f;
private static final int UNSET = -1;
@NonNull private final MaterialButtonHelper materialButtonHelper;
@NonNull
private final LinkedHashSet<OnCheckedChangeListener> onCheckedChangeListeners =
new LinkedHashSet<>();
@Nullable private OnPressedChangeListener onPressedChangeListenerInternal;
@Nullable private Mode iconTintMode;
@Nullable private ColorStateList iconTint;
@Nullable private Drawable icon;
@Nullable private String accessibilityClassName;
@Px private int iconSize;
@Px private int iconLeft;
@Px private int iconTop;
@Px private int iconPadding;
private boolean checked = false;
private boolean broadcasting = false;
@IconGravity private int iconGravity;
private int orientation = UNSET;
private float originalWidth = UNSET;
@Px private int originalPaddingStart = UNSET;
@Px private int originalPaddingEnd = UNSET;
@Nullable private LayoutParams originalLayoutParams;
// Fields for optical center.
private boolean opticalCenterEnabled;
private int opticalCenterShift;
private boolean isInHorizontalButtonGroup;
// Fields for size morphing.
@Px int allowedWidthDecrease = UNSET;
@Nullable StateListSizeChange sizeChange;
@Px int widthChangeMax;
private float displayedWidthIncrease;
private float displayedWidthDecrease;
@Nullable private SpringAnimation widthIncreaseSpringAnimation;
public MaterialButton(@NonNull Context context) {
this(context, null /* attrs */);
}
public MaterialButton(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.materialButtonStyle);
}
public MaterialButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(
wrap(context, attrs, defStyleAttr, DEF_STYLE_RES, new int[] {MATERIAL_SIZE_OVERLAY_ATTR}),
attrs,
defStyleAttr);
// Ensure we are using the correctly themed context rather than the context that was passed in.
context = getContext();
TypedArray attributes =
ThemeEnforcement.obtainStyledAttributes(
context, attrs, R.styleable.MaterialButton, defStyleAttr, DEF_STYLE_RES);
iconPadding = attributes.getDimensionPixelSize(R.styleable.MaterialButton_iconPadding, 0);
iconTintMode =
ViewUtils.parseTintMode(
attributes.getInt(R.styleable.MaterialButton_iconTintMode, -1), Mode.SRC_IN);
iconTint =
MaterialResources.getColorStateList(
getContext(), attributes, R.styleable.MaterialButton_iconTint);
icon = MaterialResources.getDrawable(getContext(), attributes, R.styleable.MaterialButton_icon);
iconGravity = attributes.getInteger(R.styleable.MaterialButton_iconGravity, ICON_GRAVITY_START);
iconSize = attributes.getDimensionPixelSize(R.styleable.MaterialButton_iconSize, 0);
StateListShapeAppearanceModel stateListShapeAppearanceModel =
StateListShapeAppearanceModel.create(
context, attributes, R.styleable.MaterialButton_shapeAppearance);
ShapeAppearanceModel shapeAppearanceModel =
stateListShapeAppearanceModel != null
? stateListShapeAppearanceModel.getDefaultShape(/* withCornerSizeOverrides= */ true)
: ShapeAppearanceModel.builder(context, attrs, defStyleAttr, DEF_STYLE_RES).build();
boolean opticalCenterEnabled =
attributes.getBoolean(R.styleable.MaterialButton_opticalCenterEnabled, false);
// Loads and sets background drawable attributes
materialButtonHelper = new MaterialButtonHelper(this, shapeAppearanceModel);
materialButtonHelper.loadFromAttributes(attributes);
if (stateListShapeAppearanceModel != null) {
materialButtonHelper.setCornerSpringForce(createSpringForce());
materialButtonHelper.setStateListShapeAppearanceModel(stateListShapeAppearanceModel);
}
setOpticalCenterEnabled(opticalCenterEnabled);
attributes.recycle();
setCompoundDrawablePadding(iconPadding);
updateIcon(/* needsIconReset= */ icon != null);
}
private void initializeSizeAnimation() {
widthIncreaseSpringAnimation = new SpringAnimation(this, WIDTH_INCREASE);
widthIncreaseSpringAnimation.setSpring(createSpringForce());
}
private SpringForce createSpringForce() {
return MotionUtils.resolveThemeSpringForce(
getContext(),
R.attr.motionSpringFastSpatial,
R.style.Motion_Material3_Spring_Standard_Fast_Spatial);
}
@NonNull
@SuppressLint("KotlinPropertyAccess")
String getA11yClassName() {
if (!TextUtils.isEmpty(accessibilityClassName)) {
return accessibilityClassName;
}
// Use the platform widget classes so Talkback can recognize this as a button.
return (isCheckable() ? CompoundButton.class : Button.class).getName();
}
@RestrictTo(LIBRARY_GROUP)
public void setA11yClassName(@Nullable String className) {
accessibilityClassName = className;
}
@Override
public void onInitializeAccessibilityNodeInfo(@NonNull AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(getA11yClassName());
info.setCheckable(isCheckable());
info.setChecked(isChecked());
info.setClickable(isClickable());
}
@Override
public void onInitializeAccessibilityEvent(@NonNull AccessibilityEvent accessibilityEvent) {
super.onInitializeAccessibilityEvent(accessibilityEvent);
accessibilityEvent.setClassName(getA11yClassName());
accessibilityEvent.setChecked(isChecked());
}
@NonNull
@Override
public Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState savedState = new SavedState(superState);
savedState.checked = checked;
return savedState;
}
@Override
public void onRestoreInstanceState(@Nullable Parcelable state) {
if (!(state instanceof SavedState)) {
super.onRestoreInstanceState(state);
return;
}
SavedState savedState = (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
setChecked(savedState.checked);
}
/**
* This should be accessed via {@link
* androidx.core.view.ViewCompat#setBackgroundTintList(android.view.View, ColorStateList)}
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void setSupportBackgroundTintList(@Nullable ColorStateList tint) {
if (isUsingOriginalBackground()) {
materialButtonHelper.setSupportBackgroundTintList(tint);
} else {
// If default MaterialButton background has been overwritten, we will let AppCompatButton
// handle the tinting
super.setSupportBackgroundTintList(tint);
}
}
/**
* This should be accessed via {@link android.view.View#getBackgroundTintList()}
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
@Nullable
public ColorStateList getSupportBackgroundTintList() {
if (isUsingOriginalBackground()) {
return materialButtonHelper.getSupportBackgroundTintList();
} else {
// If default MaterialButton background has been overwritten, we will let AppCompatButton
// handle the tinting
// return null;
return super.getSupportBackgroundTintList();
}
}
/**
* This should be accessed via {@link
* androidx.core.view.ViewCompat#setBackgroundTintMode(android.view.View, PorterDuff.Mode)}
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
public void setSupportBackgroundTintMode(@Nullable PorterDuff.Mode tintMode) {
if (isUsingOriginalBackground()) {
materialButtonHelper.setSupportBackgroundTintMode(tintMode);
} else {
// If default MaterialButton background has been overwritten, we will let AppCompatButton
// handle the tint Mode
super.setSupportBackgroundTintMode(tintMode);
}
}
/**
* This should be accessed via {@link android.view.View#getBackgroundTintMode()}
*
* @hide
*/
@RestrictTo(LIBRARY_GROUP)
@Override
@Nullable
public PorterDuff.Mode getSupportBackgroundTintMode() {
if (isUsingOriginalBackground()) {
return materialButtonHelper.getSupportBackgroundTintMode();
} else {
// If default MaterialButton background has been overwritten, we will let AppCompatButton
// handle the tint mode
return super.getSupportBackgroundTintMode();
}
}
@Override
public void setBackgroundTintList(@Nullable ColorStateList tintList) {
setSupportBackgroundTintList(tintList);
}
@Nullable
@Override
public ColorStateList getBackgroundTintList() {
return getSupportBackgroundTintList();
}
@Override
public void setBackgroundTintMode(@Nullable Mode tintMode) {
setSupportBackgroundTintMode(tintMode);
}
@Nullable
@Override
public Mode getBackgroundTintMode() {
return getSupportBackgroundTintMode();
}
@Override
public void setBackgroundColor(@ColorInt int color) {
if (isUsingOriginalBackground()) {
materialButtonHelper.setBackgroundColor(color);
} else {
// If default MaterialButton background has been overwritten, we will let View handle
// setting the background color.
super.setBackgroundColor(color);
}
}
@Override
public void setBackground(@NonNull Drawable background) {
setBackgroundDrawable(background);
}
@Override
public void setBackgroundResource(@DrawableRes int backgroundResourceId) {
Drawable background = null;
if (backgroundResourceId != 0) {
background = AppCompatResources.getDrawable(getContext(), backgroundResourceId);
}
setBackgroundDrawable(background);
}
@Override
public void setBackgroundDrawable(@NonNull Drawable background) {
if (isUsingOriginalBackground()) {
if (background != this.getBackground()) {
Log.w(
LOG_TAG,
"MaterialButton manages its own background to control elevation, shape, color and"
+ " states. Consider using backgroundTint, shapeAppearance and other attributes"
+ " where available. A custom background will ignore these attributes and you"
+ " should consider handling interaction states such as pressed, focused and"
+ " disabled");
materialButtonHelper.setBackgroundOverwritten();
super.setBackgroundDrawable(background);
} else {
// ViewCompat.setBackgroundTintList() and setBackgroundTintMode() call setBackground() on
// the view in API 21, since background state doesn't automatically update in API 21. We
// capture this case here, and update our background without replacing it or re-tinting it.
getBackground().setState(background.getState());
}
} else {
super.setBackgroundDrawable(background);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
// Workaround for API 21 ripple bug (possibly internal in GradientDrawable)
if (VERSION.SDK_INT == VERSION_CODES.LOLLIPOP && materialButtonHelper != null) {
materialButtonHelper.updateMaskBounds(bottom - top, right - left);
}
updateIconPosition(getMeasuredWidth(), getMeasuredHeight());
int curOrientation = getResources().getConfiguration().orientation;
if (orientation != curOrientation) {
orientation = curOrientation;
originalWidth = UNSET;
}
if (originalWidth == UNSET) {
originalWidth = getMeasuredWidth();
// The width morph leverage the width of the layout params. However, it's not available if
// layout_weight is used. We need to hardcode the width here. The original layout params will
// be preserved for the correctness of distribution when buttons are added or removed into the
// group programmatically.
if (originalLayoutParams == null
&& getParent() instanceof MaterialButtonGroup
&& ((MaterialButtonGroup) getParent()).getButtonSizeChange() != null) {
originalLayoutParams = (LayoutParams) getLayoutParams();
LayoutParams newLayoutParams = new LayoutParams(originalLayoutParams);
newLayoutParams.width = (int) originalWidth;
setLayoutParams(newLayoutParams);
}
}
if (allowedWidthDecrease == UNSET) {
int localIconSizeAndPadding =
icon == null
? 0
: getIconPadding() + (iconSize == 0 ? icon.getIntrinsicWidth() : iconSize);
allowedWidthDecrease = getMeasuredWidth() - getTextLayoutWidth() - localIconSizeAndPadding;
}
if (originalPaddingStart == UNSET) {
originalPaddingStart = getPaddingStart();
}
if (originalPaddingEnd == UNSET) {
originalPaddingEnd = getPaddingEnd();
}
}
void recoverOriginalLayoutParams() {
if (originalLayoutParams != null) {
setLayoutParams(originalLayoutParams);
originalLayoutParams = null;
originalWidth = UNSET;
}
}
@Override
public void setWidth(@Px int pixels) {
originalWidth = UNSET;
super.setWidth(pixels);
}
@Override
protected void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
super.onTextChanged(charSequence, i, i1, i2);
updateIconPosition(getMeasuredWidth(), getMeasuredHeight());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (isUsingOriginalBackground()) {
MaterialShapeUtils.setParentAbsoluteElevation(
this, materialButtonHelper.getMaterialShapeDrawable());
}
isInHorizontalButtonGroup = isInHorizontalButtonGroup();
}
@Override
public void setElevation(float elevation) {
super.setElevation(elevation);
if (isUsingOriginalBackground()) {
materialButtonHelper.getMaterialShapeDrawable().setElevation(elevation);
}
}
@Override
public void refreshDrawableState() {
super.refreshDrawableState();
if (this.icon != null) {
final int[] state = getDrawableState();
boolean changed = icon.setState(state);
// Force the view to draw if icon state has changed.
if (changed) {
invalidate();
}
}
}
@Override
public void setTextAlignment(int textAlignment) {
super.setTextAlignment(textAlignment);
updateIconPosition(getMeasuredWidth(), getMeasuredHeight());
}
/**
* This method and {@link #getActualTextAlignment()} is modified from Android framework TextView's
* private method getLayoutAlignment(). Please note that the logic here assumes the actual text
* direction is the same as the layout direction, which is not always the case, especially when
* the text mixes different languages. However, this is probably the best we can do for now,
* unless we have a good way to detect the final text direction being used by TextView.
*/
private Alignment getGravityTextAlignment() {
switch (getGravity() & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK) {
case CENTER_HORIZONTAL:
return Alignment.ALIGN_CENTER;
case END:
case RIGHT:
return Alignment.ALIGN_OPPOSITE;
case START:
case LEFT:
default:
return Alignment.ALIGN_NORMAL;
}
}
/**
* This method and {@link #getGravityTextAlignment()} is modified from Android framework
* TextView's private method getLayoutAlignment(). Please note that the logic here assumes the
* actual text direction is the same as the layout direction, which is not always the case,
* especially when the text mixes different languages. However, this is probably the best we can
* do for now, unless we have a good way to detect the final text direction being used by
* TextView.
*/
private Alignment getActualTextAlignment() {
switch (getTextAlignment()) {
case TEXT_ALIGNMENT_GRAVITY:
return getGravityTextAlignment();
case TEXT_ALIGNMENT_CENTER:
return Alignment.ALIGN_CENTER;
case TEXT_ALIGNMENT_TEXT_END:
case TEXT_ALIGNMENT_VIEW_END:
return Alignment.ALIGN_OPPOSITE;
case TEXT_ALIGNMENT_TEXT_START:
case TEXT_ALIGNMENT_VIEW_START:
case TEXT_ALIGNMENT_INHERIT:
default:
return Alignment.ALIGN_NORMAL;
}
}
private void updateIconPosition(int buttonWidth, int buttonHeight) {
if (icon == null || getLayout() == null) {
return;
}
if (isIconStart() || isIconEnd()) {
iconTop = 0;
Alignment textAlignment = getActualTextAlignment();
if (iconGravity == ICON_GRAVITY_START
|| iconGravity == ICON_GRAVITY_END
|| (iconGravity == ICON_GRAVITY_TEXT_START && textAlignment == Alignment.ALIGN_NORMAL)
|| (iconGravity == ICON_GRAVITY_TEXT_END && textAlignment == Alignment.ALIGN_OPPOSITE)) {
iconLeft = 0;
updateIcon(/* needsIconReset= */ false);
return;
}
int localIconSize = iconSize == 0 ? icon.getIntrinsicWidth() : iconSize;
int availableWidth =
buttonWidth
- getTextLayoutWidth()
- getPaddingEnd()
- localIconSize
- iconPadding
- getPaddingStart();
int newIconLeft =
textAlignment == Alignment.ALIGN_CENTER ? availableWidth / 2 : availableWidth;
// Only flip the bound value if either isLayoutRTL() or iconGravity is textEnd, but not both
if (isLayoutRTL() != (iconGravity == ICON_GRAVITY_TEXT_END)) {
newIconLeft = -newIconLeft;
}
if (iconLeft != newIconLeft) {
iconLeft = newIconLeft;
updateIcon(/* needsIconReset= */ false);
}
} else if (isIconTop()) {
iconLeft = 0;
if (iconGravity == ICON_GRAVITY_TOP) {
iconTop = 0;
updateIcon(/* needsIconReset= */ false);
return;
}
int localIconSize = iconSize == 0 ? icon.getIntrinsicHeight() : iconSize;
int newIconTop =
max(
0, // Always put the icon on top if the content height is taller than the button.
(buttonHeight
- getTextHeight()
- getPaddingTop()
- localIconSize
- iconPadding
- getPaddingBottom())
/ 2);
if (iconTop != newIconTop) {
iconTop = newIconTop;
updateIcon(/* needsIconReset= */ false);
}
}
}
private int getTextLayoutWidth() {
float maxWidth = 0;
int lineCount = getLineCount();
for (int line = 0; line < lineCount; line++) {
maxWidth = max(maxWidth, getLayout().getLineWidth(line));
}
return (int) ceil(maxWidth);
}
private int getTextHeight() {
if (getLineCount() > 1) {
// If it's multi-line, return the internal text layout's height.
return getLayout().getHeight();
}
Paint textPaint = getPaint();
String buttonText = getText().toString();
if (getTransformationMethod() != null) {
// if text is transformed, add that transformation to to ensure correct calculation
// of icon padding.
buttonText = getTransformationMethod().getTransformation(buttonText, this).toString();
}
Rect bounds = new Rect();
textPaint.getTextBounds(buttonText, 0, buttonText.length(), bounds);
return min(bounds.height(), getLayout().getHeight());
}
private boolean isLayoutRTL() {
return getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
}
/**
* Update the button's background without changing the background state in {@link
* MaterialButtonHelper}. This should be used when we initially set the background drawable
* created by {@link MaterialButtonHelper}.
*
* @param background Background to set on this button
*/
void setInternalBackground(Drawable background) {
super.setBackgroundDrawable(background);
}
/**
* Sets the padding between the button icon and the button text, if icon is present.
*
* @param iconPadding Padding between the button icon and the button text, if icon is present.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconPadding
* @see #getIconPadding()
*/
public void setIconPadding(@Px int iconPadding) {
if (this.iconPadding != iconPadding) {
this.iconPadding = iconPadding;
setCompoundDrawablePadding(iconPadding);
}
}
/**
* Gets the padding between the button icon and the button text, if icon is present.
*
* @return Padding between the button icon and the button text, if icon is present.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconPadding
* @see #setIconPadding(int)
*/
@Attribute("com.google.android.material:iconPadding")
@Px
public int getIconPadding() {
return iconPadding;
}
/**
* Sets the width and height of the icon. Use 0 to use source Drawable size.
*
* @param iconSize new dimension for width and height of the icon in pixels.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconSize
* @see #getIconSize()
*/
public void setIconSize(@Px int iconSize) {
if (iconSize < 0) {
throw new IllegalArgumentException("iconSize cannot be less than 0");
}
if (this.iconSize != iconSize) {
this.iconSize = iconSize;
updateIcon(/* needsIconReset= */ true);
}
}
/**
* Returns the size of the icon if it was set.
*
* @return Returns the size of the icon if it was set in pixels, 0 otherwise.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconSize
* @see #setIconSize(int)
*/
@Px
public int getIconSize() {
return iconSize;
}
/**
* Sets the icon to show for this button. By default, this icon will be shown on the left side of
* the button.
*
* @param icon Drawable to use for the button's icon.
* @attr ref com.google.android.material.R.styleable#MaterialButton_icon
* @see #setIconResource(int)
* @see #getIcon()
*/
public void setIcon(@Nullable Drawable icon) {
if (this.icon != icon) {
this.icon = icon;
updateIcon(/* needsIconReset= */ true);
updateIconPosition(getMeasuredWidth(), getMeasuredHeight());
}
}
/**
* Sets the icon drawable resource to show for this button. By default, this icon will be shown on
* the left side of the button.
*
* @param iconResourceId Drawable resource ID to use for the button's icon.
* @attr ref com.google.android.material.R.styleable#MaterialButton_icon
* @see #setIcon(Drawable)
* @see #getIcon()
*/
public void setIconResource(@DrawableRes int iconResourceId) {
Drawable icon = null;
if (iconResourceId != 0) {
icon = AppCompatResources.getDrawable(getContext(), iconResourceId);
}
setIcon(icon);
}
/**
* Gets the icon shown for this button, if present.
*
* @return Icon shown for this button, if present.
* @attr ref com.google.android.material.R.styleable#MaterialButton_icon
* @see #setIcon(Drawable)
* @see #setIconResource(int)
*/
public Drawable getIcon() {
return icon;
}
/**
* Sets the tint list for the icon shown for this button.
*
* @param iconTint Tint list for the icon shown for this button.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconTint
* @see #setIconTintResource(int)
* @see #getIconTint()
*/
public void setIconTint(@Nullable ColorStateList iconTint) {
if (this.iconTint != iconTint) {
this.iconTint = iconTint;
updateIcon(/* needsIconReset= */ false);
}
}
/**
* Sets the tint list color resource for the icon shown for this button.
*
* @param iconTintResourceId Tint list color resource for the icon shown for this button.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconTint
* @see #setIconTint(ColorStateList)
* @see #getIconTint()
*/
public void setIconTintResource(@ColorRes int iconTintResourceId) {
setIconTint(AppCompatResources.getColorStateList(getContext(), iconTintResourceId));
}
/**
* Gets the tint list for the icon shown for this button.
*
* @return Tint list for the icon shown for this button.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconTint
* @see #setIconTint(ColorStateList)
* @see #setIconTintResource(int)
*/
public ColorStateList getIconTint() {
return iconTint;
}
/**
* Sets the tint mode for the icon shown for this button.
*
* @param iconTintMode Tint mode for the icon shown for this button.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconTintMode
* @see #getIconTintMode()
*/
public void setIconTintMode(Mode iconTintMode) {
if (this.iconTintMode != iconTintMode) {
this.iconTintMode = iconTintMode;
updateIcon(/* needsIconReset= */ false);
}
}
/**
* Gets the tint mode for the icon shown for this button.
*
* @return Tint mode for the icon shown for this button.
* @attr ref com.google.android.material.R.styleable#MaterialButton_iconTintMode
* @see #setIconTintMode(Mode)
*/
public Mode getIconTintMode() {
return iconTintMode;
}
/**
* Updates the icon, icon tint, and icon tint mode for this button.
*
* @param needsIconReset Whether to force the drawable to be set
*/
private void updateIcon(boolean needsIconReset) {
if (icon != null) {
icon = DrawableCompat.wrap(icon).mutate();
icon.setTintList(iconTint);
if (iconTintMode != null) {
icon.setTintMode(iconTintMode);
}
int width = iconSize != 0 ? iconSize : icon.getIntrinsicWidth();
int height = iconSize != 0 ? iconSize : icon.getIntrinsicHeight();
icon.setBounds(iconLeft, iconTop, iconLeft + width, iconTop + height);
icon.setVisible(true, needsIconReset);
}
// Forced icon update
if (needsIconReset) {
resetIconDrawable();
return;
}
// Otherwise only update if the icon or the position has changed
Drawable[] existingDrawables = getCompoundDrawablesRelative();
Drawable drawableStart = existingDrawables[0];
Drawable drawableTop = existingDrawables[1];
Drawable drawableEnd = existingDrawables[2];
boolean hasIconChanged =
(isIconStart() && drawableStart != icon)
|| (isIconEnd() && drawableEnd != icon)
|| (isIconTop() && drawableTop != icon);
if (hasIconChanged) {
resetIconDrawable();
}
}
private void resetIconDrawable() {
if (isIconStart()) {
setCompoundDrawablesRelative(icon, null, null, null);
} else if (isIconEnd()) {