【问题标题】:Using style in AndroidView Compose在 AndroidView Compose 中使用样式
【发布时间】:2021-10-02 03:02:21
【问题描述】:

我们如何在 Compose 的 AndroidView 中使用 style 属性?下面的代码 sn -p 不起作用。

 AndroidView(factory = { context ->
                Button(context).apply {
                     text = "Turn On"
                     style = "@style/button_style"     
                }
            })

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    "@style/button_style" 只能在 XML 内部使用。

    设置样式/颜色/drawables等资源表单代码时,需要使用R.style.button_style代替。

    另外,android android.widget.Button 没有 style 参数,但您可以将其与上下文一起传递给初始化程序,如下所示:

    AndroidView(factory = { context ->
        val style = R.style.GreenText
        android.widget.Button(ContextThemeWrapper(context, style), null, style).apply {
            text = "Turn On"
    
        }
    })
    

    更新:这里有一个更详细的 AndroidView 用法示例。您可以在factory 期间设置初始值,并且可以根据update 块内的 Compose 状态变量更新您的视图状态

    var flag by remember { mutableStateOf(false) }
    Switch(checked = flag, onCheckedChange = { flag = !flag })
    AndroidView(
        factory = { context ->
            val style = R.style.GreenText
            android.widget.Button(ContextThemeWrapper(context, style), null, style).apply {
                text = "Turn On"
                // set initial text color from resources
                setTextColor(ContextCompat.getColor(context, R.color.black))
            }
        },
        update = { button ->
            // set dynamic color while updating 
            // depending on a state variable
            button.setTextColor((if (flag) Color.Red else Color.Black).toArgb())
        }
    )
    

    【讨论】:

    • 谢谢@Philip。另外,您知道我们如何在 AndroidView 可组合中使用其他 android 属性,例如 android:textcolor 等
    • @AndroidNewcomer 如果您需要更新一些 xml 视图,我建议您寻找现有的非 Compose 解决方案并将其应用于视图。我添加了更改文本颜色的示例。当您已经有一些旧布局的视图并且不想将它们转换为撰写时,也应该使用AndroidView。从您的问题来看,您似乎想从头开始构建它们:在这种情况下,我建议您使用 Compose 方法构建视图,而不是使用 AndroidView。就像 compose Button 将花费更少的代码来获得相同的效果。
    • 我有一个当前仅在 xml 中的库,我想将它与 Compose setTextColor(ContextCompat.getColor(context, R.color.black)) 一起使用不能正确使用 MaterialTheme 颜色,比如 MaterialTheme.colors.primary?
    • @AndroidNewcomer 您可以使用MaterialTheme.colors.primary.toArgb() 为旧视图转换组合颜色,就像我在update 中所做的一样
    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多