本教程将介绍在没有单选按钮的Jetpack Compose中创建切换按钮组的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。
问题描述
我正尝试在我的项目中放置一个按钮切换组,它的行为类似于单选按钮组,但看起来不像单选按钮组(即,当选择一个按钮时,其他按钮将被取消选择)。
我遵循了我在网上找到的单选按钮模式,但这似乎没有起到作用。有办法做到这一点吗?我已经将按钮放在我想要的位置,但它们都被禁用了。
MovieSpotterTheme() {
Card(
modifier = Modifier
.fillMaxWidth()
) {
@Composable
fun MaterialButtonToggleGroup() {
var selected by remember { mutableStateOf("Android") }
val buttonGroup = listOf("Popular Movies", "Search Movies")
val onSelectedChange = { text: String ->
selected = text
}
Row(
horizontalArrangement = Arrangement.SpaceEvenly
) {
buttonGroup.forEach { text ->
Row(Modifier
.selectable(
selected = (text == selected),
onClick = { onSelectedChange(text) }
)
.padding(horizontal = 16.dp)
) {
Button(
enabled = (text == selected),
onClick = { onSelectedChange(text) }
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = text,
style = MaterialTheme.typography.body1.merge(),
modifier = Modifier.padding(horizontal = 16.dp)
)
}
}
}
}
}
}
Surface() {
MaterialButtonToggleGroup()
}
}
}
推荐答案
提供简化版本。使用它来满足您的需求。
@Composable
fun CustomRadioGroup() {
val options = listOf(
"Option 1",
"Option 2",
"Option 3",
"Option 4",
)
var selectedOption by remember {
mutableStateOf("")
}
val onSelectionChange = { text: String ->
selectedOption = text
}
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize(),
) {
options.forEach { text ->
Row(
modifier = Modifier
.padding(
all = 8.dp,
),
) {
Text(
text = text,
style = typography.body1.merge(),
color = Color.White,
modifier = Modifier
.clip(
shape = RoundedCornerShape(
size = 12.dp,
),
)
.clickable {
onSelectionChange(text)
}
.background(
if (text == selectedOption) {
Color.Magenta
} else {
Color.LightGray
}
)
.padding(
vertical = 12.dp,
horizontal = 16.dp,
),
)
}
}
}
}
好了关于在没有单选按钮的Jetpack Compose中创建切换按钮组的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。