在布局中使用属性



我想在布局中使用暗模式。我尝试过:

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>


layout.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>

有别的办法吗?

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

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

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

这个链接应该会有所帮助。

最新更新