When coding with compose we use MaterialTheme code so much. Is there a way to shorten this part of the code? for example: mColor.primay
CodePudding user response:
I guess this can be done in various ways. One of them being
val mColor
get() = @Composable{
MaterialTheme.colors
}
usage
mColor().primary
CodePudding user response:
You can do it with function.
@Composable
fun materialThemeColor() = MaterialTheme.colors
While using you can use
color = materialThemeColor().primary
CodePudding user response:
This is less of a Jetpack Compose solution - more of "using Kotlin language features".
You can use the with
scope function to make MaterialTheme
, which is an object
, an implicit receiver. Then you can refer to colors.primary
or colors.whatever
without saying MaterialTheme
.
You can surround the entire enclosing function with a with
block:
@Composable
fun foo() {
with(MaterialTheme) {
// compose your view here...
// and you can say "colors.primary" instead of
// "MaterialTheme.colors.primary" in here
}
}
Alternatively, simply use a type alias to make the name MaterialTheme
shorter:
typealias MT = MaterialTheme
// now you can say "MT.colors.primary" instead of "MaterialTheme.colors.primary"