|
| 1 | +package com.example.compose.snippets.components |
| 2 | + |
| 3 | +import androidx.compose.foundation.layout.Column |
| 4 | +import androidx.compose.foundation.layout.Row |
| 5 | +import androidx.compose.foundation.layout.fillMaxWidth |
| 6 | +import androidx.compose.foundation.layout.height |
| 7 | +import androidx.compose.foundation.layout.padding |
| 8 | +import androidx.compose.foundation.selection.selectable |
| 9 | +import androidx.compose.foundation.selection.selectableGroup |
| 10 | +import androidx.compose.material3.MaterialTheme |
| 11 | +import androidx.compose.material3.RadioButton |
| 12 | +import androidx.compose.material3.Text |
| 13 | +import androidx.compose.runtime.Composable |
| 14 | +import androidx.compose.runtime.mutableStateOf |
| 15 | +import androidx.compose.runtime.remember |
| 16 | +import androidx.compose.ui.Alignment |
| 17 | +import androidx.compose.ui.Modifier |
| 18 | +import androidx.compose.ui.semantics.Role |
| 19 | +import androidx.compose.ui.tooling.preview.Preview |
| 20 | +import androidx.compose.ui.unit.dp |
| 21 | + |
| 22 | +// [START android_compose_components_radiobuttonsingleselection] |
| 23 | +@Composable |
| 24 | +fun RadioButtonSingleSelection(modifier: Modifier = Modifier) { |
| 25 | + val radioOptions = listOf("Calls", "Missed", "Friends") |
| 26 | + val (selectedOption, onOptionSelected) = remember { mutableStateOf(radioOptions[0]) } |
| 27 | + // Note that Modifier.selectableGroup() is essential to ensure correct accessibility behavior |
| 28 | + Column(modifier.selectableGroup()) { |
| 29 | + radioOptions.forEach { text -> |
| 30 | + Row( |
| 31 | + Modifier |
| 32 | + .fillMaxWidth() |
| 33 | + .height(56.dp) |
| 34 | + .selectable( |
| 35 | + selected = (text == selectedOption), |
| 36 | + onClick = { onOptionSelected(text) }, |
| 37 | + role = Role.RadioButton |
| 38 | + ) |
| 39 | + .padding(horizontal = 16.dp), |
| 40 | + verticalAlignment = Alignment.CenterVertically |
| 41 | + ) { |
| 42 | + RadioButton( |
| 43 | + selected = (text == selectedOption), |
| 44 | + onClick = null // null recommended for accessibility with screen readers |
| 45 | + ) |
| 46 | + Text( |
| 47 | + text = text, |
| 48 | + style = MaterialTheme.typography.bodyLarge, |
| 49 | + modifier = Modifier.padding(start = 16.dp) |
| 50 | + ) |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
| 55 | +// [END android_compose_components_radiobuttonsingleselection] |
| 56 | + |
| 57 | +@Preview |
| 58 | +@Composable |
| 59 | +private fun RadioButtonSingleSelectionPreview() { |
| 60 | + RadioButtonSingleSelection() |
| 61 | +} |
0 commit comments