我会将如此重要的信息存储在视图模型中作为列表,例如
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,
...
)
}
@Composable
fun MyQuestionsComposable (
questions: List<Question>, // I assume
answers: List,
onAnswerUpdate: (index, newAnswer) -> Unit
){
//I assume every question has three options for simplicity
/*and you must have access to the index of the question as it seems in the screenshot don't you?*/
//I'm using a loop for simplicity to gain the index, but you could do anything per your model
questions.forEachIndexed{ index, question ->
SurveyItem(
selectedAnswer = answers [index],
onAnswerUpdate = onAnswerUpdate,
options: List<...>
)
}
@Composable
fun SurveyItem(
selectedAnswer: Int,
options: List<...>,
onAnswerUpdate: (index, newAnswer) -> Unit
){
options.forEachIndexed{index, option ->
OptionComposable(
modifier = Modifier.clickable(onClick = onAnswerUpdate(index, option)),
selected = option == selectedAnswer
)
}
}
``
I'm storing selected answers as indices, and cross referencing them in the survey. Since it is mutable state, the selections will automatically update upon modification, and i have implemented this in a way that at a given time, only one answer can be selected.
I have followed Unidirectional Data Flow all over so it's best practiced. Don't worry about that.
Any doubts, just comment below.