实现item上下滑动改变位置,左右滑动进行删除

2019-07-16  本文已影响0人  龙_君

TouchCallBack 接口:

public interface TouchCallBack {
//数据交换
void onItemMove(int fromPosition ,int toPosition);

//数据删除
void onItemDelete(int position);
}

在adapter中重写以下两个方法:
(注:adapter 需要实现 ouchCallBack)

public void onItemMove(int fromPosition,int toPosition){
    //通过集合工具类交换位置
    Collections.swap(list,fromPosition,toPosition);
    //局部刷新
    notifyItemMoved(fromPosition,toPosition);
}

@Override
public void onItemDelete(int position) {
      //数据库进行删除
    DbDailyBean dbDailyBean = list.get(position);
    boolean delete = DataUtilDao.getDataUtilDao().delete(dbDailyBean);

    //数据库进行判断是否删除成功
    if (delete){
        //删除数据
        list.remove(position);
        //局部刷新(移除)
        notifyItemRemoved(position);
        notifyItemRangeChanged(position,list.size() - 1);

        ToastUtil.showLong("删除成功");
    }else{
        ToastUtil.showLong("删除失败");
    }
}

在MyActivity中的initView方法中写:

//自定义处理类,
    // callback回调:上下拖动和左右移动的事件触发
    //callback回调中,调用适配器类的具体实现处理交换功能
    SimpleItemTouchHelperCallBack helper = new SimpleItemTouchHelperCallBack(adapter);
    //ItemTouchHelper系统辅助类,赋值需要一个ItemTouchHelper.callback对象,自定义处理类
    ItemTouchHelper touchHelper = new ItemTouchHelper(helper);
    //关联一个RecyclerView
    touchHelper.attachToRecyclerView(mCollectRlv);

自定义处理类实现上下左右滑动:

 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 ;
    //允许右移动
     int right = ItemTouchHelper.RIGHT;   

    return makeMovementFlags(drag,swip);(将swipe替换成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 i) {
    touchCallBack.onItemDelete(viewHolder.getAdapterPosition());
}

希望可以帮到大家@_@ !

上一篇下一篇

猜你喜欢

热点阅读