如何设置夜间模式可绘制对象按预期工作

Sol*_*ata 6 xml android uimanager android-configchanges android-drawable

随着夜间模式的变化,我要改变背景。

我有 /values 和 /values-night 文件夹,其中包含具有不同值的“colors.xml”。`

<color name="grey1">#ebebeb</color>
<color name="grey2">#c7c7c7</color>
<color name="grey3">#999999</color>
<color name="hover1">#8bb065</color>
<color name="red1">#ba0000</color>
<color name="red2">#ff0000</color>
<color name="green1">#336600</color>
<color name="text1">#000000</color>
Run Code Online (Sandbox Code Playgroud)

另一个是

<color name="grey1">#999999</color>
<color name="grey2">#333333</color>
<color name="grey3">#000000</color>
<color name="hover1">#8bb065</color>
<color name="red1">#ba0000</color>
<color name="red2">#ff0000</color>
<color name="green1">#336600</color>
<color name="text1">#ffffff</color>
Run Code Online (Sandbox Code Playgroud)

这些颜色用于背景“activity_main_bg2.xml”的图层列表:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle" >
            <solid android:color="@color/grey1" />
        </shape>
    </item>
    <item
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp">
        <shape android:shape="rectangle" >
            <solid android:color="@color/grey2" />
        </shape>
     </item>
</layer-list>
Run Code Online (Sandbox Code Playgroud)

我的活动包含片段:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world_dark"
    android:background="@drawable/activity_main_bg2" />
Run Code Online (Sandbox Code Playgroud)

当我改变时间从白天到黑夜或背景中的背景颜色不会改变。但如果我使用

android:background="@color/grey1"
Run Code Online (Sandbox Code Playgroud)

一切正常。

如何解决这个问题?这是安卓bug吗?

mam*_*rka 5

请试试这个:

  1. 在文件夹 res/values 和 res/values-night 中创建文件 style.xml。
  2. 为您的 TextView 添加它们的样式,例如:

    <style name="textViewStyle">
    <item name="android:background">@drawable/activity_main_bg2</item>
    </style>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将您的布​​局更新为:

    <TextView
    style="@style/textViewStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world_dark" />
    
    Run Code Online (Sandbox Code Playgroud)

此解决方案应获得依赖于日/夜模式的属性颜色。

  • 很棒的替代解决方案!但是为什么我们必须在 res/values 和 res/values-night 中都有 style.xml 的副本?根据文档,如果在 /values-night 中找不到 res xml,则应从 /values 中获取。我真的很想知道为什么会这样!? (2认同)