【问题标题】:Use current theme backgroundcolor in layout file在布局文件中使用当前主题背景色
【发布时间】:2017-02-25 20:11:11
【问题描述】:

我有 2 个主题,一个是黑暗的,一个是明亮的。我想获取当前主题背景颜色并在这样的布局文件中使用它:

<View
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="(backgroundColor)" />

假设(backgroundColor) 是当前主题背景颜色。除了(backgroundColor),我还需要放什么?

【问题讨论】:

  • 这是什么!!这个(backgroundColor) 是什么意思?!
  • 背景颜色的占位符,我无法获得
  • 我还是不明白你的问题,但是你可能想看看这个answer
  • 我试图让我的问题更容易理解。希望这会有所帮助

标签: android android-theme


【解决方案1】:

您的问题的正确答案可能是?android:colorBackground。但在某些情况下您可能仍想使用?android:windowBackground

虽然windowBackground 将成为您活动的背景,但colorBackground 似乎是您内容的默认背景颜色。

在你的情况下,你最终会像下面这样:

<View
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:background="?android:colorBackground" />

有关这些“默认”主题属性的完整列表,您可以查看基本 Android themes.xml 的源代码

【讨论】:

    【解决方案2】:

    使用android:theme

    <View
        android:theme="@style/yourTheme"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    在你的 values\styles.xml 中

     <style name="yourTheme" parent="AppTheme">
            <item name="android:background">@color/green</item>
     </style>
    

    编辑:请尝试在第一时间发布您的完整问题,如果您做出更改,请尝试将其添加到编辑部分。否则,喜欢帮助您的人会遇到麻烦。

    对于您编辑的问题已经有答案here

    您可以从当前主题中获取背景颜色(或 Drawable) 作者:

    TypedValue a = new TypedValue();
    getTheme().resolveAttribute(android.R.attr.windowBackground, a, true);
    if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
        // windowBackground is a color
        int color = a.data;
    } else {
        // windowBackground is not a color, probably a drawable
        Drawable d = activity.getResources().getDrawable(a.resourceId);
    }
    

    并将其设置为您的视图!

    【讨论】:

    • 很抱歉给您带来不便。很抱歉告诉你,但我不能在这件事上编码,因为它会使我的布局和代码变得一团糟。还是谢谢你
    猜你喜欢
    • 2019-08-14
    • 2021-12-30
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多