在寻找答案2天后,在API < 21中按钮主题对我来说不起作用。
我唯一的解决方案是覆盖AppCompatButton着色不仅与基础应用主题“colorButtonNormal”,而且视图backgroundTint如下:
public class AppCompatColorButton extends AppCompatButton {
public AppCompatColorButton(Context context) {
this(context, null);
}
public AppCompatColorButton(Context context, AttributeSet attrs) {
this(context, attrs, android.support.v7.appcompat.R.attr.buttonStyle);
}
public AppCompatColorButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (TintManager.SHOULD_BE_USED) {
setSupportBackgroundTintList(createButtonColorStateList(getContext(), attrs, defStyleAttr));
}
}
static final int[] DISABLED_STATE_SET = new int[]{-android.R.attr.state_enabled};
static final int[] FOCUSED_STATE_SET = new int[]{android.R.attr.state_focused};
static final int[] PRESSED_STATE_SET = new int[]{android.R.attr.state_pressed};
static final int[] EMPTY_STATE_SET = new int[0];
private ColorStateList createButtonColorStateList(Context context, AttributeSet attrs, int defStyleAttr) {
final int[][] states = new int[4][];
final int[] colors = new int[4];
int i = 0;
final int themeColorButtonNormal = ThemeUtils.getThemeAttrColor(context, android.support.v7.appcompat.R.attr.colorButtonNormal);
/*TypedArray a = context.obtainStyledAttributes(attrs, new int[] { android.R.attr.backgroundTint }, defStyleAttr, 0);
final int colorButtonNormal = a.getColor(0, themeColorButtonNormal);*/
TypedArray a = context.obtainStyledAttributes(attrs, android.support.v7.appcompat.R.styleable.View, defStyleAttr, 0);
final int colorButtonNormal = a.getColor(android.support.v7.appcompat.R.styleable.View_backgroundTint, themeColorButtonNormal);
a.recycle();
final int colorControlHighlight = ThemeUtils.getThemeAttrColor(context, android.support.v7.appcompat.R.attr.colorControlHighlight);
// Disabled state
states[i] = DISABLED_STATE_SET;
colors[i] = ThemeUtils.getDisabledThemeAttrColor(context, android.support.v7.appcompat.R.attr.colorButtonNormal);
i++;
states[i] = PRESSED_STATE_SET;
colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
i++;
states[i] = FOCUSED_STATE_SET;
colors[i] = ColorUtils.compositeColors(colorControlHighlight, colorButtonNormal);
i++;
// Default enabled state
states[i] = EMPTY_STATE_SET;
colors[i] = colorButtonNormal;
i++;
return new ColorStateList(states, colors);
}
}
然后你可以像这样定义你的按钮颜色:
<com.example.views.AppCompatColorButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#ffff0000"
app:backgroundTint="#ffff0000"
android:text="Button"
android:textColor="@android:color/white" />