user123321
user123321

Reputation: 12783

Drawable.setState() How do I control the specific state of the drawable?

I have a drawable like this:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
      android:state_window_focused="true"
      android:drawable="@drawable/seek_thumb_pressed" />

<item android:state_focused="true"
      android:state_window_focused="true"
      android:drawable="@drawable/seek_thumb_selected" />

<item android:state_selected="true"
      android:state_window_focused="true"
      android:drawable="@drawable/seek_thumb_selected" />

<item android:drawable="@drawable/seek_thumb_normal" />

In code, how do I set my Drawable's specific state? I'd like to set it to the state_pressed=true state.

Upvotes: 19

Views: 21927

Answers (2)

nicholastmosher
nicholastmosher

Reputation: 161

Don't have enough points to comment, so this is just an addition to what android-developer said. For certain states such as state_enabled, there is no obvious way to set the opposite value of that state (e.g. there is no state_disabled). To indicate a negative or opposite state, simply pass the negative value of the resource for that state.

int[] state = new int[] {-android.R.attr.state_enabled}; //Essentially state_disabled

Then pass that integer array into the setState() method as usual.

minThumb.setState(state);

Upvotes: 12

user123321
user123321

Reputation: 12783

Got it. A comment from here helped: Android : How to update the selector(StateListDrawable) programmatically

So Drawable.setState() takes an array in integers. These integers represent the state of the drawable. You can pass any ints you want. Once the ints pass in match a an "item" from the state list drawables the drawable draws in that state.

It makes more sense in code:

int[] state = new int[] {android.R.attr.state_window_focused, android.R.attr.state_focused};
minThumb.setState(state);

Notice that my state list drawable has both the state_pressed="true" and android:state_window_focused="true". So I have to pass both of those int values to setState. When I want to clear it, I just minThumb.setState(new int[]{});

Upvotes: 31

Related Questions