10
10
import android .content .Context ;
11
11
import android .content .res .ColorStateList ;
12
12
import android .graphics .PorterDuff ;
13
+ import android .graphics .drawable .ColorDrawable ;
13
14
import android .graphics .drawable .Drawable ;
14
15
import android .graphics .drawable .RippleDrawable ;
15
16
import android .os .Build ;
17
+
16
18
import androidx .annotation .Nullable ;
17
19
import androidx .appcompat .widget .SwitchCompat ;
18
20
@@ -48,6 +50,18 @@ public void setChecked(boolean checked) {
48
50
}
49
51
}
50
52
53
+ @ Override
54
+ public void setBackgroundColor (int color ) {
55
+ // Ensure RippleDrawable is preserved for >=21
56
+ if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .LOLLIPOP ) {
57
+ setBackground (
58
+ new RippleDrawable (
59
+ createRippleDrawableColorStateList (color ), new ColorDrawable (color ), null ));
60
+ } else {
61
+ super .setBackgroundColor (color );
62
+ }
63
+ }
64
+
51
65
void setColor (Drawable drawable , @ Nullable Integer color ) {
52
66
if (color == null ) {
53
67
drawable .clearColorFilter ();
@@ -63,14 +77,10 @@ public void setTrackColor(@Nullable Integer color) {
63
77
public void setThumbColor (@ Nullable Integer color ) {
64
78
setColor (super .getThumbDrawable (), color );
65
79
66
- // Set the ripple color with thumb color if >= LOLLIPOP
67
- if (Build .VERSION .SDK_INT >= Build .VERSION_CODES .LOLLIPOP ) {
68
- RippleDrawable ripple = (RippleDrawable ) super .getBackground ();
69
- ColorStateList customColorState =
70
- new ColorStateList (
71
- new int [][] {new int [] {android .R .attr .state_pressed }}, new int [] {color });
72
-
73
- ripple .setColor (customColorState );
80
+ // Set the ripple color if background is instance of RippleDrawable
81
+ if (super .getBackground () instanceof RippleDrawable && color != null ) {
82
+ ColorStateList customColorState = createRippleDrawableColorStateList (color );
83
+ ((RippleDrawable ) super .getBackground ()).setColor (customColorState );
74
84
}
75
85
}
76
86
@@ -113,4 +123,9 @@ private void setTrackColor(boolean checked) {
113
123
setTrackColor (currentTrackColor );
114
124
}
115
125
}
126
+
127
+ private ColorStateList createRippleDrawableColorStateList (@ Nullable Integer color ) {
128
+ return new ColorStateList (
129
+ new int [][] {new int [] {android .R .attr .state_pressed }}, new int [] {color });
130
+ }
116
131
}
0 commit comments