我正在为一个需要在回收器视图中实现的功能而挣扎,我需要根据对任何子项执行的操作更新几个子项。
例如,我有回收商视图,比如说10件
- 孩子1
- 儿童2
- 儿童3
- -
- -
- 儿童10
现在一次只有5个孩子在屏幕上可见,其余的只有在滚动列表时才会出现。我想要实现的是,当我点击child 1并执行一个操作时,该操作会返回我随机更新child 4、child 7&儿童8
现在的问题是如何更新列表中不可见的子项。
我已经尝试使用以下解决方案:-
val childCount = rvQuestion.childCount
for (i in 0 until childCount) {
val child = rvQuestion.getChildAt(i)
.findViewById<TextInputEditText>(R.id.etQuestion)
val questionHint = child.hint
// list is the list of child that needs to be populated with a hint
if(list.contains(questionHint)) {
child.setText("someValue")
}
}
问题是recycler视图从未给出childCount,因为它只给出了5,而这5是当前可见的,因此更新了错误的child。
还有其他办法吗?
您需要使用RecyclerView
适配器来获取子项计数并更新任何子项。适配器需要重写getItemCount
函数,该函数应返回列表中的总项。尝试直接从RecyclerView
获取子项计数或更新子项不是正确的方法。
class TestAdapter(private val data: MutableList<String>) : RecyclerView.Adapter<TestAdapter.ViewHolder>() {
...
override fun getItemCount(): Int {
return data.size
}
...
}
要更新RecyclerView
中的子级,您需要告诉适配器也要这样做。在适配器中,您可以创建一个方法,该方法接受索引和任何其他必要的数据来更新子级。
class TestAdapter(private val data: MutableList<String>) : RecyclerView.Adapter<TestAdapter.ViewHolder>() {
...
fun updateChildAt(idx: Int, newValue: String) {
data[idx] = newValue
notifyItemChanged(idx)
}
...
}