在今天AppCompat更新出来之前,我可以改变Android L中按钮的颜色,但在旧版本上不行。在包含新的AppCompat更新后,我无法更改两个版本的颜色,当我尝试时,按钮就消失了。有人知道怎么改变按钮的颜色吗?
下面的图片展示了我想要达到的目标:
白色按钮是默认的,红色按钮是我想要的。
这是我之前在styles.xml中改变按钮颜色所做的:
<item name="android:colorButtonNormal">insert color here</item>
要动态地进行:
button.getBackground().setColorFilter(getResources().getColor(insert color here), PorterDuff.Mode.MULTIPLY);
我也改变了@android:style/ theme . material . light的主题父元素。到Theme.AppCompat.Light.DarkActionBar
这个SO的回答帮助我得到了一个答案https://stackoverflow.com/a/30277424/3075340
我使用这个实用工具方法来设置按钮的背景色调。它适用于棒棒糖之前的设备:
// Set button background tint programmatically so it is compatible with pre-lollipop devices.
public static void setButtonBackgroundTintAppCompat(Button button, ColorStateList colorStateList){
Drawable d = button.getBackground();
if (button instanceof AppCompatButton) {
// appcompat button replaces tint of its drawable background
((AppCompatButton)button).setSupportBackgroundTintList(colorStateList);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Lollipop button replaces tint of its drawable background
// however it is not equal to d.setTintList(c)
button.setBackgroundTintList(colorStateList);
} else {
// this should only happen if
// * manually creating a Button instead of AppCompatButton
// * LayoutInflater did not translate a Button to AppCompatButton
d = DrawableCompat.wrap(d);
DrawableCompat.setTintList(d, colorStateList);
button.setBackgroundDrawable(d);
}
}
如何在代码中使用:
Utility.setButtonBackgroundTintAppCompat(myButton,
ContextCompat.getColorStateList(mContext, R.color.your_custom_color));
这样,如果你只是想改变背景色调,只是想保持漂亮的按钮效果,你就不必指定ColorStateList。