The Wayback Machine - https://web.archive.org/web/20240531043217/https://www.geeksforgeeks.org/android-jetpack-compose-interoperability-using-compose-in-xml-layouts/
Open In App

Android Jetpack Compose – Interoperability Using Compose in XML Layouts

Last Updated : 15 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Writing UI in jetpack compose can be fun, but can be difficult to migrate your whole project into Compose at one time. Fortunately, Jetpack Compose provides Interoperability api to use compose in existing XML views so that you can migrate to compose slowly.

Prerequisites:

  1. Knowledge of Jetpack Compose.
  2. Knowledge of Kotlin
  3. Knowledge of Android’s View.

Jetpack compose provides a ComposeView which we can use in XML and then write compose in our View.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Add a ComposeView in xml layout wherever we want to use the compose in our XML view. For simplicity, we will be using it in a Linear Layout with just a text in it.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/app_name"
        android:textColor="@color/black" />
  
    <!-- Compose view provided by jetpack compose -->
    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
</LinearLayout>


Step 3: Working with the MainActivity.kt File

Create a simple composable function that we want to use in the existing XML layout and write the following code.

Kotlin




@Composable
fun Greeting(text: String) {
    Text(
        text = "$text!", color = Color(0xFF0F9D58), 
          fontStyle = FontStyle.Italic, 
        fontSize = 30.sp
    )
}


Create a variable named composeView in the top level of MainActivity class

Kotlin




lateinit var composeView: ComposeView


then assign it after inflating the view (after setContentView call)

Kotlin




composeView = findViewById(R.id.compose_view)


and then use this setContent method in composeView context to use composable in our existing XML layout

Kotlin




composeView.setContent {
            Box(
                modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
            ) {
                Greeting("Hello Geeks for geeks")
            }
        }


Final MainActivity code.

Kotlin




import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.unit.sp
  
class MainActivity : AppCompatActivity() {
    lateinit var composeView: ComposeView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_activity)
        composeView = findViewById(R.id.compose_view)
        composeView.setContent {
            Box(
                modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center
            ) {
                Greeting("Hello Geeks for geeks")
            }
        }
    }
}
  
@Composable
fun Greeting(text: String) {
    Text(
        text = "$text!", color = Color(0xFF0F9D58), fontStyle = FontStyle.Italic, fontSize = 30.sp
    )
}


When we run the app we can see both XML’s Textview and Jetpack compose’ Text in the same page.

Output:

Composeview in XML layout

 



Similar Reads

Android - Interoperability in Jetpack Compose
Creating UI in Jetpack compose is fun, but it can be a blocker if we want to write some functionalities in our app which is not yet supported by Jetpack compose(like Google maps, admob) or some third-party libraries which are still not been migrated to Compose. Fortunately, Jetpack Compose supports various Interoperability APIs to make use of Tradi
4 min read
Android Runtime Permissions with Dexter using Android Jetpack Compose
Android applications require the usage of hardware devices within the android applications such as microphones or cameras. For using these devices within any android application. Permissions for using this hardware have to be provided to the application. For giving these permissions to the application runtime permissions are used. Handling permissi
7 min read
Start a New Activity using Intent in Android using Jetpack Compose
In Android OS, an Intent is a mechanism used to navigate a user to another activity or application to achieve a specific task. In general, Intents are used to progress to the next activity or come back to the previous activity. [caption width="800"] [/caption] In this article, we will show you how you could start a New Activity using Intent in Andr
4 min read
How to Update Data in API using Retrofit in Android using Jetpack Compose?
Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. Note: If you are seeking Java code f
9 min read
How to Post Data to API using Volley in Android using Jetpack Compose?
APIs are used within Android Applications to interact with a database to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post data to API in android using Volley in Jetpack Compose. Note: If you are
9 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose?
APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retrofit in Android using Jetpack Compose. Note: If you
9 min read
Shimmer Animation in Android using Jetpack Compose
Prerequisites: Basic Knowledge of KotlinBasic knowledge of Jetpack Compose Shimmer Animation was created by Facebook to show the loading screen while images are fetched from the server. Now we see shimmer animation in lots of places. In this article, we will take a look at the implementation of shimmer animation using the all-new Jetpack Compose. A
5 min read
Horizontal ListView in Android using Jetpack Compose
Many Android Applications present data in the form of horizontally scrollable lists. This list can be scrolled horizontally. In this article, we will take a look at How to Implement Horizontal ListView in Android Applications using Jetpack Compose. Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only avai
6 min read
Material Design Text Input Field using Jetpack Compose in Android
Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material design out of the box. In this article, we will explain
3 min read
How to Remove TextField Padding in Android using Jetpack Compose?
In Android Jetpack Compose, a TextField is used to take input from the user in the form of text. TextField when in focus or when clicked invokes a soft keyboard. In general, TextField is highly attributed for a better feel and appearance. However, we can use a pre-developed TextField, named BasicTextField, which has no attributes like that of a reg
3 min read
Article Tags :