美文网首页
RecyClerView实现拖拽与侧滑删除

RecyClerView实现拖拽与侧滑删除

作者: 玖玖君 | 来源:发表于2019-07-16 19:46 被阅读0次

    TouchCallBack

    public interface TouchCallBack {
        //数据交换
        void onItemMove(int fromPosition, int toPosition);
    
        //数据删除
        void onItemDelete(int position);
    }
    
    
    

    SimpleItemTouchHelperCallBack

    public class SimpleItemTouchHelperCallBack extends ItemTouchHelper.Callback {
    
        private TouchCallBack touchCallBack;
    
        public SimpleItemTouchHelperCallBack(TouchCallBack touchCallBack) {
            this.touchCallBack = touchCallBack;
        }
    
        @Override
        public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
            //允许上下移动
            int drag = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
    
            //允许左右滑动
            int swip = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
            return makeMovementFlags(drag, right);
        }
    
        @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
            touchCallBack.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
            return true;
        }
    
        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            touchCallBack.onItemDelete(viewHolder.getAdapterPosition());
        }
    }
    

    GoldChooseTabAdapter(适配器里面添加)

        @Override
        public void onItemMove(int fromPosition, int toPosition) {
            //通过集合工具类交换位置
            Collections.swap(list,fromPosition,toPosition);
            //局部刷新
            notifyItemMoved(fromPosition, toPosition);
        }
    
        @Override
        public void onItemDelete(int position) {
            list.remove(position);
            notifyItemRangeChanged(position, list.size() - position);
            notifyItemRemoved(position);
        }
    

    Activity里写

       //自定义处理类
       //callback回调,上下拖动和左右移动的时间触发
            SimpleItemTouchHelperCallBack helper = new SimpleItemTouchHelperCallBack(adapter);
       //itemTouchHelper系统辅助类,赋值需要一个ItemTouchHelper.callback对象,自定义处理类
            ItemTouchHelper touchHelper = new ItemTouchHelper(helper);
            //关联一个Recyclerview
            touchHelper.attachToRecyclerView(recy);
    
    

    更炫酷的侧滑以及刷新效果:https://qibilly.com/SmartSwipe-tutorial/

    相关文章

      网友评论

          本文标题:RecyClerView实现拖拽与侧滑删除

          本文链接:https://www.haomeiwen.com/subject/cuhxlctx.html