如何缩短MaterialTheme.colors.primary?

Rez*_*aji 2 kotlin android-jetpack-compose

当使用 compose 进行编码时,我们经常使用 MaterialTheme 代码。有没有办法缩短这部分代码?例如:mColor.primay

Swe*_*per 5

这与其说是 Jetpack Compose 解决方案,不如说是“使用 Kotlin 语言功能”。

您可以使用with作用域函数使MaterialTheme,即object,成为隐式接收器。那么你可以参考colors.primary或者colors.whatever不用说MaterialTheme

您可以用块包围整个封闭函数with

@Composable
fun foo() {
    with(MaterialTheme) {
        // compose your view here...
        // and you can say "colors.primary" instead of 
        // "MaterialTheme.colors.primary" in here
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,只需使用类型别名来使名称MaterialTheme更短:

typealias MT = MaterialTheme
// now you can say "MT.colors.primary" instead of "MaterialTheme.colors.primary"
Run Code Online (Sandbox Code Playgroud)