skip to content

In a View-based Android app, how do you place Jetpack Compose UI inside an existing XML screen using ComposeView?

level: juniorimportance: must knowfreq 65%

answer

  1. a View that hosts composables
  2. declared in XML like any widget
  3. setContent with a theme around it
  4. one unique id per ComposeView
  5. needs a ViewTreeLifecycleOwner or it throws

basics

~20 s

Add androidx.compose.ui.platform.ComposeView to the XML layout or create it in code, then call setContent with your composables wrapped in a theme. It is an ordinary View, so the rest of the screen stays as it is.

solid answer

~40 s

`ComposeView` is a real Android `View` (`androidx.compose.ui.platform.ComposeView`), so you declare it in the XML layout like any widget, or create it in code, and call `setContent { }` with the composables. The first composition happens when the view is attached to a window or when `createComposition()` is called, whichever comes first. Wrap the content in your Compose theme, because Material composables expect a `MaterialTheme` above them. If one layout holds several `ComposeView`s, give each a unique id so saved instance state works. The host must propagate a `ViewTreeLifecycleOwner` and `ViewTreeSavedStateRegistryOwner`; `ComponentActivity` and `Fragment` already do. You cannot `addView` child Views into it, and inside a Fragment you also set a `ViewCompositionStrategy` that follows the Fragment's view lifecycle.

code

xml · 15 lines
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <TextView
      android:id="@+id/room_title"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />

  <androidx.compose.ui.platform.ComposeView
      android:id="@+id/now_singing"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
</LinearLayout>

go deeper

for a junior

Recall that ComposeView is a View you put in XML or code, that setContent supplies the composables, and that a theme should wrap them.

for a middle

Explain when the first composition runs, which view-tree owners it needs, and why several ComposeViews in one layout need unique ids.

for a senior

Show you can diagnose the missing ViewTreeLifecycleOwner crash and choose a disposal strategy that fits where the view lives.

for a principal

Frame ComposeView as the unit of incremental adoption: where a team allows it, which theme every instance must use, and when AbstractComposeView wrappers are worth maintaining.

## What ComposeView is `ComposeView` (package `androidx.compose.ui.platform`) is the bridge for putting **Compose inside Views**. It extends `AbstractComposeView`, which extends `ViewGroup`, so to the View system it is just another widget: it can sit in a `LinearLayout`, a `ConstraintLayout` or a `CoordinatorLayout`, take layout params and an id, and be found with `findViewById` or view binding. Inside, it hosts one Compose **composition** whose content you set with `setContent { }`. In a karaoke-booking app migrating one piece at a time, the booking screen can stay in XML while a new "now singing" banner is written in Compose and dropped into the layout as a `ComposeView`. ## The steps 1. **Declare it.** Add `<androidx.compose.ui.platform.ComposeView android:id="@+id/now_singing" ... />` to the layout, or construct `ComposeView(context)` in code and add it to a parent. 2. **Set the content.** After inflation, look the view up (or use the binding field) and call `setContent { }` with your composables. 3. **Wrap a theme.** Put your Compose theme (usually built on `MaterialTheme`) around the content. The Android documentation states that Material components such as `Button` and `Text` depend on a `MaterialTheme` being in place and their behaviour is undefined without it. 4. **Choose disposal when needed.** By default the composition follows `ViewCompositionStrategy.Default`; inside a Fragment you normally switch to `DisposeOnViewTreeLifecycleDestroyed` so the composition follows the Fragment's view lifecycle. For a whole new screen in an Activity there is a shorter path: `ComponentActivity.setContent { }` from the `androidx.activity:activity-compose` artifact creates the `ComposeView` for you. ## When the composition starts and what it needs - `setContent` stores the lambda; the **initial composition** runs when the view becomes attached to a window or when `createComposition()` is called, whichever comes first. - The view tree above it must provide a **`ViewTreeLifecycleOwner`** and a **`ViewTreeSavedStateRegistryOwner`**. `ComponentActivity`, `Fragment` and the Navigation component set these up. If they are missing, composing throws `IllegalStateException` with the message "Composed into the View which doesn't propagate ViewTreeLifecycleOwner!" (or the SavedStateRegistryOwner variant), which is what happens when a `ComposeView` is placed under a host that does not set them. - A `ViewModelStoreOwner` is looked up the same way, which is how `viewModel()` inside the content finds the Activity or Fragment that owns the screen. ## Rules that trip people up | Rule | What happens if you ignore it | |---|---| | Unique id for each `ComposeView` in one layout | The documentation says each needs a unique id for `savedInstanceState` to work, so saved state is not restored correctly without one | | No child Views | `addView` on a `ComposeView` throws `UnsupportedOperationException` ("Cannot add views to ComposeView; only Compose content is supported") | | Theme around content | Material composables fall back to undefined styling | | Lifecycle owners present | `IllegalStateException` at first composition | ## Reusable Compose widgets for View screens When the same Compose component must appear in several XML screens, subclass `AbstractComposeView` and implement `@Composable override fun Content()`. Exposing its inputs as `mutableStateOf` properties makes the class behave like a classic custom View that can be inflated from XML and set through view binding, while recomposing when a property changes. ## Choosing the entry point | Situation | Entry point | |---|---| | A whole new screen in an Activity | `ComponentActivity.setContent { }` | | A new screen in a Fragment-based app | a Fragment whose `onCreateView` returns `ComposeView(requireContext())` | | A new piece inside an existing XML screen | a `ComposeView` element in the layout, then `setContent` | | The same Compose component in many XML screens | an `AbstractComposeView` subclass | All four end up in the same place: a `ComposeView`-style host with one composition. The choice only decides who creates the host and where its content is set. ## Review checklist for a new ComposeView - Is the content wrapped in the app's Compose theme rather than a bare `MaterialTheme` with defaults? - Does every `ComposeView` in the layout have its own id? - Inside a Fragment, is a lifecycle-based `ViewCompositionStrategy` set? - Is state that both the View code and the composable need kept in one owner, such as the screen's `ViewModel`, rather than copied into both? ## What to remember - `ComposeView` is a `View`; Compose lives inside it. - `setContent` plus a theme is the whole basic recipe. - The view tree must provide lifecycle and saved-state owners. - Several `ComposeView`s in one layout need distinct ids.

  • Why does a ComposeView sometimes crash with "Composed into the View which doesn't propagate ViewTreeLifecycleOwner!"?
    Composition needs a `LifecycleOwner` and a `SavedStateRegistryOwner` found through the view tree. `ComponentActivity` and `Fragment` set them on their views, but a host that does not, such as a plain platform `Activity` or a window you create yourself, leaves them missing. Host the view under a `ComponentActivity` or Fragment, or set the owners on the root with `setViewTreeLifecycleOwner` and `setViewTreeSavedStateRegistryOwner`.
  • How do you reuse one Compose button in several XML screens without repeating setContent everywhere?
    Subclass `AbstractComposeView`, implement `Content()` with the composable wrapped in your theme, and expose its inputs as `mutableStateOf` properties. The class can then be declared in XML and configured through view binding like any custom View, and changing a property recomposes it.

  • ComposeView is a special Activity type rather than a regular View
  • You can add child Views to a ComposeView with addView
  • Composition starts as soon as setContent is called, even when detached
  • Material composables pick up the XML theme with no Compose theme around them
  • Several ComposeViews in one layout can share an id without consequence