如何在 Jetpack Compose 中引用主题属性?

Arc*_*nes 6 android android-theme android-jetpack-compose

所以在目前的andriod开发中,如果我们需要引用主题中设置的颜色,我们可以简单地做:(在布局xml中)

....
    <TextView
        ...
        android:textColor="?attr/colorPrimary"
        .../>
....
Run Code Online (Sandbox Code Playgroud)

如果我在主题中设置了蓝色。我将在上面的文本视图中获得该颜色。

我想知道如何在Jetpack Compose. 在Compose,我们做,

MaterialTheme(...) {
    Column {
        Text(
            ...
            textStyle = TextStyle(color = ????) // How to I reference to the theme?
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*tti 5

您可以使用以下内容:

Text(text = "....",
     style = TextStyle(color = MaterialTheme.colors.primary))
Run Code Online (Sandbox Code Playgroud)

  • 如果我想引用维度属性(例如“android.R.attr.actionBarSize”)怎么办? (4认同)

小智 5

为了从属性中获取颜色,我使用这个可组合函数:

@Composable
fun getColor(color: Int): Color {
    return colorResource(LocalContext.current.getColorFromAttrs(color).resourceId)
}

fun Context.getColorFromAttrs(attr: Int): TypedValue {
    return TypedValue().apply {
        theme.resolveAttribute(attr, this, true)
    }
}
Run Code Online (Sandbox Code Playgroud)

用途:

val color: Color = getColor(R.attr.colorText)
Run Code Online (Sandbox Code Playgroud)