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

android背景设置报错 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值