0
0
Android Kotlinmobile~15 mins

rememberSaveable for configuration changes in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: RememberSaveable Demo
This screen shows a counter that keeps its value even when the device is rotated or configuration changes happen.
Target UI
---------------------
| RememberSaveable  |
| Demo Screen       |
|                   |
| Count: 0          |
|                   |
| [Increment]       |
---------------------
Display a count starting at 0
Add a button labeled 'Increment' that increases the count by 1 when tapped
Use rememberSaveable to keep the count value across configuration changes like screen rotation
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 RememberSaveableDemo() {
    // TODO: Add rememberSaveable state for count
    // TODO: Display count and button
}

@Preview(showBackground = true)
@Composable
fun PreviewRememberSaveableDemo() {
    RememberSaveableDemo()
}
Task 1
Task 2
Task 3
Task 4
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 RememberSaveableDemo() {
    var count by rememberSaveable { 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("Increment")
        }
    }
}

@Preview(showBackground = true)
@Composable
fun PreviewRememberSaveableDemo() {
    RememberSaveableDemo()
}

We use rememberSaveable to create a state variable count that survives configuration changes like screen rotations. This means when the user rotates the device, the count value does not reset to zero.

The UI shows the current count and a button labeled 'Increment'. When the button is tapped, the count increases by 1 and the UI updates automatically.

The Column arranges the text and button vertically with some spacing for a clean layout.

Final Result
Completed Screen
---------------------
| RememberSaveable  |
| Demo Screen       |
|                   |
| Count: 5          |
|                   |
| [Increment]       |
---------------------
Tapping 'Increment' increases the count number by 1
Rotating the device keeps the count value unchanged
Stretch Goal
Add a 'Reset' button that sets the count back to zero
💡 Hint
Add another Button below the Increment button with onClick resetting count to 0