在 JetPack Compose 中手动重构所有 AndroidView

Manually recompose all AndroidView in JetPack Compose

在我的项目中,我使用 JetPack Compose 和 AndroidView 来使用 XML 视图。

@Composable
fun MyComposable(
    message: String
) {

    AndroidView(
        factory = { context ->

            TextView(context).apply {
                text = message
            }

        })
}

我的问题是,当我的 message 状态改变时,AndroidView 中的 XML 视图没有重新组合。 AndroidView中有一个选项来反对状态变化?

ps:我已经简化了 MyComposable 的例子

您可以使用 update 块。

来自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. When state changes, the block will be reexecuted to set the new properties. Note the block will also be ran once right after the factory block completes

AndroidView(
    factory = { context ->

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