我正在嘗試使用Jetpack Compose和RadioButtons做一個調查應用程式。 我創建了一個帶有問題和答案的串列
val surveyQuestions = listOf(
Question("問題1", listOf("答案1", "答案2"))。)
Question("問題2", listOf("答案1", "答案2", "答案3")。
Question("問題3", listOf("答案1", "答案2")
)
我還創建了一個視圖(附件)。
我怎樣才能將每個問題的答案選擇數量限制在1個?
我如何以listOf(question1 - answer2, question2 - answer)等形式保存調查結果?
uj5u.com熱心網友回復:
我會把這些重要的資訊以串列的形式存盤在viewmodel里面
var markedAnswers = mutableStateListOf<Int> ()
然后添加一個更新機制
fun onAnswerUpdate(index: Int, newAnswer: Int){
markedAnswer[index] = newAnswer
}
現在,只要把這個getter和setter傳給Composables就可以了
MainActivity{
val viewModel by viewModels<...> (()
MyQuestionsComposable(
answers = viewModel.markedAnswers,
onAnswerUpdate = viewModel::onAnswerUpdate,
...
)
}
fun MyQuestionsComposable (
問題。List<Question>, // I assume
答案。List,
onAnswerUpdate: (index, newAnswer) -> Unit; Unit
){
//I assume every question has three options for simplicity。
/*而且你必須能夠訪問問題的索引,就像截圖中看起來的那樣,不是嗎?
//I'm using a loop for simpleicity to gain the index, but you could do anything per your model
questions.forEachIndexed{ index, question ->
調查專案(
selectedAnswer = answers [index],
onAnswerUpdate = onAnswerUpdate,
選項。List<...>
)
}
fun SurveyItem(
selectedAnswer: Int,
選項。List<...>。
onAnswerUpdate: (index, newAnswer) -> Unit; Unit
){
options.forEachIndexed{index, option ->
OptionComposable(
modifier = Modifier.clickable(onClick = onAnswerUpdate(index, option))。
selected = option == selectedAnswer
)
}
}
``
我將選定的答案存盤為索引,并在調查中交叉參考它們。由于它是可變的狀態,選擇將在修改后自動更新,我已經實作了這種方式,在一個特定的時間,只能選擇一個答案。
我一直在遵循單向資料流,所以它是最好的實踐。不要擔心這個問題。
有任何疑問,請在下面評論。
uj5u.com熱心網友回復:
你需要將選擇存盤為state。這取決于你的資料模型,例如你可以使用mutableStateMapOf:
val selectionStates = remember { mutableStateMapOf<Int, Int> ()}
surveyQuestions.forEachIndexed { i, question ->
question.answer.forEachIndexed { j, answer ->
RadioButton(selected = selectionStates[i] == j, onClick = { selectionStates[i] = j })
}
}
如果你使用的是Lazy視圖,你可以將forEachIndexed替換為itemsIndexed。
你也可以將selectionStates從composable移到view model以確保它不會被旋轉破壞,以防你支持這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/313077.html
標籤:

