Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 104 ยท Building a Real UI

Views Interop and Legacy XML

Read legacy XML layouts, use ViewBinding, embed Views with AndroidView and Compose with ComposeView, and migrate an old Android app to Compose one screen at a time.

Compose is the modern way to build Android screens, but most real apps you will meet were started before it existed. They have dozens of XML layouts, fragments, a RecyclerView for every list and custom views that took months to write. You will often work in a codebase that mixes both worlds, and you will often need a library that only offers a View, such as a map or an ad. Android supports this on purpose: Compose and Views can live inside each other.

This lesson teaches you to read XML layouts, use ViewBinding, embed a View in Compose with AndroidView, embed Compose in an XML screen with ComposeView, and plan a gradual migration. Almost everything here is read-only (it needs the Android SDK and the View framework). The TryIts are stand-ins in plain Kotlin that show how XML-style attributes correspond to Compose modifiers and how a mixed screen is organized. For Compose basics see Thinking in Compose.

Reading an XML layout

Before Compose, a screen was described in an XML file under res/layout/. Each element is a View (a widget or a container, called a ViewGroup), and the attributes configure it:

XML
<!-- read-only example: res/layout/activity_profile.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/nameText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/profile_name"
        android:textSize="20sp" />

    <Button
        android:id="@+id/followButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="@string/follow" />
</LinearLayout>

Learn the vocabulary because it maps onto what you already know:

  • layout_width and layout_height take match_parent (fill the parent), wrap_content (fit the content) or a fixed dp value.
  • LinearLayout with orientation is a Column or Row; FrameLayout is similar to a Box; ConstraintLayout positions children by constraints and exists in Compose too.
  • padding is inside the view, layout_margin* is outside. In Compose both become Modifier.padding(...) at different positions in the chain, as in Modifiers.
  • @string/... references come from the resources you saw in The Manifest and Resources.
  • android:id="@+id/nameText" creates an id that code uses to find the view.

The stand-in below converts a few XML attributes into the Compose modifiers a rewrite would use. It is a small lookup, not a real inflater, but it is exactly the thinking you do when migrating a layout by hand.

Kotlin Mapping XML attributes to modifiers (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the last entry: a custom view has no direct equivalent. That is where interop comes in.

ViewBinding

In the old style you found views by id with findViewById, which could return the wrong type or null. ViewBinding generates a binding class for each layout file at build time, with a property for every view that has an id. The class name comes from the file name: activity_profile.xml becomes ActivityProfileBinding.

Kotlin
// read-only example
class ProfileActivity : AppCompatActivity() {
    private lateinit var binding: ActivityProfileBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.nameText.text = "Ada Lovelace"
        binding.followButton.setOnClickListener { follow() }
    }
}

It is enabled with buildFeatures { viewBinding = true } in the module's build.gradle.kts (see Gradle for Android). Properties have the right types and are null-safe for views that exist in every configuration. Binding is the recommended way to work with XML today; the older kotlin-android-extensions synthetic imports are removed, and findViewById is only for rare cases.

Data Binding

Data Binding is ViewBinding's bigger sibling. It also generates a binding class, but it lets the layout file itself read your data: instead of calling binding.nameText.text = user.name in code, the XML says android:text="@{user.name}". It was the standard way to build MVVM screens with LiveData before Compose, and you will find it in many older apps.

Enable it in the module's build.gradle.kts (it can be on together with ViewBinding):

Kotlin
// read-only example
android {
    buildFeatures {
        dataBinding = true
    }
}

A data-binding layout has a <layout> root element, an optional <data> block that declares variables, and then the normal view tree:

XML
<!-- read-only example: res/layout/activity_profile.xml -->
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="viewModel" type="com.example.app.ProfileViewModel" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@{viewModel.name}" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="@{!viewModel.loading}"
            android:onClick="@{() -> viewModel.follow()}"
            android:text="@string/follow" />
    </LinearLayout>
</layout>

