首页 > 解决方案 > Android ?attr/colorAccent 在 API 21 上使用不正确的颜色

问题描述

我的布局中有两个按钮,如下所示:

在此处输入图像描述

左边的那个有android:backgroundTint="?attr/colorAccent"并且正确地显示为紫色。右侧的按钮在 XMLandroid:backgroundTint="@color/button_color"@color/button_color定义如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@color/gray"/>
    <item android:color="?attr/colorAccent" />
</selector>

在 android 版本 >22 上,两个按钮都正确显示紫色,但仅在 API 21 和 22 上(我没有在下面测试,因为我的应用只支持 >=21),使用的按钮android:backgroundTint="@color/button_color"显示(看似随机的)红色。

使用时如何使?attr/colorAccent显示正确的颜色button_color.xml

标签: androidandroid-layout

解决方案


我仍然不确定是什么导致了这个问题,但我已经通过应用这样ColorStateList的代码解决了这个问题:

button.setBackgroundTintList(
    new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_enabled}, //Disabled
                    new int[]{} //Default
            },
            new int[]{
                    disabledColor,
                    defaultColor
            }
    )
);

要设置defaultColor等于强调色属性,我使用以下方法:

public static int getAccentColor(final Context context) {
    final TypedValue typedValue = new TypedValue();
    final TypedArray a = context.obtainStyledAttributes(typedValue.data, new int[]{android.R.attr.colorAccent});
    final int color = a.getColor(0, 0);
    a.recycle();
    return color;
}

推荐阅读