首页 > 代码库 > android 控件选择器Selector
android 控件选择器Selector
以Button为例:
一般Button有2个状态,按下和正常状态
1.在res下新建drawable文件夹,用以存放自己的Drawable文件
2.在drawable文件夹下新建按下和正常状态shape文件(是图片资源,则略过此步骤)
3.新建Button背景Selector文件
4.为Button的backgroud指定Drawable
代码:
button_noraml.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke
android:width="1dp"
android:color="#00FF00" />
<gradient
android:angle="270"
android:endColor="#e5e5e5"
android:startColor="#DCDCDC" />
</shape>
————————————————————————————————————————————————————
button_press.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 描边 -->
<stroke
android:width="1dp"
android:color="#00FF00" />
<!-- 渐变 -->
<gradient
android:angle="270"
android:endColor="#00FF00"
android:startColor="#90EE90" />
</shape>
————————————————————————————————————————————————————
button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 按下状态的Drawable -->
<item android:drawable="@drawable/button_press" android:state_pressed="true"></item>
<!-- 正常状态的Drawable -->
<item android:drawable="@drawable/button_noraml"></item>
</selector>
————————————————————————————————————————————————————
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="30dp"
android:background="@drawable/button_selector"
android:text="Button" />
</LinearLayout>