In Jetpack Compose, what belongs in AndroidView's factory block versus its update block, and how does AndroidViewBinding apply this to an XML layout?
answer
- create once, sync many times
- listeners carry View events up
- State read inside update re-runs it
- XML::inflate as the factory
- factory runs exactly once per View instance
basics
~20 sCreate the View and attach its listeners in factory, which runs once per View instance; set state-driven properties in update, which runs after factory and again when state changes. AndroidViewBinding does the same with a generated binding's inflate as the factory.
solid answer
~40 s`AndroidView(factory, modifier, update)` calls `factory(context)` exactly once on the UI thread to build the View, so that is where construction, one-off setup and listeners go; listeners carry View events up as callbacks or state writes. `update` runs right after `factory` and then whenever recomposition passes new values or a `State` read inside the block changes, so it is where state-driven properties are pushed down. Data that differs per call must not be set in `factory`, or the View keeps its first value. `AndroidViewBinding`, from `androidx.compose.ui:ui-viewbinding`, wraps `AndroidView` for an XML layout: pass the generated `inflate` reference as the factory and write the update block with the binding as receiver. View binding must be enabled, and the documentation keeps it for small legacy layouts during migration.
code
kotlin · 18 lines@Composable
fun BookingForm(
state: BookingUiState,
onPartySizeChanged: (Int) -> Unit,
) {
AndroidViewBinding(
factory = BookingFormBinding::inflate,
update = {
// runs after inflation and again on recomposition
roomName.text = state.roomName
partySize.value = state.partySize
// reassigned here so it always calls the latest callback
partySize.setOnValueChangedListener { _, _, newValue ->
onPartySizeChanged(newValue)
}
},
)
}go deeper
Recall that factory creates the View and update sets its properties, and that AndroidViewBinding takes a generated binding's inflate.
Explain how often each block runs, that State read in update re-runs it, and how events flow back through listeners set up in factory.
Spot stale data set in factory and listeners that capture an outdated callback, and fix them with update or rememberUpdatedState.
Decide when a legacy View or XML layout is wrapped with AndroidView or AndroidViewBinding versus rewritten, and keep those wrappers small and temporary.
## Two directions across one seam `AndroidView` puts a classic Android `View` inside a composition. Data has to move both ways: - **Compose to View**: state from the composable is pushed into View properties. - **View to Compose**: View events such as clicks or value changes are reported back as callbacks or state writes. The two lambdas split that work by **how often they run**. ## factory: build once `factory: (Context) -> T` is called **exactly once** to obtain the View, and it is guaranteed to run on the UI thread. Use it for: 1. constructing the View, or inflating it; 2. one-off configuration and constant properties, such as text size or a fixed range; 3. attaching listeners that report events back up, for example a click listener that calls a lambda or writes a `mutableStateOf`. The documentation also prefers constructing the View inside `factory` over holding a View in `remember` outside `AndroidView`. ## update: sync many times `update: (T) -> Unit` runs once right after `factory` completes, then again whenever the call site recomposes with new values. `AndroidView` also observes the `State` objects **read inside** `update`, so changing one of them re-runs the block. Put every property that depends on state here: the current lyric line, a selected value, an enabled flag. | Belongs in `factory` | Belongs in `update` | |---|---| | `TextView(context)` or an inflate call | `view.text = currentLine` | | fixed styling and sizes | values that come from state | | listeners that report events up | anything that must change after first display | A frequent bug is a listener created in `factory` that captures the **first** callback passed to the composable. If the caller later passes a different lambda, the View still calls the old one. Either reassign the listener in `update`, or read the callback through `rememberUpdatedState`. `AndroidView` does not clip its child to the layout bounds; call `setClipToOutline` on the View if needed. Size and position come from the `modifier` parameter like any composable. ## Patterns for events coming back The documentation's own example shows the two usual ways a hosted View reports to Compose: 1. **Write state from a listener.** A click listener set in `factory` assigns a `mutableIntStateOf` held by the composable; Compose recomposes and, if `update` reads that state, the View is updated in turn. 2. **Call a hoisted callback.** The listener calls a lambda parameter such as `onPartySizeChanged`, so the screen's state holder decides what happens, following "data flows down, events flow up". Whichever you pick, keep the **source of truth** on one side. If the View also keeps its own copy, for example a `NumberPicker` value the user just changed, `update` should set it from state rather than read it back, otherwise the two sides drift apart. And avoid doing work in `update` that is not idempotent, such as adding a listener with an `add...` method on every run, because the block runs many times. ## AndroidViewBinding: the same contract for XML `AndroidViewBinding` lives in the `androidx.compose.ui:ui-viewbinding` artifact and requires view binding to be enabled in the module. Its factory has the shape `(LayoutInflater, ViewGroup, Boolean) -> T`, which matches every generated binding's three-argument `inflate`, so `BookingFormBinding::inflate` is passed directly. The trailing `update` lambda has the **binding as receiver**, so you write `roomName.text = ...` with no `binding.` prefix. Like `AndroidView`, the factory runs once and `update` runs after inflation and again when state read in it changes. Two details are specific to it: - If the composable sits inside a Fragment, the layout is inflated with the parent Fragment's `LayoutInflater`, so a `FragmentContainerView` in the XML nests its Fragment correctly. - When the `AndroidViewBinding` leaves the composition, Fragments inflated through a `FragmentContainerView` in that layout are removed, unless the Fragment manager's state is already saved. The documentation recommends it only for **smaller legacy XML layouts during incremental migration**, not for inflating whole screens in a Compose-only app. ## Checklist - Construction and listeners go in `factory`. - Every state-driven property goes in `update`. - Callbacks that can change are re-read, not captured once. - For XML, `AndroidViewBinding(XxxBinding::inflate) { ... }` with view binding enabled.
- Why does a View that receives per-item data in factory keep showing the first value?`factory` runs once per View instance. Any value applied there is never applied again, even when the composable is called with new arguments. Values that change belong in `update`, which runs after `factory` and again on recomposition or when a `State` read inside it changes.
- What must a module have before it can call AndroidViewBinding?The `androidx.compose.ui:ui-viewbinding` dependency, which provides `AndroidViewBinding`, and view binding enabled in the module's build configuration so the `XxxBinding` classes with their `inflate(LayoutInflater, ViewGroup, Boolean)` method are generated.
- factory runs on every recomposition, so setting data there is fine
- update runs only once, right after the View is created
- Holding the View in remember outside AndroidView is the preferred pattern
- AndroidViewBinding works without enabling view binding in the module
- A listener set in factory always sees the latest callback passed in