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
- Android中的选择器selector的写法解析及不起作用原因
- android中的选择器selector
- android中Selector中的相关属性及配置写法
- 关于Android的selector背景选择器的配置不起作用的问题
- Android中的Selector 背景选择器
- Android中的背景选择器selector
- Android中的Selector-背景选择器
- ImageView设置selector不起作用原因
- android的selector,背景选择器
- android的selector,背景选择器
- Android的selector,背景选择器
- Android 的 selector--背景选择器
- Android的selector,背景选择器
- Android的selector,背景选择器
- Android的selector,背景选择器
- android的selector,背景选择器
- android的selector,背景选择器
- android的selector,背景选择器
- HDU 1856 More is better
- Android:Layout_weight的深刻理解
- oracle 条件:1=1或1=0,动态添加条件
- ubuntu如何完全卸载和安装 Java及android环境
- MyEclipse+Struts+Spring+Hibernate 环境配置
- Android中的选择器selector的写法解析及不起作用原因
- 数据库复习1——数据库体系结构和关系系统
- Announce of Looksery Cup 2015-B. Looksery Party
- Integer.toHexString(int)得到byte类型的十六进制字符串形式
- HDU 5266 HDU 2586 LCA问题
- silicon_status用这个标志来控制灯的状态
- 金蝶条码标签打印无缝对接金蝶K3接口金蝶KIS条码标签打印金蝶单据打印条码标签打印
- Qt学习笔记--编程技巧总结
- SQL结构化查询语言及Mysql基本操作