1. 背景選取器(位於res/drawable/,使用方法:android:background=”@drawable/XXX”)
<?xml version="1.0" encoding="utf-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<itemandroid:drawable="@drawable/login_blue_pressed" android:state_pressed="true"/>
<itemandroid:drawable="@drawable/login_blue_pressed"android:state_focused="true"/>
<itemandroid:drawable="@drawable/login_blue_normal" />
</selector>
2. 文字顏色選取器(位於res/color/,使用方法:android:textColor=”@color/XXX”)
<?xml version="1.0" encoding="utf-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<itemandroid:color="#ffffff" android:state_pressed="true"/>
<itemandroid:color="#ffffff" android:state_focused="true"/>
<item android:color="#000000"/>
</selector>
注意:在res/drawable/XXX.xml智能提示時沒有android:color,同理在res/color/XXX.xml智能提示時沒有android:drawable。
3.背景漸層器(位於res/color/或res/drawable/)
res/drawable/selector1.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:Android="http://schemas.android.com/apk/res/android">
<itemAndroid:state_selected="true">
<shape>
<gradientAndroid:angle="270" android:endColor="#99BD4C"
android:startColor="#A5D245" />
<sizeAndroid:height="60dp" android:width="320dp" />
<cornersandroid:radius="8dp" />
</shape>
</item>
<itemAndroid:state_pressed="true">
<shape>
<gradientAndroid:angle="270" android:endColor="#99BD4C"
android:startColor="#A5D245"/>
<sizeAndroid:height="60dp" android:width="320dp" />
<cornersandroid:radius="8dp" />
</shape>
</item>
<item>
<shape>
<gradientAndroid:angle="270" android:endColor="#A8C3B0"
android:startColor="#C6CFCE" />
<sizeAndroid:height="60dp" android:width="320dp" />
<cornersandroid:radius="8dp" />
</shape>
</item>
</selector>
layout/main.xml:
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="50dp"
android:background="@drawable/selector1"
android:text="button1" />
結合Shape來實現背景漸層效果。
或者只是以color代替drawable作為背景選取器的元素:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:Android="http://schemas.android.com/apk/res/android">
<itemAndroid:state_selected="true">
<shape>
<solidAndroid:color="#ff0000" />
</shape>
</item>
<itemAndroid:state_pressed="true">
<shape>
<solidAndroid:color="#ff0000" />
</shape>
</item>
<item>
<shape>
<solidAndroid:color="#00ffff" />
</shape>
</item>
</selector>
再或者drawable和color混用(不過注意四角的一致性,因為drawable裡可能圓弧型四角):
<?xml version="1.0" encoding="utf-8"?>
<selectorxmlns:Android="http://schemas.android.com/apk/res/android">
<itemAndroid:state_selected="true">
<shape>
<solidAndroid:color="#ff0000" />
</shape>
</item>
<itemAndroid:state_pressed="true">
<shape>
<solidAndroid:color="#ff0000" />
</shape>
</item>
<itemAndroid:drawable="@drawable/login_blue_normal">
</item>
</selector>
: