What is a StateListDrawable?

Let’s say you have a View like a Button. You want to set a background to the button, you use

But what can you do when you want to set a different background while the button is pressed or maybe when the button is not focused anymore.

My first solution for this problem was to extend a View class and override the setPressed() method to set the specific drawables.

In the fragment where i used the button I then called the method inside a onTouchListener()

This process can be simplified with StateListDrawables.

How do they work?

You just create a new xml file e.g. button_selector.xml inside your drawables folder.

This selector will do the same like my custom view. The drawable from the item with android:state_pressed=”true” will be used when the button is pressed. You can use StateListDrawables also for other attributes like textColor. Android will use the item without a state as the default one.

Here is a list of all states that are available:

How to apply the selector?

You just use it like any other drawable inside your layout file

Android will set the attributes when the view is in the specified state

And that’s it. Now you can apply this selector to any of your Views.

Example project and ressources

Android Documentation StateList