Sat. Jan 4th, 2025

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:

  1. State Management:
    • var isChecked by remember { mutableStateOf(false) } tracks the checkbox’s state.
    • remember ensures the state is retained across recompositions.
  2. Checkbox:
    • checked: Determines if the checkbox is checked.
    • onCheckedChange: Listener that triggers when the checkbox’s state changes.
  3. UI Update:
    • The Text composable dynamically updates based on the isChecked state.
  4. Actions:
    • Inside onCheckedChange, you can add logic to respond to checkbox changes.

Run the app, and you’ll see a checkbox with text updating dynamically.

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *