Replace selector images programmatically

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.

Leave a Comment