Addev
Addev

Reputation: 32243

Drawable states with colors (not drawables)

I want to give a view a background color with the following behavior: The background should be green while the view is pressed and black otherwise.

This selector works

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/green" android:state_pressed="true"/>
    <item android:drawable="@drawable/black"/>

</selector>

But for doing that I need to create a nine patch 3x3 file with the desired color. How can I reach the same behavior but giving the color code rather a drawable?

Thanks

Upvotes: 9

Views: 3974

Answers (2)

goto10
goto10

Reputation: 4370

Just use the color. From the docs:

A color resource can also be used as a drawable in XML. For example, when creating a state list drawable, you can reference a color resource for the android:drawable attribute (android:drawable="@color/green").

Upvotes: 14

Bobbake4
Bobbake4

Reputation: 24857

You can do this with a color state list, they are the same thing as the drawable state list in your code posted. You can also create a shape drawable and still use the drawable code used above.

Upvotes: 4

Related Questions