先在适配器里面写一个接口回调
//接口
public interface onLongClickLisenter
{
void onLongClickLisenter(int position);
}
//声明接口
private onLongClickLisenter onLongClickLisenter;
public void setOnLongClickLisenter(MyAdapter.onLongClickLisenter onLongClickLisenter) {
this.onLongClickLisenter = onLongClickLisenter;
}
-
然后在RecyclerView适配器 这个 onCreateViewHolder里面写长按删除
//长按删除 view.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int layoutPosition = myViewHolder.getLayoutPosition(); if (onLongClickLisenter!=null) { onLongClickLisenter.onLongClickLisenter(layoutPosition); } return true; } });
-
然后在RecyclerView适配器 这个方法的getItemCount()下面 定义一个方法
public void removeItem(int position) { //操作数据源 results.remove(position); //刷新 notifyDataSetChanged(); }
4.然后你在哪个Activity或者是fragment里面调用的适配器里面调用接口回传过来的长按删除
adapter.setOnLongClickLisenter(new MyAdapter.onLongClickLisenter() {
@Override
public void onLongClickLisenter(int position) {
Toast.makeText(getActivity(),"删除成功",Toast.LENGTH_SHORT).show();
//删除数据
adapter.removeItem(position);
}
});