简体   繁体   English

在 JetPack Compose 中手动重构所有 AndroidView

[英]Manually recompose all AndroidView in JetPack Compose

In my project I use JetPack Compose and the AndroidView to use an XML View.在我的项目中,我使用 JetPack Compose 和 AndroidView 来使用 XML 视图。

@Composable
fun MyComposable(
    message: String
) {

    AndroidView(
        factory = { context ->

            TextView(context).apply {
                text = message
            }

        })
}

My issue is that when my message state change, the XML view in the AndroidView isn't recomposed.我的问题是,当我的message state 更改时, AndroidView中的 XML 视图不会重新组合。 There is an option in the AndroidView to obverse the state change? AndroidView中有一个选项可以阻止 state 更改?

ps: I've simplified MyComposable for the example ps:我已经为示例简化了MyComposable

You can use the update block.您可以使用update块。

From the doc :文档

The update block can be run multiple times (on the UI thread as well) due to recomposition, and it is the right place to set View properties depending on state.由于重组, update块可以多次运行(也可以在 UI 线程上),它是根据 state 设置View属性的正确位置。 When state changes, the block will be reexecuted to set the new properties .当 state 更改时,将重新执行该块以设置新属性 Note the block will also be ran once right after the factory block completes请注意,该块也将在factory块完成后立即运行一次

AndroidView(
    factory = { context ->

        TextView(context).apply {
            text = "Initial Value"
        }
    },
    update = {
        it.text =  message
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM