RecyclerView长按拖拽,侧滑删除

1,导包

implementation ‘com.android.support:recyclerview-v7:27.1.1’

2,Xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_linear_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="20dp"/>
</android.support.constraint.ConstraintLayout>
3,Activity
public class RvItemTouchActivity extends AppCompatActivity {
    private android.support.v7.widget.RecyclerView rvlinearlist;
    private ArrayList<String> mData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linear);
        this.rvlinearlist = (RecyclerView) findViewById(R.id.rv_linear_list);
        initData();
        initAdapter();

    }

    private void initAdapter() {
        //线性布局拖拽
        rvlinearlist.setLayoutManager(new LinearLayoutManager(this));

        //自定义类实现拖拽,侧滑删除
        RvItemTouchAdapter adapter = new RvItemTouchAdapter(this, mData);

        new ItemTouchHelper(new MyItemTouchHandler(adapter)).attachToRecyclerView(rvlinearlist);

        rvlinearlist.setAdapter(adapter);

       /* //库实现
        RvItemTouchAdapter2 adapter2 = new RvItemTouchAdapter2(R.layout.item_rv_linear2, mData);
        rvlinearlist.setAdapter(adapter2);

        ItemDragAndSwipeCallback itemDragAndSwipeCallback = new ItemDragAndSwipeCallback(adapter2);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragAndSwipeCallback);
        itemTouchHelper.attachToRecyclerView(rvlinearlist);

// 开启拖拽
        adapter2.enableDragItem(itemTouchHelper);
        adapter2.setOnItemDragListener(onItemDragListener);

// 开启滑动删除
        adapter2.enableSwipeItem();
        adapter2.setOnItemSwipeListener(onItemSwipeListener);
*/


    }
    OnItemDragListener onItemDragListener = new OnItemDragListener() {
        @Override
        public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos){}
        @Override
        public void onItemDragMoving(RecyclerView.ViewHolder source, int from, RecyclerView.ViewHolder target, int to) {

            //移动位置互换
            Collections.swap(mData,from,to);

        }
        @Override
        public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {}
    };

    OnItemSwipeListener onItemSwipeListener = new OnItemSwipeListener() {
        @Override
        public void onItemSwipeStart(RecyclerView.ViewHolder viewHolder, int pos) {
            Log.e("MMM", "onItemSwipeStart: "+pos );
        }
        @Override
        public void clearView(RecyclerView.ViewHolder viewHolder, int pos) {
            Log.e("MMM", "clearView: "+pos);
        }
        @Override
        public void onItemSwiped(RecyclerView.ViewHolder viewHolder, int pos) {
            Log.e("MMM", "onItemSwiped: "+pos);
        }

        @Override
        public void onItemSwipeMoving(Canvas canvas, RecyclerView.ViewHolder viewHolder, float dX, float dY, boolean isCurrentlyActive) {
            //正在滑动监听

        }
    };



    private void initData() {
        mData = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            mData.add("频道"+i);
        }
    }
}
4,Adapter
public class RvItemTouchAdapter extends MyItemTouchHandler.ItemTouchAdapterImpl {

    private final LayoutInflater mLayoutInflater;
    private Context mContext;
    private List<String>mData;

    public RvItemTouchAdapter(Context context, List<String> data) {
        mContext = context;
        mData = data;
        mLayoutInflater = LayoutInflater.from(context);
    }

    @Override
    public void onItemMove(int fromPosition, int toPosition) {
        //移动时交换位置
        Collections.swap(mData,fromPosition,toPosition);
    }

    @Override
    public void onItemRemove(int position) {
        //移除监听
        mData.remove(position);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.item_rv_linear2, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        if (holder instanceof ViewHolder) {
            ((ViewHolder) holder).tvTv.setText(mData.get(position));
        }

    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTv;
        public ViewHolder(View itemView) {
            super(itemView);
            tvTv=itemView.findViewById(R.id.tv_item_rv_linear_text);
        }
    }
}
5,MyItemTouchHandler
public class MyItemTouchHandler extends ItemTouchHelper.Callback {
      ItemTouchAdapterImpl adapter;    

      public MyItemTouchHandler(@NonNull ItemTouchAdapterImpl adapter) {
          this.adapter = adapter;    
      }    

