首页 > 解决方案 > 在 AndroidView Compose 中使用样式

问题描述

我们如何在 Compose 的 AndroidView 中使用样式属性?下面的代码片段不起作用。

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

标签: androidandroid-jetpack-compose

解决方案


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

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

androidandroid.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())
    }
)

推荐阅读