Reputation: 121
Is there any way 'state' can be changed programmatically for StateListDrawable?
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_shortAnimTime">
<item
android:state_checked="true"
android:drawable="@drawable/picker_circle_selected"/>
<item
android:state_checked="false"
android:drawable="@drawable/picker_circle_today" />
StateListDrawable backgroundDrawable = (StateListDrawable) ContextCompat.getDrawable(getContext(), R.drawable.picker_selector);
I have tried ....."selectDrawable(int index)
" and "addState()
" on StateListDrawable
. But nothing worked.
By default "state_checked = false
" drawable gets displayed. When user taps on this drawable it changes it's state to "state_checked = true
". Is there any way it's state can be changed programmatically?
Upvotes: 0
Views: 2039
Reputation: 910
Try this
// call your view
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(yourlayout, viewGroup, false);
ColorDrawable colorDrawableSelected = new ColorDrawable(context.getResources().getColor(R.color.white));
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[]{android.R.attr.state_selected}, colorDrawableSelected);
stateListDrawable.addState(StateSet.WILD_CARD, null);// set the StateListDrawable as background of the view
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
view.setBackgroundDrawable(stateListDrawable);
} else {
view.setBackground(stateListDrawable);
then call like this: view.setSelected etc
Upvotes: 3
Reputation: 6073
you can change the color of the stat using LayerDrawable
DrawableContainerState drawableContainerState = (DrawableContainerState) backgroundDrawable.getConstantState();
Drawable[] children = drawableContainerState.getChildren();
LayerDrawable selectedItem = (LayerDrawable) children[0];
LayerDrawable unselectedItem = (LayerDrawable) children[1];
selectedItem.setColor(Color.Black); // changing to black color
Upvotes: 0