How to integrate Jetpack Compose with other Android components?

Integrating Jetpack Compose with traditional Android components can enhance your application by leveraging the best of both worlds. This allows developers to use Jetpack Compose for UI while maintaining compatibility with existing Views and other Android components.

Example: Integrating Jetpack Compose with XML Layout

In this example, we will demonstrate how to integrate a Jetpack Compose component into an XML layout using a ComposeView.

<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Welcome to my app!" /> <androidx.compose.ui.platform.ComposeView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/compose_view" app:composeContent="@{composeComponent}" /> </LinearLayout> </layout>

In your activity, you can set the content of the ComposeView like this:

import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.platform.ComposeView class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { YourComposeContent() } } @Composable fun YourComposeContent() { Text(text = "Hello from Jetpack Compose!") } }

Keywords: Jetpack Compose Android XML Layout ComposeView Integration Android Components