I have a toggle button with 3 custom states : - Pressed - Checked - Realeased
I'm using the following xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/togglebutton_color_custom_ripple" android:state_pressed="true" />
<item android:drawable="@drawable/togglebutton_color_custom_checked" android:state_checked="true"/>
<item android:drawable="@drawable/togglebutton_color_custom_unchecked" />
</selector>
I'd like to change the background color for each state of this button programmatically. I tried to use the following code:
StateListDrawable drawable = (StateListDrawable) mToggleButtonCustom.getBackground();
DrawableContainer.DrawableContainerState dcs = (DrawableContainer.DrawableContainerState) drawable.getConstantState();
Drawable[] drawableItems = dcs.getChildren();
GradientDrawable gradientDrawablePressed = (GradientDrawable) drawableItems[0];
GradientDrawable gradientDrawableChecked = (GradientDrawable) drawableItems[1];
GradientDrawable gradientDrawableUnChecked = (GradientDrawable) drawableItems[2];
gradientDrawablePressed.setColor(Color.parseColor(color));
gradientDrawableChecked.setColor(Color.parseColor(color));
gradientDrawableUnChecked.setColor(Color.parseColor(color));
It works fine for 'checked' and 'released' state because I use classic shapes in XML but it doesn't work for 'pressed' state because I use the following Ripple effect in my XML:
<?xml version="1.0" encoding="utf-8"?>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/ripple">
<item>
<shape android:shape="oval">
<size
android:height="@dimen/togglebutton_size"
android:width="@dimen/togglebutton_size" />
<solid android:color="@color/blue_vs"/>
<stroke android:width="@dimen/togglebutton_button_stroke"
android:color="@color/white" />
</shape>
</item>
</ripple>
It'd seem I have to use 'RippleDrawable' in my code but I don't really understand how, I juste want to change the solid background color, not the ripple color or stroke.
Thanks