为了使ViewHolder单独处理每个单选按钮,而不重复使用以前单选按钮的状态,我将单选按钮项是否被选中的状态存储在布尔值列表中,并根据该列表设置单选按钮状态.但是,当我向下和向上滚动时,被切换的单选按钮会被随机取消切换,即使isCheckedList包含每个单选按钮的正确布尔信息(我用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
}
}