您的位置:首页 > 移动开发 > Android开发

Android Selector 背景选择器

2017-03-01 16:10 288 查看
Android Selector 背景选择器
效果图



Android Selector 背景选择器

selector中文的意思选择器,在Android中常常用来作组件的背景,这样做的好处是省去了用代码控制实现组件在不同状态下不同的背景颜色或图片的变换。使用十分方便。

selector的定义:

selector就是状态列表(StateList), 它分为两种,一种Color-Selector 和Drawable-Selector。

Color-Selector:

color-selector 就是颜色状态列表,可以跟color一样使用,颜色会随着组件的状态而改变。文件的位置存储于
/res/color/filename.xml
1
1

语法:
android:color="hex_color"
//颜色值,#RGB,$ARGB,#RRGGBB,#AARRGGBB

android:state_pressed="true"
| "false"//是否触摸

android:state_focused="true"
| "false"//是否获得焦点

android:state_selected="true"
| "false"//是否被状态

android:state_checkable="true"
| "false"//是否可选

android:state_checked="true"
| "false"//是否选中

android:state_enabled="true"
| "false"//是否可用

android:state_window_focused="true"
| "false"//是否窗口聚焦

使用xml文件:
1.方法一:在listview中配置android:listSelector="@drawable/xxx"
或者在listview的item中添加属性android:background="@drawable/xxx"

2.方法二:
  Drawable drawable = getResources().getDrawable(R.drawable.xxx);  
  ListView.setSelector(drawable);
但是这样会出现列表有时候为黑的情况,需要加上:android:cacheColorHint="@android:color/transparent"使其透明。

代码演示
1.在/res/color/文件夹下新建selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--shift+control+/-->
<!--按下-->
<item android:state_pressed="true"
android:color="#C0C0C0"/>
<!--默认-->
<item android:color="#000000"/>
</selector>


2.主布局文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.shape.MainActivity">

<Button
android:id="@+id/button"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@drawable/shape"
android:text="颜色选择器"
android:textColor="@color/selector"/>
</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android Selector 背景选