Issue
I am trying to do a survey app using Jetpack Compose and RadioButtons. I created a list with questions and answers
val surveyQuestions = listOf(
Question("question 1", listOf("answer 1", "answer 2")),
Question("question 2", listOf("answer 1", "answer 2", "answer 3")),
Question("question 3", listOf("answer 1", "answer 2"))
)
I created also a view (attachment).
How can I limit the number of answers to be selected to 1 per question?
How can I save the survey result in the form of listOf(question1 - answer2, question2 - answer), etc.?
Solution
You need to store the selection as state. It depends on your data model, for example you can use mutableStateMapOf:
val selectionStates = remember { mutableStateMapOf<Int, Int>()}
surveyQuestions.forEachIndexed { i, question ->
question.answers.forEachIndexed { j, answer ->
RadioButton(selected = selectionStates[i] == j, onClick = { selectionStates[i] = j })
}
}
If you are using the Lazy view, you can replace forEachIndexed with itemsIndexed.
You can also move selectionStates from composable to view model to make sure it is not destroyed by rotation in case you support this.
Answered By - Philip Dukhov

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.