0

レイアウトでダークモードを使用したい。私はこれを試しました:

attr.xml:

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


themes.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 を作成する必要があるため、アプリで 2 つの 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 に答える