android stuidio RecyclerView 长按删除
时间: 2024-05-14 20:12:05 浏览: 79
Android中RecyclerView的长按删除
在RecyclerView中,要实现长按删除功能,需要以下步骤:
1. 在RecyclerView的适配器中,实现长按事件监听接口OnItemLongClickListener,代码如下:
```
public interface OnItemLongClickListener {
void onItemLongClick(View view, int position);
}
private OnItemLongClickListener mOnItemLongClickListener;
public void setOnItemLongClickListener(OnItemLongClickListener listener) {
this.mOnItemLongClickListener = listener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(itemView);
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
mOnItemLongClickListener.onItemLongClick(v, viewHolder.getAdapterPosition());
}
return true;
}
});
return viewHolder;
}
```
2. 在RecyclerView的Activity或Fragment中,实现OnItemLongClickListener接口,并在onCreate方法中设置适配器的长按监听器,代码如下:
```
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemLongClickListener(new MyAdapter.OnItemLongClickListener() {
@Override
public void onItemLongClick(View view, int position) {
// 在此处处理长按删除操作
mAdapter.removeItem(position);
}
});
```
3. 在适配器中添加删除数据的方法removeItem(int position),代码如下:
```
public void removeItem(int position) {
mDatas.remove(position);
notifyItemRemoved(position);
}
```
这样,当用户长按某个RecyclerView的item时,就会弹出删除确认框,用户确认后,该item就会被删除。
阅读全文