當你的應用程序的主題顏色是在color.xml color_primary。你可以像這樣在你的選擇器中使用它。但是你必須創建兩個可繪製文件,一個用於默認狀態,另一個用於selected_state。
button_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--selected/pressed/focused -->
<item android:state_selected="true"
android:drawable="@drawable/button_selected"
/>
<item android:drawable="@drawable/button_default"/>
<!-- default -->
</selector>
button_default.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<!--this is to give gradient effect -->
<gradient android:angle="270"
android:startColor="@color/gray"
android:endColor="#@color/gray"
/>
<!-- this will make corners of button rounded -->
<corners android:topLeftRadius="5dip"
android:bottomRightRadius="5dip"
android:topRightRadius="5dip"
android:bottomLeftRadius="5dip"/>
</shape>
button_selected.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<!--this is to give gradient effect -->
<gradient android:angle="270"
android:startColor="@color/color_primary"
android:endColor="#@color/color_primary"
/>
<!-- this wil make corners of button rounded -->
<corners android:topLeftRadius="5dip"
android:bottomRightRadius="5dip"
android:topRightRadius="5dip"
android:bottomLeftRadius="5dip"/>
</shape>
您必須以編程方式執行以下操作,以便該按鈕將保持選中狀態。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(v.isSelected())
{
v.setSelected(false);
}
else
{
v.setSelected(true);
}
}
});
顯而易見的答案是使用一個實際的主題色,而不是'@色/ color_theme1',例如像'colorPrimary'。這就是說,這將只適用於api 21或以上 –