Last active
January 8, 2022 08:23
-
-
Save kirmartuk/a93fb5519ac44bb6170ce800d3b76ef8 to your computer and use it in GitHub Desktop.
[Jetpack Compose] Android dialog for choosing one option of list. Use material3(You) https://m3.material.io/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun SingleChoiceDialog( | |
title: String, | |
radioOptions: List<String>, | |
indexOfDefault: Int, | |
isDialogVisible: (Boolean) -> Unit, | |
setSelectedItem: (String) -> Unit | |
) { | |
val (selectedItemIndex, setSelectedItemIndex) = remember { | |
mutableStateOf(indexOfDefault) | |
} | |
AlertDialog( | |
title = { Text(text = title) }, | |
text = { | |
RadioItem(radioOptions, selectedItemIndex, setSelectedItemIndex) | |
}, | |
onDismissRequest = { | |
isDialogVisible(false) | |
}, | |
dismissButton = { | |
TextButton(onClick = { isDialogVisible(false) }) { | |
Text(text = stringResource(id = R.string.dialog_cancel)) | |
} | |
}, | |
confirmButton = { | |
TextButton(onClick = { | |
isDialogVisible(false) | |
setSelectedItem(radioOptions[selectedItemIndex]) | |
}) { | |
Text(text = stringResource(id = R.string.dialog_ok)) | |
} | |
} | |
) | |
} | |
@Composable | |
fun RadioItem(items: List<String>, selectedItemIndex: Int, setIndexOfSelected: (Int) -> Unit) { | |
Column(modifier = Modifier.fillMaxWidth()) { | |
items.forEachIndexed { index, text -> | |
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier | |
.fillMaxWidth() | |
.clickable { | |
setIndexOfSelected(index) | |
}) { | |
RadioButton( | |
selected = (index == selectedItemIndex), | |
onClick = { | |
setIndexOfSelected(index) | |
} | |
) | |
Text( | |
text = text | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment