Android中的选择器selector的写法解析及不起作用原因

来源:互联网 发布:淘宝好评返现处罚规则 编辑:程序博客网 时间:2024/06/05 10:31

selector能为我们快速定义各种状态下控件的字体或背景颜色,非常方便快捷,可是有时候我们写对了状态定义却不起效果,比如

<selector>    <!-- 无焦点的时候 -->    <item android:state_focused="false" android:color="红色"><!-- 实际中颜色不能这么写,要写#ff0000,这里为了看起来更加清晰,才这么写 -->    <!-- 有焦点的时候 -->    <item android:state_focused="true" android:color="黄色">    <!-- 非触摸模式(有焦点有点击)按下的时候 -->    <item android:state_pressed="true" android:state_focused="true" android:color="黑色"></selector>

运行之后会发现,有焦点的时候,是黄色(√),无焦点的时候是红色(√),点击的时候还是黄色(×)。

原因是,在第二个item设置有焦点的时候,已经把所有的情况都包含了,所以第三个item其实是不起作用的(eclipse会提醒黄色三角形:This item is unreachable because a previous item(item #2) is a more general match than this one)。

所以只要给第二个item加一个分支和第三个区分开来就可以。
即把上述代码改为

<selector>    <!-- 无焦点的时候 -->    <item android:state_focused="false" android:color="红色">    <!-- 有焦点无点击的时候 -->    <item android:state_focused="true" android:state_pressed="false" android:color="黄色">    <!-- 非触摸模式(有焦点有点击)按下的时候 -->    <item android:state_focused="true" android:state_pressed="true" android:color="黑色"></selector>

其实在xml里面顺序是有影响的,细节(detail)的放在整体(general)的后面会被整体所影响,但是如果放在它前面,就能够正常实现所写状态了。
所以还有一种改动更小的方法,即将item3放在item2前面

<selector>    <!-- 无焦点的时候 -->    <item android:state_focused="false" android:color="红色">    <!-- 非触摸模式(有焦点有点击)按下的时候 -->    <item android:state_pressed="true" android:state_focused="true" android:color="黑色">    <!-- 有焦点的时候 -->    <item android:state_focused="true" android:color="黄色"></selector>

附:常用样式

<selector>    <!-- 非触摸模式(有焦点有点击)按下的时候 -->    <item android:state_pressed="true" android:state_focused="true">    <!-- 触摸模式(无焦点有点击)按下的时候 -->    <item android:state_pressed="true" android:state_focused="false">    <!-- 有焦点的时候 -->    <item android:state_focused="true" >    <!-- 无焦点的时候 -->    <item android:state_focused="false" >    <!-- selected状态选中的时候 -->    <item android:state_selected="true">    <!-- checked状态选中的时候 -->    <item android:state_checked="true"></selector>

如果这篇博文有帮助到你,或者有什么错误提醒,建议改进的地方,欢迎给我留言。

1 0
原创粉丝点击