Checkbox in Android using Jetpack Compose
The checkbox is a composable function that is used to represent two states of any item in Android. It is used to differentiate an item from the list of items. In this article, we will take a look at the implementation of Simple Checkbox in Android using Jetpack Compose.
Attributes of Checkbox
Attributes | Uses |
---|---|
checked | this is used to set our checkbox checked or unchecked on app launch. |
onCheckedChange | this is a callback that will receive when there is a change in events whether the checkbox is checked or unchecked. |
modifier | this is used to add beautification to our checkbox in the sense of padding, margin, and other properties. |
color | this parameter is used to add color to our checkbox in the default case the checkbox color is a secondary color in the app theme. |
enabled | this parameter is used to add a boolean value that determines whether the checkbox is enabled. |
interactionSource | this parameter uses an interaction source that handles interaction events for the checkbox. |
Step-by-Step Implementation
Step 1: Create a New Project
To create a new project in the Android Studio please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Navigate to the app > java > {package name} > MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to help you understand the code in more detail.
MainActivity.kt:
package com.geeksforgeeks.demo
import android.os.Bundle
import androidx.activity.*
import androidx.activity.compose.setContent
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
Column {
Component()
}
}
}
}
@Composable
fun Component() {
// set the state of our checkbox.
val isChecked = remember { mutableStateOf(false) }
// creating a checkbox in a Column.
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Checkbox(
// set the state of checkbox.
checked = isChecked.value,
onCheckedChange = { isChecked.value = it },
modifier = Modifier.padding(8.dp),
enabled = true,
colors = CheckboxDefaults.colors(
checkedColor = Color.Green,
uncheckedColor = Color.DarkGray,
checkmarkColor = Color.White
),
interactionSource = remember { MutableInteractionSource() }
)
Text(
text = if (isChecked.value) "Checked" else "Unchecked",
modifier = Modifier.padding(top = 8.dp)
)
}
}