      /**     
       * 设置 允许拖拽和滑动删除的方向     
       */    
       @Override    
       public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
          // 指定可 拖拽方向 和 滑动消失的方向        
          int dragFlags,swipeFlags;        
          RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();        
          if (manager instanceof GridLayoutManager || manager instanceof StaggeredGridLayoutManager) {
               // 上下左右都可以拖动            
               dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;       
           } else {            
              // 可以上下拖动            
              dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;        
           }        
           // 可以左右方向滑动消失        
           swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;        
           // 如果某个值传 0 , 表示不支持该功能        
           return makeMovementFlags(dragFlags, swipeFlags);    
        }    

        /**     
         * 拖拽后回调,一般通过接口暴露给adapter, 让adapter去处理数据的交换     
         */    
         @Override    
         public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {        
             // 相同 viewType 之间才能拖动交换        
             if (viewHolder.getItemViewType() == target.getItemViewType()) {            
                 int fromPosition = viewHolder.getAdapterPosition();
                 int toPosition = target.getAdapterPosition();
                 if (fromPosition < toPosition) {    
                    //途中所有的item位置都要移动    
                    for (int i = fromPosition; i < toPosition; i++) {        
                        adapter.onItemMove(i, i + 1);    
                    }
                  } else {    
                    for (int i = fromPosition; i > toPosition; i--) {        
                        adapter.onItemMove(i, i - 1);    
                    }
                  }
                  adapter.notifyItemMoved(fromPosition, toPosition);
                  return true;    
             }        
             return false;    
          }    

          /**     
           * 滑动删除后回调,一般通过接口暴露给adapter, 让adapter去删除该条数据     
           */    
           @Override    
           public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {        
              // 删除数据        
              adapter.onItemRemove(viewHolder.getAdapterPosition());        
              // adapter 刷新        
              adapter.notifyItemRemoved(viewHolder.getAdapterPosition());    
           }    

           @Override    
           public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
               super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);       
               if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {            
                    //滑动时改变Item的透明度           
                    final float alpha = 1 - Math.abs(dX) / (float)viewHolder.itemView.getWidth();            
                    viewHolder.itemView.setAlpha(alpha);            
                    viewHolder.itemView.setTranslationX(dX);       
               }    
           }   

           /**     
            * item被选中(长按)     
            * 这里改变了 item的背景色, 也可以通过接口暴露, 让adapter去处理逻辑     
            */    
            @Override    
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {        
                if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {            
                   // 拖拽状态            
                   viewHolder.itemView.setBackgroundColor(Color.BLUE);
                }else if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {            
                   // 滑动删除状态            
                   viewHolder.itemView.setBackgroundColor(Color.RED);       
                }       
                super.onSelectedChanged(viewHolder, actionState);    
            }   

            /**     
             * item取消选中(取消长按)     
             * 这里改变了 item的背景色, 也可以通过接口暴露, 让adapter去处理逻辑     
             */    
             @Override    
             public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {        
                viewHolder.itemView.setBackgroundColor(Color.TRANSPARENT);        
                super.clearView(recyclerView, viewHolder);    
             }    

             /**     
              * 是否支持长按开始拖拽,默认开启     * 可以不开启,然后在长按 item 的时候,手动 调用 mItemTouchHelper.startDrag(myHolder) 开启,更加灵活     
              */    
              @Override    
              public boolean isLongPressDragEnabled() {        
                 return adapter.autoOpenDrag();    
              }    

              /**     
               * 是否支持滑动删除,默认开启     * 可以不开启,然后在长按 item 的时候,手动 调用 mItemTouchHelper.startSwipe(myHolder) 开启,更加灵活     
               */    
               @Override    
               public boolean isItemViewSwipeEnabled() {        
                    return adapter.autoOpenSwipe();    
               }    

               // 建议让 adapter 实现该接口    
               public static abstract class ItemTouchAdapterImpl extends RecyclerView.Adapter{        
                    public abstract void onItemMove(int fromPosition, int toPosition);       
                    public abstract void onItemRemove(int position);       
                    // 是否自动开启拖拽        
                    protected boolean autoOpenDrag(){            
                         return true;       
                    }        
                    // 是否自动开启滑动删除        
                    protected boolean autoOpenSwipe(){            
                         return true;        
                    }    
               }
    }

6,效果图

Untitled.gif

7,网格布局实现
  • 效果图
    网格拖拽.gif
  • 改动部分,仅在Activity中改动部分代码,如下
 GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        //线性布局拖拽
        //rvlinearlist.setLayoutManager(new LinearLayoutManager(this));
        rvlinearlist.setLayoutManager(gridLayoutManager);

        //自定义类实现拖拽,侧滑删除
        RvItemTouchAdapter adapter = new RvItemTouchAdapter(this, mData);

        MyItemTouchHandler myItemTouchHandler = new MyItemTouchHandler(adapter);

        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new MyItemTouchHandler(adapter));
        itemTouchHelper.attachToRecyclerView(rvlinearlist);

        rvlinearlist.setAdapter(adapter);

源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值