Skip to content

Commit 50d2993

Browse files
committed
Ensure RippleDrawable background for ReactSwitch
1 parent ebe5417 commit 50d2993

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

ReactAndroid/src/main/java/com/facebook/react/views/switchview/ReactSwitch.java

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
import android.content.Context;
1111
import android.content.res.ColorStateList;
1212
import android.graphics.PorterDuff;
13+
import android.graphics.drawable.ColorDrawable;
1314
import android.graphics.drawable.Drawable;
1415
import android.graphics.drawable.RippleDrawable;
1516
import android.os.Build;
17+
1618
import androidx.annotation.Nullable;
1719
import androidx.appcompat.widget.SwitchCompat;
1820

@@ -48,6 +50,18 @@ public void setChecked(boolean checked) {
4850
}
4951
}
5052

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+
5165
void setColor(Drawable drawable, @Nullable Integer color) {
5266
if (color == null) {
5367
drawable.clearColorFilter();
@@ -63,14 +77,10 @@ public void setTrackColor(@Nullable Integer color) {
6377
public void setThumbColor(@Nullable Integer color) {
6478
setColor(super.getThumbDrawable(), color);
6579

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);
7484
}
7585
}
7686

@@ -113,4 +123,9 @@ private void setTrackColor(boolean checked) {
113123
setTrackColor(currentTrackColor);
114124
}
115125
}
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+
}
116131
}

0 commit comments

Comments
 (0)