The generated class is still ActivityProfileBinding, but inflating it needs a lifecycle owner so that observable data can update the UI:

Kotlin
// read-only example
val binding = DataBindingUtil.setContentView<ActivityProfileBinding>(this, R.layout.activity_profile)
binding.viewModel = viewModel
binding.lifecycleOwner = this   // lets LiveData and StateFlow drive the layout

Binding expressions

Everything inside @{ } is a binding expression. The language is a small subset of Java and supports field access, method calls, arithmetic, comparison, the ternary operator, null coalescing (user.nickname ?? user.name), string resources (@{@string/greeting(user.name)}) and calls to static methods through an <import>:

XML
<!-- read-only example -->
<data>
    <import type="android.view.View" />
    <variable name="state" type="com.example.app.UiState" />
</data>

<ProgressBar android:visibility="@{state.loading ? View.VISIBLE : View.GONE}" ... />
<TextView android:text="@{state.error ?? @string/no_error}" ... />

Expressions are evaluated when the observed data changes. Properties are observed when they come from LiveData, StateFlow (with lifecycleOwner set), ObservableField or a class that extends BaseObservable. A plain property is read once.

Two-way binding

One-way binding pushes data to the view. Two-way binding, written @={ }, also writes the user's changes back to the variable:

XML
<!-- read-only example -->
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@={viewModel.email}" />

If email is a MutableLiveData<String> in the ViewModel, typing updates it directly, with no TextWatcher. Use it for simple forms; keep validation in the ViewModel.

Binding adapters

When an attribute does not exist on the view, or you want custom logic, write a BindingAdapter: a static function that Data Binding calls when the expression changes. It is the usual place for image loading:

Kotlin
// read-only example
@BindingAdapter("imageUrl")
fun ImageView.bindImageUrl(url: String?) {
    if (url != null) load(url) else setImageResource(R.drawable.placeholder)
}
XML
<!-- read-only example -->
<ImageView app:imageUrl="@{user.avatarUrl}" ... />

Adapters turn the layout into a small DSL for your app, but each one is code that lives away from the screen that uses it, which makes the app harder to follow.

ViewBinding or Data Binding?

ViewBinding Data Binding
Generated class Yes, typed view properties Yes, typed views plus variables
Layout root Any view <layout> wrapper required
Logic in XML None Expressions, two-way binding, adapters
Build cost Small Higher (annotation processing, slower builds)
Debugging Plain Kotlin Errors appear in generated code
Recommended today Yes, for most XML screens Only to maintain existing code

The common advice: use ViewBinding for XML screens and put the logic in Kotlin, where the compiler, the debugger and unit tests can help. Data Binding is not deprecated, but it is not where Android is going. Compose gives you the same result (UI as a function of state) with no generated classes, as in State in Compose.

The stand-in below mimics the idea without the SDK: a binding holds a variable, expressions are lambdas that re-run when the observed value changes, and a "two-way" binding writes back.

