Android inflate XML selector to be used in StateListDrawable

800 views Asked by At

Is it possible to inflate a selector created in XML to be used by StateListDrawable programmatically?

I found that StateListDrawable has an inflate method, but I don't find usage examples.

That would be nice to avoid made this:

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);

Does somebody know if it is possible and provide an example?

Thanks in advance.

1

There are 1 answers

0
tynn On

It's possible of course. You'll find more information to every other drawable available with the documentation for State list. I hope this answer comes in handy for anyone even six years later.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/normal" />
</selector>