android背景设置报错 <item> tag requires a 'drawable' attribute or child tag defining a drawable

今天本来只是想实现一个简单的按下ImageButton背景变颜色的功能,结果碰到 tag requires a 'drawable' attribute or child tag defining a drawable的错误。这句话的意思很简单,就是说item标签下需要drawable属性。在逛了无数国内论坛无果后,我尝试进了一个英文网站,结果如醍醐灌顶,深深的感觉到国内和国外的差距。

The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:

你不能将颜色选择器用在background上,应该使用drawable selector,所以你应该这样修改(假设文件名为selector.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@drawable/selected_state" />
</selector>awable/selected_state"/>
</selector>


You would also need to move that resource to the drawable directory where it would make more sense since it's not a color selector per se.

Then you would have to create the res/drawable/selected_state.xml file like this:


同时你也要将selected_state.xml放在drawable目录下而不是color目录,然后这样定义res/drawable/selected_state.xml:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@color/semitransparent_white" />
</shape>

and finally, you would use it like this:

最后在imageView中我们这样定义background:

android:background="@drawable/selector"

其实这种方法将selector和颜色的定义分开了 我们可以将selector和shape的定义放在一起:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#F1F1F1"/>
        </shape>
    </item>
    <item android:state_selected="true">
        <shape>
            <solid android:color="#F1F1F1"/>
        </shape>           
    </item>
</selector>