android - 如何从 Jetpack Compose Modifier 引用 xml 样式?

标签 android android-jetpack android-jetpack-compose

如何从 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 样式都负责。例如,您不能添加边距。
您可以创建撰写 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")

关于android - 如何从 Jetpack Compose Modifier 引用 xml 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68934217/

相关文章:

java - Android - 应用程序崩溃并显示 "java.lang.ClassCastException"

android - Android 中的 Firebase 身份验证错误

Android Studio :An alert box showed when I try to add RecyclerView

android - 测试 Android Compose State 值

android - 如何使伴奏导航 BottomSheet 完全展开?

android - Jetpack 撰写 : How to avoid Button Text disappearing when Button size is small?

android - 从android上传图片到golang服务器并保存在mongodb中

java - 如何使用Web App和Android App访问SQL数据库

android - 我可以使用 CameraX (Android Jetpack) 录制视频吗?

android - Room - 检查最近是否获取了数据