Kotlin One-way and two-way binding (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Using a View inside Compose

If Compose lacks a widget, wrap the View in AndroidView. It takes a factory that creates the view once and an update block that runs on each recomposition with the latest state:

Kotlin
// read-only example
@Composable
fun LegacyChart(points: List<Float>, modifier: Modifier = Modifier) {
    AndroidView(
        modifier = modifier,
        factory = { context -> ChartView(context) },
        update = { chart -> chart.setPoints(points) },
    )
}

Treat update as the place where state flows into the view. Keep the view's own state minimal and clean up listeners when needed (onRelease is available). AndroidView can also inflate an XML layout through AndroidViewBinding. A common use is a map view or a WebView, which you will see again in Securing Your App.

Using Compose inside an XML screen

The opposite direction lets you migrate one screen region at a time. Add a ComposeView to the XML file and fill it in code:

XML
<!-- read-only example -->
<androidx.compose.ui.platform.ComposeView
    android:id="@+id/composeHeader"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
Kotlin
// read-only example: inside an Activity using ViewBinding
binding.composeHeader.setContent {
    AppTheme { ProfileHeader(name = viewModel.name) }
}

Inside a Fragment, set the view composition strategy to ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed so that the composition is disposed with the fragment's view, not with the window. For a whole new screen in an XML app, an AppCompatActivity calling setContent { } works with no XML at all.

Migrating gradually

A rewrite from scratch rarely pays off. A safe plan:

  1. Write all new screens in Compose. Embed them in the old navigation (fragments with a ComposeView, or activities with setContent).
  2. Share the theme. Use the MdcTheme-style adapters or define the Compose theme from your existing colors and typography so old and new screens match. See Material 3 and Theming.
  3. Convert leaf components first (a card, a toolbar, a form), then whole screens, then navigation.
  4. Keep the ViewModel. If screens already use ViewModel with LiveData or StateFlow, the data layer needs no change; Compose reads observeAsState or collectAsStateWithLifecycle.
  5. Delete XML only when nothing references it. Use the Android Studio "Find usages" and lint's unused resources check.
flowchart LR
    A["XML screen<br/>(Activity + ViewBinding)"] --> B["XML screen with<br/>a ComposeView island"]
    B --> C["Compose screen with<br/>an AndroidView for a legacy widget"]
    C --> D["Pure Compose screen"]

A typical migration path: each step compiles and ships, and the app is never "half-broken".

RecyclerView at a glance

Old lists used RecyclerView with an Adapter (creates and binds item views) and a ViewHolder (holds the item's views for reuse). It recycles the views that scroll out of sight, which is the idea that LazyColumn follows in Compose without the boilerplate. When you read old code, look for RecyclerView.Adapter or ListAdapter (which adds DiffUtil to animate changes): the item layout XML becomes the item composable, and onBindViewHolder becomes the body of the items { } lambda. A LazyColumn with stable keys replaces DiffUtil, as you learned in Lazy Lists and Grids.

The last stand-in shows the organization of a mixed screen: a tree where some nodes are old views and some are Compose islands. The helper prints the structure and counts how many parts still need migrating.

Kotlin A mixed screen and its migration progress (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Common mistakes

  • Creating a new View in update. Create it in factory once; update should only push state into it.
  • Forgetting the composition strategy in fragments, which leaks the composition or crashes on fragment transitions.
  • Duplicating state: one copy in the view and one in Compose. Keep one source of truth, usually the ViewModel.
  • Mismatched themes, so a migrated screen looks different from its neighbors.
  • Migrating everything at once. Ship in small steps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which API embeds an existing Android View (for example a map) inside a Compose screen?

    AndroidView takes a factory that creates the View and an update block. ComposeView goes the other way, hosting Compose inside an XML layout.
  2. 2. What does ViewBinding generate for activity_profile.xml?

    ViewBinding creates one binding class per layout at build time, named from the file name, replacing findViewById calls.
  3. 3. In AndroidView, where should the View be created?

    factory runs once to create the View, while update runs on recomposition and applies the latest state to the existing instance.
  4. 4. What is a sensible first step when migrating a large XML app to Compose?

    Interop lets you add Compose screens or islands without touching the rest, so the app keeps shipping while you migrate.

Summary

  • XML layouts describe a tree of Views; match_parent, wrap_content, margin and padding map onto Compose layouts and modifiers.
  • ViewBinding generates typed binding classes from layout files and replaces findViewById.
  • Data Binding adds <layout>/<data> variables, @{} expressions, two-way @={} and BindingAdapters; prefer ViewBinding for new XML screens.
  • AndroidView hosts a View in Compose (create in factory, update in update); ComposeView hosts Compose in XML.
  • Migrate gradually: new screens first, shared theme, leaf components, then navigation; keep the ViewModel.
  • RecyclerView adapters become LazyColumn items; the idea of recycling is the same.
  • This lesson is read-only except for the stand-ins that map attributes and model a mixed screen.

Next: Navigation Compose Basics