0
0
Android Kotlinmobile~20 mins

Recomposition concept in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Recomposition Demo Screen
This screen demonstrates the recomposition concept in Jetpack Compose by updating a counter value when a button is clicked.
Target UI
-------------------------
| Recomposition Demo    |
|-----------------------|
| Count: 0              |
|                       |
| [Increase Count]      |
-------------------------
Display a text showing the current count starting at 0.
Add a button labeled 'Increase Count'.
When the button is clicked, increase the count by 1 and update the displayed count.
Use Jetpack Compose state to trigger recomposition.
Starter Code
Android Kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun RecompositionDemo() {
    // TODO: Add state and UI here
}

@Preview(showBackground = true)
@Composable
fun PreviewRecompositionDemo() {
    RecompositionDemo()
}
Task 1
Task 2
Task 3
Solution
Android Kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

@Composable
fun RecompositionDemo() {
    var count by remember { mutableStateOf(0) }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Center
    ) {
        Text(text = "Count: $count", style = MaterialTheme.typography.headlineMedium)
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = { count++ }) {
            Text("Increase Count")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewRecompositionDemo() {
    RecompositionDemo()
}

This example uses Jetpack Compose's remember and mutableStateOf to hold the count variable. When the button is clicked, count is incremented. Because count is a state variable, Compose automatically recomposes the UI to show the updated count. This demonstrates the recomposition concept where UI updates reactively when state changes.

Final Result
Completed Screen
-------------------------
| Recomposition Demo    |
|-----------------------|
| Count: 3              |
|                       |
| [Increase Count]      |
-------------------------
Tapping 'Increase Count' increments the number shown in 'Count' by 1.
The UI updates immediately without restarting the screen.
Stretch Goal
Add a reset button that sets the count back to zero.
💡 Hint
Add another Button composable below the first one with onClick resetting count to 0.