You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin开发:如何让单选按钮匹配数据库保存的值?

问题解决:单选按钮无法加载数据库保存的状态

你的问题核心在于:编辑条目时,单选按钮始终默认选中第一个选项,没有匹配数据库里保存的status值——而标题、描述字段能正常加载,是因为你初始化单选状态时没读取已保存的数据,硬编码成了默认选项。

问题代码定位

在CfhForm组合函数里,你这样初始化单选状态:

var status by remember { mutableStateOf(radioOptions[0]) }

这里直接固定为radioOptions[0](也就是"Open"),完全忽略了callforhelp对象里的已保存状态。但标题和描述都正确使用了callforhelp的对应值:

var title by remember { mutableStateOf(TextFieldValue(callforhelp?.title ?: "")) }
var description by remember { mutableStateOf(TextFieldValue(callforhelp?.description ?: "")) }

修复方案

修改status的初始化逻辑,优先使用callforhelp里的已保存状态,新增条目时才用默认选项:

var status by remember { 
    mutableStateOf(callforhelp?.status ?: radioOptions[0]) 
}

额外注意点

要确保数据库里保存的status值和radioOptions中的字符串完全一致(包括大小写、空格),比如数据库存的是"Ongoing"就不能写成"ongoing",否则会因匹配失败仍显示默认值。

修改后的CfhForm关键代码片段

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CfhForm(
    callforhelp: CallForHelp?,
    onSave: (icon: String, title: String, description: String, status: String) -> Unit
) {
    var title by remember { mutableStateOf(TextFieldValue(callforhelp?.title ?: "")) }
    var description by remember { mutableStateOf(TextFieldValue(callforhelp?.description ?: "")) }

    val radioOptions = listOf("Open","Ongoing","Closed")
    // 核心修改:从callforhelp读取已保存的status
    var status by remember { 
        mutableStateOf(callforhelp?.status ?: radioOptions[0]) 
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        radioOptions.forEach { caseStatus ->
            Row(verticalAlignment=Alignment.CenterVertically) {
                RadioButton(
                    selected = (caseStatus == status),
                    onClick = {
                        status = caseStatus
                    }
                )
                Text(
                    text = caseStatus,
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(start = 3.dp)
                )
            }
        }
        // 其余TextField、Button代码保持不变...
    }
}

内容的提问来源于stack exchange,提问作者MikkoR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:41:14