android - 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
?
解决方案
我仍然不确定是什么导致了这个问题,但我已经通过应用这样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;
}
推荐阅读
- c# - Revit插件,启动时重置表单的所有值
- android - Google Play 管理中心 - 如何通知我的应用是否包含广告
- java - 如何在 `@Query` 注释的存储库方法中启用通用返回类型?
- css - 如何删除工具提示箭头边框
- flutter - 如何在颤振可搜索下拉列表中从 api 列表中搜索数据
- python - Django ForeignKey 哪个字段?
- kotlin - 函数必须接受另一个函数的结果作为参数 Kotlin
- elasticsearch - Elasticsearch 停用词相对路径
- mysql - “#1265 - 数据被截断”错误更改列(集)值
- c# - 在 MVC 中创建一个按钮来隐藏标签并将其替换为 '******'