本文实例讲述了Android编程中selector背景选择器用法。分享给大家供大家参考,具体如下:
在Android开发过程中,经常对某一View的背景在不同的状态下,设置不同的背景,增强用户体验。如果按钮,在按下时,背景变化,如果在代码中动态设置,相对比较麻烦。Android为我们提供了selector背景选择器可以非常方便的解决这一问题。
[b]Selector的结构描述:[/b]
1.android:state_pressed="true/false"
true:表示按下状态下使用,false:表示非按下状态下使用。
2.android:state_focused="true/false"
ture:表示聚焦状态使用(例如使用滚动球/D-pad聚焦Button),false:表示非聚集状态下使用。
3.android:state_selected="true/false"
true:表示被选中状态下使用,false:表示非选中下使用
4.android:state_active="true/false"
true:表示可勾选状态时使用,false:表示不可勾选状态下使用
5. android:state_checkable="true/false"
true:表示勾选状态下使用,false:表示非勾选状态使用
6.android:state_checked="true/false"
true:表示勾选状态下使用,false:表示非勾选状态使用
7. android:state_enabled="true/false"
true:表示可用状态使用(能接收触摸/点击事件),false:表示不可用状态使用
8. android:state_window_focused="true/false"
true:表示应用程序窗口有焦点时使用(应用程序在前台),false:表示无焦点时使用
9.android:background
设置背景图片 模拟灯开启关闭
在drawable目录先新建bg_button.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/r7"></item>
<item android:state_checked="false" android:drawable="@drawable/r7b"></item>
</selector>
为了方便点击查看效果 使用CheckBox组件
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@null"
android:textSize="15sp"
android:textColor="#EE2C2C"
android:drawableTop="@drawable/bg_button"
android:text="灯"/>
效果:
[img]http://files.jb51.net/file_images/article/201601/2016118155528285.png?2016018155559[/img]
[img]http://files.jb51.net/file_images/article/201601/2016118155603067.png?2016018155632[/img]
更多关于Android开发相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/410.htm]Android开发入门与进阶教程[/url]》
希望本文所述对大家Android程序设计有所帮助。