一、selector的具体使用方法
Android中的Selector主要是用来改变ListView和Button控件的默认背景。其使用方法可以按一下步骤来设计:
(以在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文件后,在没有添加任何属性时其内部代码结构为:
- <?xml version="1.0" encoding="utf-8" ?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
-
- </selector>
下面就可以根据项目需求,在其内部定义为自己想要的样式了,主要属性如下:
- <?xml version="1.0" encoding="utf-8" ?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
- <!-- 默认时的背景图片-->
- <item android:drawable="@drawable/pic1" />
- <!-- 没有焦点时的背景图片 -->
- <item android:state_window_focused="false"
- android:drawable="@drawable/pic1" />
- <!-- 非触摸模式下获得焦点并单击时的背景图片 -->
- <item android:state_focused="true" android:state_pressed="true" android:drawable= "@drawable/pic2" />
- <!-- 触摸模式下单击时的背景图片-->
- <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pic3" />
- <!--选中时的图片背景-->
- <item android:state_selected="true" android:drawable="@drawable/pic4" />
- <!--获得焦点时的图片背景-->
- <item android:state_focused="true" android:drawable="@drawable/pic5" />
- </selector>
3.引用mylist_view.xml文件
三种方法可以来引用刚才创建的文件:
(1)在ListView中添加如下属性代码
- android:listSelector="@drawable/mylist_view"
(2)在ListView的item界面中添加如下属性代码
- android:background="@drawable/mylist_view"
(3)利用JAVA代码直接编写
- Drawable drawable = getResources().getDrawable(R.drawable.mylist_view);
- listView.setSelector(drawable);
为了防止列表拉黑的情况发生,需要在ListView中添加以下的属性代码
- android:cacheColorHint="@android:color/transparent"
二、属性介绍:
android:state_pressed:Boolean、“true”表示按下状态使用(例如按钮按下)、“false”表示非按下状态使用
android:state_focused:Boolean、“true”表示聚焦状态使用(例如使用滚动球/D-pad聚焦Button);“false”表示非聚焦状态使用
android:state_selected:Boolean、“true”表示选中状态使用(例如Tab 打开);“false” 表示非选中状态使用
android:state_checkable:Boolean、“true”表示可勾选状态时使用;“false”表示非可 勾选状态使用、(只对能切换可勾选—非可勾选的构件有用、)
android:state_checked:Boolean、“true”表示勾选状态使用;“false”表示非勾选状态使用
android:state_enabled:Boolean、“true”表示可用状态使用(能接收触摸/点击事件)、“false”表示不可用状态使用
android:window_focused:Boolean、“true”表示应用程序窗口有焦点时使用(应用程序在前台)、“false”表示无焦点时使用(例如Notification栏拉 下或对话框显示)
由于本人初写博客,写的不好的地方还请大家能批评指正,希望能和大家相互学习、相互交流、共同成长。