如何从 Jetpack Compose 修改器引用 xml 样式?

How to refer xml style from Jetpack Compose Modifier?

如何从 Compose 小部件引用资源样式?

styles.xml

<style name="Style.Monet.TextView.HeaderSubtext" parent="Widget.AppCompat.TextView">
    <item name="android:textColor">#737373</item>
    <item name="android:textSize">12sp</item>
    <item name="android:layout_marginStart">16dp</item>
    <item name="android:layout_marginBottom">16dp</item>
    <item name="android:layout_marginEnd">24dp</item>
</style>

MyComponent.kt

Text(text = "June 2021", style = TextStyle(R.style.Style_TextView_HeaderSubtext))

但这行不通。有没有办法让这个工作?

你不能那样做,因为 Compose Text 的样式不同,TextStyle 它不负责,所以所有 xml 样式都有责任。例如,您不能添加边距。

您可以创建 compose TextStyle:

val textStyle = TextStyle(
    color = Color(0xFF737373),
    fontSize = 12.sp,
)

并在您的项目中全局使用它或传递给您的主题。这是在撰写中使用样式的首选方式,请在 theming documentation 中查看更多相关信息。自定义 material 种可用样式之一:

val typography = Typography(
        body1 = TextStyle(
                color = Color(0xFF737373),
                fontSize = 12.sp,
        )
)

传递给你的主题:

@Composable
fun ComposePlaygroundTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (darkTheme) {
        DarkThemeColors
    } else {
        LightThemeColors
    }
    MaterialTheme(
        colors = colors,
        typography = typography,
        shapes = shapes,
        content = content,
    )
}

在可组合根​​应用主题:

setContent {
    ComposePlaygroundTheme {
        // your composables
    }
}

之后你可以这样使用它:

Text("",
    style = MaterialTheme.typography.body1,
)

要在撰写中应用边距,您需要使用填充修饰符。在 layout documentation:

中查看有关 compose 布局的更多信息

如果您想在撰写中重复使用相同样式的文本,您可以使用预定义的样式和填充创建您自己的可组合项:

@Composable
fun ProjectText(text: String, modifier: Modifier) {
// without material theme you can just define text style here and pass to text
//    val textStyle = TextStyle(
//        color = Color(0xFF737373),
//        fontSize = 12.sp,
    )
    Text("",
        style = MaterialTheme.typography.body1,
        modifier = modifier
            .padding(start = 16.dp, end = 24.dp, bottom = 16.dp)
    )
}

用法:

ProjectText("June 2021")