简体   繁体   中英

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

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").

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM