android - 在 AndroidView Compose 中使用样式
问题描述
我们如何在 Compose 的 AndroidView 中使用样式属性?下面的代码片段不起作用。
AndroidView(factory = { context ->
Button(context).apply {
text = "Turn On"
style = "@style/button_style"
}
})
解决方案
"@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())
}
)
推荐阅读
- shell - Shell 脚本显示美元 $ 的语法错误
- r - 优势比是逻辑回归中分层的连续变量
- scrapy-splash - 带有 Splash 的响应表中缺少计时键
- c++ - 除非浮点数是完整的,否则是否有带有 sprintf 的格式字符串来填充?
- azure - Azure Devops 管道运行中的 Pytest 无法识别的参数
- angular - Angular 方法返回带有 http observable
- amazon-web-services - 使用 Athena 查询 S3 库存时出现 HIVE_CURSOR_ERROR - 大小列是否正确?
- javascript - 使用 React Native 从 API 获取数据
- javascript - 在函数中声明默认参数有什么作用?
- amazon-web-services - 如何在 DynamoDB 中搜索嵌套的对象数组