I use RecyclerView's ItemTouchHelper to change the order(drag & drop),And I want to move only a part of the list. I don't want to move after a certain index. How can I handle it with one RecyclerView?
If I explain a little more about what I want to make, The active items are sorted up and the non-active items are sorted down. And only the activated items will shift the order. Right now, when I drag an active item, it goes down to the area of the non-active item, but I want to prevent it from going down. How can I do it?
UPDATE
open class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter) :
ItemTouchHelper.Callback() {
private var isLongPressDrag = true
fun setLongPressDragEnable(isLongPressDrag: Boolean) {
this.isLongPressDrag = isLongPressDrag
}
override fun isLongPressDragEnabled() = isLongPressDrag
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
val dragFlags = ItemTouchHelper.UP or ItemTouchHelper.DOWN
val swipeFlags = 0
return makeMovementFlags(dragFlags, swipeFlags)
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return mAdapter.onItemMove(viewHolder.adapterPosition, target.adapterPosition)
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, i: Int) {
mAdapter.onItemDismiss(viewHolder.adapterPosition)
}
}
Use ItemTouchHelper.SimpleCallback
and override getDragDirs
and onMove
methods:
ItemTouchHelper.SimpleCallback(
UP or DOWN,
0
) {
override fun getDragDirs(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
val selectedPosition = viewHolder.adapterPosition
val isActive: Boolean = // retrieve your model from list and check its active state
return if (isActive) super.getDragDirs(recyclerView, viewHolder) else 0
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder,
): Boolean {
val toPosition = target.adapterPosition
val isActiveTarget: Boolean = // retrieve your target model from list and check its active state
if (!isActiveTarget) return false
val fromPosition = viewHolder.adapterPosition
moveItem(fromPosition, toPosition)
return true
}
}
Returning 0
on getDragDirs
prevents inactive item selection, while returning false
on onMove
prevents item movement while dragging.