<item> tag requires a 'drawable' attribute or child tag defining a drawable错误,感叹国内和国外的水平的差距

今天本来只是想实现一个简单的单击按钮变颜色的功能,结果碰到<item> tag requires a 'drawable' attribute or child tag defining a drawable的错误。这句话的意思很简单,就是说item标签下需要drawable属性。因为本人刚接触android,只有求助google了。答案千奇百怪,有人还建议将selector的xml文件放到layout文件夹中。我很佩服国内同胞谨记毛主席的教导“实践是检验真理的唯一标准”。勇于尝试,不过不懂原理而盲目的去折腾效率是很低的。在逛了无数国内论坛无果后,我尝试进了一个英文网站,结果如醍醐灌顶,深深的感觉到国内和国外的差距。

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:

<?xml version="1.0" encoding="utf-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
   
<item
       
android:state_pressed="true"
       
android:drawable="@drawable/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:

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

and finally, you would use it like this:

android:background="@drawable/selector"

Note: the reason why the OP was getting an image resource drawn is probably because he tried to just reference

his resource that was still in the color directory but using @drawable so he ended up with an ID collision, selecting the wrong resource.

其实问题很简单,按钮的背景图片不支持颜色选择器,只支持drawable选择器,我用的是颜色选择器,所以就产生了上述错误。

解决方法:

在drawable文件夹中根据需要新建shape类型的drawable,指定shape为矩形并指定颜色

然后在drawable文件夹下新建一个drawable选择器,在selector中对不同的事件引用上面建好的drawable

注意:drawable资源文件必须先定义(新建),才能使用。新建完一个drawable资源文件后,程序会在R.java中的drawable类中新建一个public static final int类型的成员变量

这个drawable类和成员变量都是static final修饰的,也就是说是不可改变的。

 

这些资源在layout文件中通过@drawable/“R.java文件中drawable类中对应的成员变量的名称”来使用,在java代码中通过R.drawable.“R.java文件中drawable类中对应的成员变量的名称”来使用。

posted @ 2012-05-22 18:57  IT_chen  阅读(6887)  评论(0)    收藏  举报