Android RecyclerView拖动滑拽的实现

最近做项目遇到了需要拖动recyclerView的item,并且拖动后数据源也根据拖动顺序而变化,在此简单记录下。
参考的文章链接:
1.https://blog.csdn.net/anyudong123/article/details/82861870;
2.https://blog.csdn.net/qq_38686506/article/details/120130520?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.no_search_link

ItemTouchHelper关联RecyclerView

ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new  MyItemTouchHelperCallBack());
itemTouchHelper.attachToRecyclerView(mMainRecyclerView);

实现接口

public class MyItemTouchHelperCallBack extends ItemTouchHelper.Callback {

@Override
public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
    // 长按拖动,不可删除,可换位使用
    int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;

    // 轻扫轻按可滑动删除
      // int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
    return makeMovementFlags(dragFlags, 0);
}

// 拖拽 排序item时调用
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
    int form = viewHolder.getAdapterPosition();
    int to = target.getAdapterPosition();

    boolean isMove = false;
   //AlbumPanoramaAdapter拖拽的适配器
    AlbumPanoramaAdapter adapter = (AlbumPanoramaAdapter) recyclerView.getAdapter();
      try {
      //adapter.getPanoramaDataBeanList()  拖拽的适配器里的数据源
        if (adapter != null && adapter.getPanoramaDataBeanList().size() > 0) {
            if (form < to) {
                //从上往下拖动,每滑动一个item,都将list中的item向下交换,向上滑同理。
                for (int i = form; i < to; i++) {
                    Collections.swap(adapter.getPanoramaDataBeanList(), i, i + 1);//交换数据源两个数据的位置
                }
            } else {
                for (int i = form; i > to; i--) {
                    Collections.swap(adapter.getPanoramaDataBeanList(), i, i - 1);//交换数据源两个数据的位置
                }
            }

        // adapter.notifyDataSetChanged();//这个方法也可解决拖动后item边距错位问题,但是会丢失拖动动画效果
            adapter.notifyItemMoved(form, to);
            isMove = true;
         }
      } catch (Exception e) {
    }
    return isMove;
}

// 轻拖滑动出recyclerview后调用(可做删除item)
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
    // null
  }
}

你可能感兴趣的:(Android RecyclerView拖动滑拽的实现)