Question #382MediumNative Android

What is Jetpack Compose and how is it different from XML layouts?

#jetpack-compose#xml#android

Answer

Overview

Jetpack Compose is Android's modern declarative UI toolkit.


Key Differences

FeatureXMLJetpack Compose
ParadigmImperativeDeclarative
LanguageXML + Java/KotlinPure Kotlin
Code LocationSeparate filesSingle file
Type Safety❌ Runtime errors✅ Compile-time
PreviewLimited@Preview annotations
Hot ReloadNoYes (limited)

XML Approach

###layout/activity_main.xml

xml
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello" />
    
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click" />
</LinearLayout>

Activity Code

kotlin
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        val textView = findViewById<TextView>(R.id.textView)
        val button = findViewById<Button>(R.id.button)
        button.setOnClickListener {
            textView.text = "Clicked!"
        }
    }
}

Compose Approach

kotlin
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApp()
        }
    }
}

@Composable
fun MyApp() {
    var text by remember { mutableStateOf("Hello") }
    
    Column {
        Text(text)
        Button(onClick = { text = "Clicked!" }) {
            Text("Click")
        }
    }
}

@Preview
@Composable
fun MyAppPreview() {
    MyApp()
}

Advantages of Compose

1. Less Code

  • No findViewById
  • No separate XML files
  • Single source of truth

2. Type Safety

kotlin
// XML - runtime error
android:text="@string/missing_key" 

// Compose - compile error
Text(stringResource(R.string.missing_key))

3. Easy Conditionals

kotlin
@Composable
fun UserProfile(user: User?) {
    if (user != null) {
        Text(user.name)
    } else {
        Text("Guest")
    }
}

4. Reactive UI

kotlin
@Composable
fun Counter() {
    var count by remember { mutableStateOf(0) }
    Button(onClick = { count++ }) {
        Text("Count: $count") // Auto-updates
    }
}

Bottom Line: Compose = Modern, declarative, Kotlin-first. XML = Legacy, imperative.