19

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.

2 Answers 2

31

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[]{});

3
  • What if the current view doesn't have a background, and need to notify its children about its state (because they have android:duplicateParentState="true" ) ? how would you change the state of the view ? Jul 2, 2014 at 10:01
  • 8
    "It makes more sense in code" - nothing related to drawable states makes sense...
    – milosmns
    Dec 5, 2015 at 22:37
  • What is minThumb? Mar 19, 2020 at 14:35
12

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);
1
  • I did not test that but for me just not having state_enabled made it use the disabled color.
    – Slion
    Oct 2, 2023 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.