Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android Jetpack Compose Checkbox example
package app.ruyut.jetpackcompose
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Checkbox()
}
}
}
@Composable
fun Checkbox() {
val isChecked = remember { mutableStateOf(false) }
Row(
modifier = Modifier
.clickable(onClick = {
isChecked.value = !isChecked.value // 點擊文字時也能變更勾選狀態
})
.padding(16.dp),
) {
Checkbox(
checked = isChecked.value, // 是否勾選
enabled = true, // 能否被變更
onCheckedChange = { checked ->
isChecked.value = checked
},
colors = CheckboxDefaults.colors(
checkedColor = MaterialTheme.colors.primarySurface, // 勾選時顏色
uncheckedColor = MaterialTheme.colors.primary, // 未勾選時顏色
)
)
Text(
text = "Ruyut",
color = MaterialTheme.colors.secondaryVariant,
modifier = Modifier
.padding(start = 8.dp)
.align(Alignment.CenterVertically)
)
}
}
@Preview(
name = "Checkbox",
uiMode = Configuration.UI_MODE_NIGHT_NO,
showBackground = true,
)
@Preview(
name = "Dark Mode",
uiMode = Configuration.UI_MODE_NIGHT_YES,
showBackground = true,
)
@Composable
fun Test() {
Checkbox()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment