RecyclerView 下降
RecyclerView on drop
我有 RecyclerView
拖放功能,但我想在 Drop 上做一些计算。当我将 expensiveFunction()
放入 onMove()
时,它会在每次位置变化时触发,直到拖动结束。这是一个很大的矫枉过正。有没有办法在拖动结束时触发功能?
val itemTouchHelper = ItemTouchHelper(simpleCallback)
itemTouchHelper.attachToRecyclerView(recyclerView)
private var simpleCallback = object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP.or(ItemTouchHelper.DOWN), 0) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val startPosition = viewHolder.absoluteAdapterPosition
val endPosition = target.absoluteAdapterPosition
Collections.swap(itemList, startPosition, endPosition)
recyclerView.adapter?.notifyItemMoved(startPosition, endPosition)
expensiveFunction()
return true
}
}
您可以覆盖 onSelectedChanged()
,当 ViewHolder
被 ItemTouchHelper
滑动或拖动时调用它。
要捕捉掉落动作,请检查 actionState
值为 ItemTouchHelper.ACTION_STATE_IDLE
:
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
when (actionState) {
// when the item is dropped
ItemTouchHelper.ACTION_STATE_IDLE -> {
Log.d(TAG, "Item is dropped")
}
}
}
我有 RecyclerView
拖放功能,但我想在 Drop 上做一些计算。当我将 expensiveFunction()
放入 onMove()
时,它会在每次位置变化时触发,直到拖动结束。这是一个很大的矫枉过正。有没有办法在拖动结束时触发功能?
val itemTouchHelper = ItemTouchHelper(simpleCallback)
itemTouchHelper.attachToRecyclerView(recyclerView)
private var simpleCallback = object : ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP.or(ItemTouchHelper.DOWN), 0) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val startPosition = viewHolder.absoluteAdapterPosition
val endPosition = target.absoluteAdapterPosition
Collections.swap(itemList, startPosition, endPosition)
recyclerView.adapter?.notifyItemMoved(startPosition, endPosition)
expensiveFunction()
return true
}
}
您可以覆盖 onSelectedChanged()
,当 ViewHolder
被 ItemTouchHelper
滑动或拖动时调用它。
要捕捉掉落动作,请检查 actionState
值为 ItemTouchHelper.ACTION_STATE_IDLE
:
override fun onSelectedChanged(viewHolder: RecyclerView.ViewHolder?, actionState: Int) {
super.onSelectedChanged(viewHolder, actionState)
when (actionState) {
// when the item is dropped
ItemTouchHelper.ACTION_STATE_IDLE -> {
Log.d(TAG, "Item is dropped")
}
}
}