在布局文件中使用当前主题的背景色

3
我有两个主题,一个是黑色的,一个是亮色的。我想获取当前主题的背景颜色,并在布局文件中使用它,如下所示:
<View
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="(backgroundColor)" />

假设 (backgroundColor) 是当前主题的背景颜色。我需要在那里放什么,而不是 (backgroundColor)


这是什么!!这个 (backgroundColor) 是什么意思?! - Atef Hares
一个占位符用于背景颜色,我无法获取。 - King Natsu
我仍然不理解你的问题,但是你可能想看看这个答案 - Atef Hares
我试图让我的问题更易懂。希望这有所帮助。 - King Natsu
2个回答

4

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

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

在你的情况下,你会像下面这样结束:

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

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


3
使用 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>
编辑: 请尽可能在第一时间发布完整的问题,如果您做出更改,请尝试将其添加到编辑部分下面。否则会给乐于帮助您的人们带来麻烦。
对于您编辑后的问题,已经有一个答案在这里 这里

You can get the background color (or Drawable) from the current theme by:

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);
}

并将其设置为您的视图!


抱歉给您带来不便。很抱歉告诉您,我无法按照这种方式编写代码,因为它会使我的布局和代码变得混乱。无论如何还是谢谢您。 - King Natsu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接