Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created December 23, 2021 15:29
Show Gist options
  • Save ruyut/7958022b2237f78440d42044fab42611 to your computer and use it in GitHub Desktop.
Save ruyut/7958022b2237f78440d42044fab42611 to your computer and use it in GitHub Desktop.
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