Jetpack compose

Add Compose in XML (Interoperability) — Part 2

Muhammad Ajmal
2 min readJul 10, 2021

In the previous part of this article, we talked about adding custom views in jetpack compose.

In this part we will talk about adding composable in your existing XML layout. You might have scenarios when you get new features to implement, in an existing screen built in XML, with a short deadline. You are motivated and want to add the new features in Compose. But with the deadline already banging at your door, you can’t afford to remove existing XML and writing everything in Compose from scratch.

So what would you do in any such case. We will follow the android’s suggested bottom up approach:

The bottom-up approach starts migrating the smaller UI elements on the screen, like a Button or a TextView, followed by its ViewGroup elements until everything is converted to composable function

Note: Video Tutorial @ https://www.youtube.com/watch?v=PyD0yeU9hrg

So we will start writing the new layout features in compose keeping the existing XML intact. Let’s understand with an example.

Suppose our existing layout looks like this (on the left) and we will add a login button and a text using compose in it:

Existing layout (left)- Desired layout (right)

And the existing XML looks like the following:

Now let’s start adding compose in thisXML:

Step1: Add ComposeView Container in XML:

Just like any other View Group like Constraint or a RelativeLayout, jetpack compose has provided a container ComposeView, that you can add in XML. This Compose view will contain your new UI that you will write programmatically in Kotlin Compose. So Let’s add ComposeView and give it some constraints like any other view.

Step2: Define ComposeView and call SetContent:

Now just like any other layout, we need to define compose view in our Activity either using findViewById or using Data binding. In my case, i used data binding, so i will simply get Compose view through binding object and then call compose View on it

binding.composeView.setContent {}

That’s it. You’re read to start writing your compose layout inside the braces. Let’s define a column inside, put some margins (using Spacer) and define a button and textview

That’s it. For clean up, i will put this code in a function, and call it simply from anywhere in onCreate. The final code looks like the following.

And We’re done. If you liked the article, do leave some engagement in the form of claps, comment or maybe by following my youtube channel.

And the complete code is available on github.

I will see you in the next article. Till then, Good Bye (:

--

--

Muhammad Ajmal
Muhammad Ajmal

Written by Muhammad Ajmal

Apps Dev at Systems Ltd— YouTuber @CodingWithAj

Responses (1)