如何根据当前应用主题为按钮选择器设置不同的样式?
这是我的button_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<color android:color="@color/color_theme1"/>
</item>
<!-- pressed -->
<item android:drawable="@color/transparent"/>
<!-- default -->
</selector>
答案 0 :(得分:2)
由于您的应用主题颜色位于color.xml中的color_primary中。你可以在你的选择器中使用它。但是你必须创建两个drawables文件,一个用于默认状态,另一个用于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);
}
}
});
答案 1 :(得分:1)
在您的应用中使用动态选择器,以便您可以根据需要指定颜色。
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},
getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },
getResources().getDrawable(R.drawable.normal));
imageView.setImageDrawable(states);
或