0

我想在我的布局中使用暗模式。我试过这个:

attr.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myColor" format="reference|color" />
</resources>


主题.xml:

<resources xmlns:tools="http://schemas.android.com/tools">
    ...
    <!-- Light -->
    <item name="myColor">#4A4A4A</item>
    ...
    <!-- Dark-->
    <item name="myColor">#FFFFFF</item>
</resources>


布局.xml:

<androidx.cardview.widget.CardView
    style="@style/HBCardContent"
    android:textDirection="locale">

    <TextView
        android:id="@+id/my_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World"
         android:textColor="?attr/myColor"/>

</androidx.cardview.widget.CardView>

但我收到了这个错误:

Unable to start activity ... Binary XML file line #53 in com.example.xxx:layout/layout: Error inflating class <unknown>

还有另一种方法吗?

4

1 回答 1

3

您需要为夜间模式创建文件夹并在其中创建 colors.xml,因此您将在应用程序中创建两个 colors.xml 文件:

values/colors.xml -> <item name="myColor">#4A4A4A</item>
values-night/colors.xml -> <item name="myColor">#FFFFFF</item>

当您将应用切换到夜间模式时,android 会自动从夜间文件夹中获取颜色

这个链接应该有帮助。

于 2021-06-26T12:06:37.973 回答