Android中selector背景选择器

来源:互联网 发布:redis和mysql结合使用 编辑:程序博客网 时间:2024/04/30 08:22

转至:http://blog.csdn.net/forsta/article/details/26148403

在Android开发过程中,经常对某一View的背景在不同的状态下,设置不同的背景,增强用户体验。如果按钮,在按下时,背景变化,如果在代码中动态设置,相对比较麻烦。Android为我们提供了selector背景选择器可以非常方便的解决这一问题。

Selector的结构描述:

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

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:state_checked="true" android:drawable="@drawable/r7"></item>  
  4.     <item android:state_checked="false" android:drawable="@drawable/r7b"></item>  
  5. </selector>  

为了方便点击查看效果 使用CheckBox组件

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <CheckBox   
  2.       android:layout_width="wrap_content"  
  3.       android:layout_height="wrap_content"  
  4.       android:button="@null"  
  5.       android:textSize="15sp"  
  6.       android:textColor="#EE2C2C"  
  7.       android:drawableTop="@drawable/bg_button"  
  8.       android:text="灯"/>  

效果:

0 0
原创粉丝点击