为了使 ViewHolder 分别处理每个单选按钮而不重复使用以前的单选按钮的状态,我将单选按钮项的状态存储在 bool 列表中,并根据该列表设置单选按钮状态。但是当我向下和向上滚动时,即使 isCheckedList 包含每个单选按钮的正确 bool 信息,切换的单选按钮也会随机取消切换(我使用 logd() 打印列表以验证它是否实际存储状态)
知道我缺少什么吗?
class QuestionAdapter(context: Context) :
RecyclerView.Adapter<QuestionAdapter.QuestionViewHolder>() {
private val listOfQuestion: List<String>
private val listSize = 20
private val isCheckedList: MutableList<Boolean> = MutableList(listSize) { false }
//Initialize a list of 20 questions.
init {
val allQuestions = context.resources.getStringArray(R.array.questions).toList()
listOfQuestion = allQuestions
.shuffled()
.take(listSize)
}
class QuestionViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
val questionText = view.findViewById<TextView>(R.id.question)
val radioButton = view.findViewById<RadioButton>(R.id.yes)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuestionViewHolder {
val layout = LayoutInflater
.from(parent.context)
.inflate(R.layout.item_view, parent, false)
return QuestionViewHolder(layout)
}
override fun onBindViewHolder(holder: QuestionViewHolder, position: Int) {
val item = listOfQuestion[position]
holder.questionText.text = item
holder.radioButton.isChecked = isCheckedList[position]
holder.radioButton.setOnCheckedChangeListener { _, isChecked ->
isCheckedList[holder.adapterPosition] = isChecked
Log.d("Adapter", "list: $isCheckedList ")
}
}
override fun getItemCount(): Int {
return listOfQuestion.size
}
}
最佳答案
在设置正确的值之前,您需要清除单选按钮上的选择。
holder.radioGroup.clearCheck()
这样,RadioGroup
清除其选择,准备接收将触发正确 RadioButton
的输入经检查。但是您需要注意,这可能会调用您的
onCheckedChanged
听众,并可能带来意想不到的结果。但是对于由此产生的问题有一个解决方法。// Nullify listener
holder.radioGroup.setOnCheckedChangeListener(null);
// Clear selection
holder.radioGroup.clearCheck();
// Reset listener after selection has been cleared
holder.radioGroup.setOnCheckedChangeListener(checkedChangeListener);
关于android - 即使我在单选按钮上明确设置了选中状态,RecyclerView 中的单选按钮也会随机取消选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72003133/