To create a checkbox with a listener in Jetpack Compose, you can use the Checkbox
composable along with a state to track the checkbox’s checked state. Here’s a simple example:
package com.androindian.check
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
CheckboxWithListener()
}
}
}
}
@Composable
fun CheckboxWithListener() {
var isChecked by remember { mutableStateOf(false) }
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Checkbox(
checked = isChecked,
onCheckedChange = { checked ->
isChecked = checked
// Listener action
if (checked) {
println("Checkbox checked!")
} else {
println("Checkbox unchecked!")
}
}
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = if (isChecked) "Checked" else "Unchecked")
}
}
}
Explanation:
- State Management:
var isChecked by remember { mutableStateOf(false) }
tracks the checkbox’s state.remember
ensures the state is retained across recompositions.
- Checkbox:
checked
: Determines if the checkbox is checked.onCheckedChange
: Listener that triggers when the checkbox’s state changes.
- UI Update:
- The
Text
composable dynamically updates based on theisChecked
state.
- The
- Actions:
- Inside
onCheckedChange
, you can add logic to respond to checkbox changes.
- Inside
Run the app, and you’ll see a checkbox with text updating dynamically.