简体   繁体   中英

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.

I hope to define a color based MaterialTheme.colors , but Code B return the following error.

@Composable invocations can only happen from the context of a @Composable function

At present, I have to use Code C, it's not very good, is there a better way?

Code A

val IconColor = Color(0xFF2E7D32)

Code B

val IconColor = MaterialTheme.colors.onSurface.copy(alpha = 0.76f)

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

1:

 val IconColor1: @Composable () -> Color = { MaterialTheme.colors.onSurface.copy(alpha = 0.76f) }

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. Just Ctrl + Click on the name of the class/color and you're there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM