I am getting the all views but when I click the button and scroll down at that time the it will be unchecked. I added the removeall views on the onBindViewHolder
. because the radiobuttons are generated infinite times. Here I shared the code please check it.
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.radioGrp.setOrientation(RadioGroup.VERTICAL)
holder.radioGrp.removeAllViews()
holder.bindView(position)
}
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val radioGrp = itemView.findViewById<RadioGroup>(R.id.radio_group)
fun bindView(position: Int) {
itemView.tv_question.text = feedback[position].questions
var newAnswer = feedback[position].answser as ArrayList<String>
if (newAnswer.isEmpty()) {
itemView.linear2.visibility = View.VISIBLE
} else {
newAnswer.forEach {
itemView.linear2.visibility = View.GONE
val rb = RadioButton(context)
rb.text = it
rb.id = position
radioGrp.addView(rb)
rb?.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener {
buttonView, isChecked ->
if (isChecked) {
rb.isChecked = true
examinationListener.addAnswer(names)
} else {
rb.isChecked = false
examinationListener.removeAnswer(names as String)
}
})
}
}
}
}
You need to track the checked state of your answers externally to the views and apply the state when binding the views. Assuming the answers for each list item are all unique Strings, you could use a Map to store the states.
// In your adapter:
val answerStates = mutableMapOf<Int, MutableMap<String, Boolean>>()
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val radioGrp = itemView.findViewById<RadioGroup>(R.id.radio_group)
fun bindView(position: Int) {
itemView.tv_question.text = feedback[position].questions
val newAnswer = feedback[position].answser as ArrayList<String>
if (newAnswer.isEmpty()) {
itemView.linear2.visibility = View.VISIBLE
} else {
itemView.linear2.visibility = View.GONE
// Lazily create answer states map for this list item
val answerStates = answerStates[position]
?: mutableMapOf<String, Boolean>().also { answerStates[position] = this }
newAnswer.forEach {
val rb = RadioButton(context)
rb.text = it
rb.id = position
rb.checked = answerStates[it] ?: false // Bind last known state, default false
radioGrp.addView(rb)
rb?.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener {
buttonView, isChecked ->
answerStates[it] = isChecked // Save state
if (isChecked) {
rb.isChecked = true
examinationListener.addAnswer(names)
} else {
rb.isChecked = false
examinationListener.removeAnswer(names as String)
}
})
}
}
}
}
If your data can change, this gets more complicated. You would need to store this Boolean in your actual Feedback class so it can be restored when there is fresh data.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.