Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually recompose all AndroidView in JetPack Compose

In my project I use JetPack Compose and the AndroidView to use an XML View.

@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. There is an option in the AndroidView to obverse the state change ?

ps: I've simplified MyComposable for the example

like image 357
Ady Avatar asked Apr 16 '26 04:04

Ady


1 Answers

You can use the update block.

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. 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
    }
)
like image 165
Gabriele Mariotti Avatar answered Apr 18 '26 19:04

Gabriele Mariotti