How to add CheckBox in Android Jetpack Compose

By Mohammed Rashid •  November 18th, 2022 • 

A checkbox is considered as a useful UI element through which users can select multiple options by just checking and unchecking. Let’s learn how to add a checkbox in Android using Jetpack Compose.

Jetpack Compose has a dedicated compose named Checkbox for this purpose. Using remember and mutableStateOf we can manage the check state. See the code snippet given below.

@Composable
fun CheckboxExample() {
    val checkedState = remember { mutableStateOf(true) }
    Checkbox(
        checked = checkedState.value,
        onCheckedChange = { checkedState.value = it },
        colors = CheckboxDefaults.colors(Color.Red)
    )
}

The checkedState variable holds the boolean value that whether the Checkbox is checked or not. Through onCheckedChange the variable is updated with the current state of the Checkbox. I also choose red as the Checkbox color.

Jetpack Compose Checkbox

Following is the complete code for reference.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background,
                    modifier = Modifier.fillMaxWidth().fillMaxHeight()
                ) {
                    CheckboxExample()
                }
            }
        }
    }
}

@Composable
fun CheckboxExample() {
    val checkedState = remember { mutableStateOf(true) }
    Checkbox(
        checked = checkedState.value,
        onCheckedChange = { checkedState.value = it },
        colors = CheckboxDefaults.colors(Color.Red)
    )
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        CheckboxExample()
    }
}

For more information about Checkbox, you may go to the official documentation.

Mohammed Rashid

Keep Reading