【问题标题】:Is there a way to override Android's platform attribute value at the app level?有没有办法在应用级别覆盖 Android 的平台属性值?
【发布时间】:2021-02-23 00:02:59
【问题描述】:

我有一个自定义的 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;
}

稍后在bind方法上最终设置颜色:

someTextView.setTextColor(mDefaultPrimaryColor);

我想通过 XML 覆盖我的应用程序中的 android.R.attr.colorPrimary 值,而不修改 Java 代码,以便该值与 SDK 中设置的值不同。

我试图在我的主题.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?我做错了什么?

编辑:主题已在清单文件中设置。更新了代码 sn-p 更准确。

【问题讨论】:

    标签: android android-layout android-resources android-theme android-styles


    【解决方案1】:

    您的代码还不够远,无法获得颜色代码。试试这个:

    // 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>
    

    当然,您必须根据需要应用此颜色。

    【讨论】:

    • 对不起,我应该展示完整的代码。得到 TypedArray 之后的部分就在那里。我将更新问题以反映这一点。
    • @dividebyzero 好吧,该代码应该可以工作。在获取颜色后在代码中放置一个调试断点以验证您是否得到它(在 `ta.recycle()` 将是一个好地方)。我的猜测是您正在检索您想要的值,但代码无法正确应用它,或者它在显示之后和之前被更改。
    • @dividebyzero 要检查的另一件事是绑定方法中的逻辑。如果那里有任何逻辑,它可能会走一条你没有预料到的道路。请记住,视图持有者被重复使用。
    【解决方案2】:

    您可以创建一个具有更改属性值的单独主题,然后将主题传递给将ContextThemeWrapper(context, R.style.new_theme) 作为上下文传递的视图。

    查看文档: https://developer.android.com/reference/android/view/ContextThemeWrapper

    UPD:当然可以在您尝试的时候在主题中设置 colorPrimary。你需要添加

    <application
        ...
        android:theme="@style/MyAppTheme"
        ...
    

    到 AndroidManifest.xml。

    【讨论】:

    • 我应该提到这一点,但主题已经在清单中设置,所以我怀疑还有其他事情发生。
    猜你喜欢
    • 2015-12-27
    • 2012-09-03
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 2018-03-12
    • 2014-08-14
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多