Using Android Views in Compose (and Vice Versa)

AndroidView and ComposeView are bridges for gradual UI migration. Use them to embed classic Views in Compose screens or vice versa, like for a MapView. The footgun is managing state and lifecycles across the two different UI paradigms, which can lead to bugs.
WHY IT EXISTS Android's original UI toolkit is based on XML layouts and imperative View objects. Rewriting a large, mature application in the newer, declarative Jetpack Compose is often too costly and risky. Interoperability APIs were created to allow for a gradual, piece-by-piece migration, enabling teams to adopt Compose without a full rewrite.
THE MENTAL MODEL Think of interoperability as a set of adapters for two different UI systems. To place an old View inside a new Compose screen, you wrap it in an AndroidView composable. To place a new composable inside an old XML layout, you use the ComposeView class. These act as bridges, translating between the two worlds.
HOW IT WORKS There are two directions. First, to use a View inside Compose, you use the AndroidView composable. It takes a factory lambda to create the View (e.g., a MapView) and an update lambda that is called whenever your Compose state changes, allowing you to imperatively update the View. Second, to use Compose inside a View-based screen, you add a ComposeView to your XML layout. Then, in your Fragment or Activity, you find this view and call its setContent method, passing in the root composable you want to display.
WHEN TO USE IT Use interoperability for three main scenarios: first, gradually migrating an existing app screen by screen or component by component; second, using a third-party library that only provides a View-based component within a new Compose screen; third, embedding a new Compose element into an older, stable XML layout that isn't scheduled for a rewrite.
WHEN NOT TO USE IT For new applications, you should aim for a 100% Compose architecture and only use interop if a critical library has no Compose alternative. Avoid creating complex, deeply nested interop layers, such as a View inside a Composable that is itself hosted in a View. This creates a maintenance and performance nightmare by blurring the boundaries between the two systems.
ONE CANONICAL EXAMPLE Embedding a MapView in a Compose UI is a classic use case. Google Maps provides a highly optimized, feature-rich View that has no native Compose equivalent. Using the AndroidView composable, you can place this powerful map component within your declarative UI, building the rest of the screen around it with Compose.
Read the original → developer.android.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.