[英]How can I define a color in Color.kt with simple way when I use Jetpack Compose?
I can use Code A to define a color in Color.kt file which is generated by Android Studio wizard automatically, it's OK.我可以使用代码A在Android Studio向导自动生成的Color.kt文件中定义颜色,没关系。
I hope to define a color based MaterialTheme.colors
, but Code B return the following error.我希望定义一个基于颜色的
MaterialTheme.colors
,但是代码 B 返回以下错误。
@Composable invocations can only happen from the context of a @Composable function @Composable 调用只能在 @Composable function 的上下文中发生
At present, I have to use Code C, it's not very good, is there a better way?目前,我必须使用代码 C,不太好,有没有更好的方法?
Code A代码 A
val IconColor = Color(0xFF2E7D32)
Code B代码 B
val IconColor = MaterialTheme.colors.onSurface.copy(alpha = 0.76f)
Code C代码 C
@Composable
fun IconColor(): Color {
return MaterialTheme.colors.onSurface.copy(alpha = 0.76f)
}
You are getting that because MaterialTheme.colors
the getter of this field is using @compsable
scope, So I have found 2 ways you can declare your variable in Colors.kt
in the way you want.你得到这个是因为
MaterialTheme.colors
这个字段的吸气剂正在使用@compsable
scope,所以我找到了两种方法,你可以用Colors.kt
的方式声明你的变量。
1:
1:
val IconColor1: @Composable () -> Color = { MaterialTheme.colors.onSurface.copy(alpha = 0.76f) }
2:
2:
val IconColor2: Color @Composable get() = MaterialTheme.colors.onSurface.copy(alpha = 0.76f)
And I hope this was helpful我希望这会有所帮助
Studio has the source for the material colours. Studio 有材料颜色的来源。 Just
Ctrl
+ Click
on the name of the class/color and you're there.只需
Ctrl
+ Click
类/颜色的名称即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.