Android中的Selector

来源:互联网 发布:php微信开发教程视频 编辑:程序博客网 时间:2024/06/05 09:58

Android中的Selector主要是用来改变ListView和Button控件的默认背景。


android:drawable 放一个drawable资源
android:state_pressed 是否按下,如一个按钮触摸或者点击。
android:state_focused 是否取得焦点,比如用户选择了一个文本框。
android:state_hovered 光标是否悬停,通常与focused state相同,它是4.0的新特性
android:state_selected 被选中,它与focus state并不完全一样,如一个list view 被选中的时候,它里面的各个子组件可能通过方向键,被选中了。
android:state_checkable 组件是否能被check。如:RadioButton是可以被check的。
android:state_checked 被checked了,如:一个RadioButton可以被check了。
android:state_enabled 能够接受触摸或者点击事件
android:state_activated 被激活
android:state_window_focused 应用程序是否在前台,当有通知栏被拉下来或者一个对话框弹出的时候应用程序就不在前台


其使用方法可以按一下步骤来设计:


(以在mylist_view.xml为例)


1.创建mylist_view.xml文件

首先在res目录下新建drawable文件夹,再在新建的drawable文件夹中新建mylist_view.xml,其目录结构为:res/drawable/mylist_view.xml。


2.根据具体需求编辑mylist_view.xml文件

新建mylist_view.xml文件后,在没有添加任何属性时其内部代码结构为:

[html] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8" ?>     
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">   
  3.    
  4. </selector>  

下面就可以根据项目需求,在其内部定义为自己想要的样式了,主要属性如下:

[html] view plaincopyprint?
  1. <?xml version="1.0" encoding="utf-8" ?>     
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">   
  3. <!-- 默认时的背景图片-->    
  4.   <item android:drawable="@drawable/pic1" />      
  5. <!-- 没有焦点时的背景图片 -->    
  6.   <item android:state_window_focused="false"     
  7.         android:drawable="@drawable/pic1" />     
  8. <!-- 非触摸模式下获得焦点并单击时的背景图片 -->    
  9.   <item android:state_focused="true" android:state_pressed="true"   android:drawable"@drawable/pic2" />   
  10. <!-- 触摸模式下单击时的背景图片-->    
  11. <item android:state_focused="false" android:state_pressed="true"   android:drawable="@drawable/pic3" />    
  12. <!--选中时的图片背景-->    
  13.   <item android:state_selected="true"   android:drawable="@drawable/pic4" />     
  14. <!--获得焦点时的图片背景-->    
  15.   <item android:state_focused="true"   android:drawable="@drawable/pic5" />     
  16. </selector>  

3.引用mylist_view.xml文件


三种方法可以来引用刚才创建的文件:

(1)在ListView中添加如下属性代码

[html] view plaincopyprint?
  1. android:listSelector="@drawable/mylist_view"  

(2)在ListView的item界面中添加如下属性代码

[html] view plaincopyprint?
  1. android:background="@drawable/mylist_view"  

(3)利用JAVA代码直接编写

[java] view plaincopyprint?
  1. Drawable drawable = getResources().getDrawable(R.drawable.mylist_view);   
  2. listView.setSelector(drawable);  

为了防止列表拉黑的情况发生,需要在ListView中添加以下的属性代码

[html] view plaincopyprint?
  1. android:cacheColorHint="@android:color/transparent"  

属性介绍:

android:state_selected选中

android:state_focused获得焦点

android:state_pressed点击

android:state_enabled设置是否响应事件,指所有事件

0 0
原创粉丝点击