[내일배움캠프] 캠프 19주차 - 3/20(수) #RecyclerView #Drag&Drop

0
post-thumbnail

📝TIL

RecyclerView 항목 롱클릭 후 Drag & Drop으로 순서 변경하기

📌참고자료:

Drag & Drop 처리를 위한 Simple Callback 클래스 생성

  • ItemTouchHelper.SimpleCallback 생성하기
    • dragDirs: 뷰가 drag 될 수 있는 방향 플래그 (LEFT, RIGHT, START, END, UP, DOWN)
    • swipeDirs: 뷰가 swipe 될 수 있는 방향 플래그 (LEFT, RIGHT, START, END, UP, DOWN)
    public SimpleCallback(int dragDirs, int swipeDirs)
  • 위아래로 drag & drop하여 순서 변경을 구현할 것이므로,
    dragDirs로 ItemTouchHelper.UP or ItemTouchHelper.DOWN or ItemTouchHelper.START or ItemTouchHelper.END 넘겨주기
    (스와이프 사용 X -> swipeDirs로 0 넘겨주기)
import java.util.Collections

class ItemTouchSimpleCallback : ItemTouchHelper.SimpleCallback(
    		ItemTouchHelper.UP
            or ItemTouchHelper.DOWN
            or ItemTouchHelper.START
            or ItemTouchHelper.END,
    		0 
) {

    override fun onMove(
        recyclerView: RecyclerView,
        selectedViewHolder: RecyclerView.ViewHolder,
        targetViewHolder: RecyclerView.ViewHolder
    ): Boolean {
        // TODO 순서 변경 구현하기
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        // Do Nothing
    }
}

Simple Callback을 갖는 ItemTouchHelper 클래스에 RecyclerView Attach하기

  val itemTouchHelper = ItemTouchHelper(ItemTouchSimpleCallback())
  itemTouchHelper.attachToRecyclerView(binding.rvRouteRecyclerview)

Drag & Drop 처리하기

    override fun onMove(
        recyclerView: RecyclerView,
        selectedViewHolder: RecyclerView.ViewHolder,
        targetViewHolder: RecyclerView.ViewHolder
    ): Boolean {
        val routeAdapter = recyclerView.adapter as RouteAdapter

        val fromPosition = selectedViewHolder.absoluteAdapterPosition
        val toPosition = targetViewHolder.absoluteAdapterPosition

        routeAdapter.notifyItemMoved(fromPosition, toPosition)
        return true
    }

profile
Be able to be vulnerable, in search of truth

0개의 댓글