I have an ImageView that has a drawable image resource set to a selector. How do I programmatically access the selector and change the images of the highlighted and non-highlighted state?
Here is a code of selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/iconSelector">
<!-- pressed -->
<item android:state_pressed="true" android:drawable="@drawable/btn_icon_hl" />
<!-- focused -->
<item android:state_focused="true" android:drawable="@drawable/btn_icon_hl" />
<!-- default -->
<item android:drawable="@drawable/btn_icon" />
</selector>
I want to be able to replace btn_icon_hl
and btn_icon
with other images.
As far as I've been able to find (I've tried doing something similar myself), there's no way to modify a single state after the StateListDrawable has already been defined. You can, however, define a NEW one through code:
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},
getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },
getResources().getDrawable(R.drawable.normal));
imageView.setImageDrawable(states);
And you could just keep two of them on hand, or create a different one as you need it.