Sobes.tech
Junior — Middle

How to integrate Jetpack Compose into an existing project using XML layout?

sobes.tech AI

Answer from AI

To integrate Jetpack Compose into an existing Android project with XML layout, you can use Compose within individual components or screens without rewriting the entire UI at once.

Main steps:

  1. Add Compose dependencies to build.gradle:
implementation "androidx.compose.ui:ui:<version>"
implementation "androidx.compose.material:material:<version>"
implementation "androidx.compose.ui:ui-tooling-preview:<version>"
implementation "androidx.activity:activity-compose:<version>"
  1. In an existing Activity or Fragment, create a ComposeView and add it to the hierarchy or use setContent in the Activity:
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyComposeContent()
        }
    }
}
  1. To mix with XML, you can insert a ComposeView into XML:
<androidx.compose.ui.platform.ComposeView
    android:id="@+id/compose_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

And in code:

val composeView = findViewById<ComposeView>(R.id.compose_view)
composeView.setContent {
    MyComposeContent()
}

This way, you can gradually migrate the UI, using Compose for new screens or components while preserving the existing XML layout.