问题描述
我有一个自定义 viewholder 类,它从构造函数中 android 命名空间中的属性获取颜色:
int mDefaultPrimaryColor = GetColor(context,android.R.attr.colorPrimary);
....
public static int getColor(Context context,int attr)
{
TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
int color = ta.getColor(0,0);
ta.recycle();
return color;
}
稍后绑定方法最终设置颜色:
someTextView.setTextColor(mDefaultPrimaryColor);
我想通过 XML 覆盖我的应用程序中的 android.R.attr.colorPrimary 值而不修改 Java 代码,以便该值与 SDK 中设置的值不同。
我试图在我的 themes.xml 中覆盖这个值:
<resources>
<style name="MyAppTheme" parent="@android:Theme.DeviceDefault.NoActionBar">
<item name="android:colorPrimary">@color/my_color</item>
</style>
</resources>
但是,我在 Android 模拟器中看到的颜色并不是我为 my_color 设置的颜色。有没有办法用我在应用程序中定义的颜色覆盖 android.R.attr.colorPrimary?我做错了什么?
编辑:主题已在清单文件中设置。更新了代码片段,使其更加准确。
解决方法
您的代码不够深入,无法获取颜色代码。试试这个:
// Extract the color attribute we are interested in.
TypedArray a = context.obtainStyledAttributes(new int[]{android.R.attr.colorPrimary});
// From the TypedArray retrive the value we want and default if it is not found.
int defaultColor = a.getColor(0,0xFFFFFF);
// Make sure to recycle the TypedArray.
a.recycle();
现在在您的主题/样式中,您可以指定如下内容:
<item name="android:colorPrimary">@android:color/holo_blue_light</item>
这是
<!-- A light Holo shade of blue. Equivalent to #ff33b5e5. -->
<color name="holo_blue_light">#ff33b5e5</color>
当然,您必须根据需要应用此颜色。
,您可以使用更改的属性值创建单独的主题,然后将该主题传递给将 ContextThemeWrapper(context,R.style.new_theme)
作为上下文传递的视图。
检查文档: https://developer.android.com/reference/android/view/ContextThemeWrapper
UPD:当然可以按照您的尝试在主题中设置 colorPrimary。您需要添加
<application
...
android:theme="@style/MyAppTheme"
...
到 AndroidManifest.xml。