RecyclerView实现侧滑删除和长按拖拽-2

今天我们就来实现RecyclerView的侧滑删除和长按拖拽功能,实现这两个功能我们只需要一个类—— ItemTouchHelper
Google官方文档上是这么介绍的:
This is a utility class to add swipe to dismiss and drag & drop support to RecyclerView.意思就是:这是一个支持RecyclerView滑动删除和拖拽的实用工具类
接下来接着上一节“RecyclerView实现Listview-1”实现侧滑删除和长按拖拽

1、在ThirdTabFragment中定义

private ItemTouchHelper mItemTouchHeler;

2、在OnCreateView中的 recyclerView.setAdapter(adapter)下面接着写代码

ItemTouchHelper.Callback callback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
                int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position
                if (fromPosition < toPosition) {
                    //分别把中间所有的item的位置重新交换
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(data, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(data, i, i - 1);
                    }
                }


                adapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                data.remove(position);

                adapter.notifyItemRemoved(position);
            }
        };
        mItemTouchHeler = new ItemTouchHelper(callback);
        mItemTouchHeler.attachToRecyclerView(recyclerView);

但是这里面的数据data变为下面List,不在是String[]类型

 List<String>  data = new ArrayList<String>();
            for (int i = 0; i < 100; ++i) {
                data.add(new String("item") + i);
            }

3、MyAdapter中数据也改为如下:

 public List<String> mDataset;
    public MyAdapter(List<String> data) {
        this.mDataset=data;
    }

OnBindViewHolder中的代码
   holder.textView.setText(mDataset.get(i));

getItemCount()中的代码
  return mDataset.size();

你可能感兴趣的:(RecycleVie)