我有一个RecyclerView,它有滑动手势删除行。RecyclerView的适配器数据不时被重置,在这种情况下,我将其适配器重新分配给一个新的适配器。虽然新的数据似乎反映在UI(即RecyclerView更新),滑动手势仍然反映旧的适配器。我期望attachToRecyclerView()
会处理旧的ToucherHelper的删除。根据attachToRecyclerView()
的文档:
将ItemTouchHelper附加到提供的RecyclerView。如果TouchHelper已经连接到一个RecyclerView,它将首先从前一个分离。你可以用null来调用这个方法,将它从当前的RecyclerView中分离出来。
然而,我的日志显示,当onSwiped()
被调用时,适配器的地址仍然是旧适配器的地址。
HistorySwipeHelper init itemCount 0 address 156969509
HistorySwipeHelper init itemCount 3 address 65479865
onSwiped itemCount 0 adapterPosition 0 address 156969509
setupRecyclerView() in MyFragment
private fun setupRecyclerView(historyList: MutableList<HistoryObject>) {
val historyListAdapter = HistoryListAdapter(historyList)
val callback = HistorySwipeHelper(historyListAdapter)
val helper = ItemTouchHelper(callback)
history_games_list.adapter = historyListAdapter
helper.attachToRecyclerView(history_games_list)
}
<标题>HistorySwipeHelper h1> 可以在Fragment上创建一个成员变量,它存储对当前ItemHelper的引用,并在附加新ItemHelper之前将其分离。这可以工作,但感觉像代码气味。是否有一种习惯的方式,我应该保持我的滑动手势与它们所连接的RecyclerView同步?标题>标题>
尝试手动加载recycleview
class HistorySwipeHelper(private val adapter: HistoryListAdapter) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
init {
Log.d("HistorySwipeHelper", "HistorySwipeHelper init itemCount ${adapter.itemCount} address ${System.identityHashCode(adapter)}")
}
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean { return false }
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
Log.d("HistorySwipeHelper", "onSwiped itemCount ${adapter.itemCount} adapterPosition ${viewHolder.adapterPosition} address ${System.identityHashCode(adapter)}")
if (viewHolder.adapterPosition < adapter.itemCount) {
adapter.showMenu(viewHolder.adapterPosition)
}
}
}.attachToRecyclerView(yourRecyclerView);