我第一次探索 Compose + Material 3,在尝试实现自定义颜色时遇到了很大的困难。
\n我的意思是根据 Compose 之前的工作方式执行以下操作:
\n我有我的自定义属性attrs.xml
<?xml version="1.0" encoding="UTF-8"?>\n<resources>\n <declare-styleable name="CustomStyle">\n <attr name="myCustomColor"\n format="reference|color"/>\n </declare-styleable>\n</resources>\nRun Code Online (Sandbox Code Playgroud)\n并且该自定义属性可以在我的光明和黑暗中使用styles.xml
<?xml version="1.0" encoding="utf-8"?>\n<resources xmlns:tools="http://schemas.android.com/tools">\n <style name="AppTheme" parent="Theme.Material3.DayNight.NoActionBar">\n <item name="myCustomColor">@color/white</item> <!-- @color/black in the dark style config -->\n </style>\n</resources>\nRun Code Online (Sandbox Code Playgroud)\n然后我可以在任何我想要的地方使用它,无论是在代码中还是在布局中:
\n<com.google.android.material.imageview.ShapeableImageView\n android:layout_width="24dp"\n android:layout_height="24dp"\n android:background="?myCustomColor"\nRun Code Online (Sandbox Code Playgroud)\n这非常简单实用,因为它会自动解析浅色和深色,而我所需要的只是使用自定义颜色参考。
\n但在 Compose with Material 3 中我找不到任何地方解释如何完成这样的事情。
\n在材质 2 中,可以执行以下操作:
\nval Colors.myExtraColor: Color\n get() = if (isLight) Color.Red else Color.Green\nRun Code Online (Sandbox Code Playgroud)\n但在材料 3 中这不再可能:
\n …Android Jetpack Compose Colors类包含一组可以实现材质主题应用程序的颜色类型。如果我的应用主题需要一些额外的颜色类型,我如何添加这些额外的颜色,以便它们可以通过MaterialTheme对象使用?
android ×2