要實現滑動刪除功能,您需要使用ItemTouchHelper
類。以下是實現滑動刪除的步驟:
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.2.1'
}
RecyclerView.Adapter
,并實現必要的方法。在這個類中,您需要定義一個接口來處理滑動事件:public interface OnItemSwipeListener {
void onItemSwiped(int position);
}
OnItemSwipeListener
成員變量,并在構造函數中接收一個實例。然后,在onBindViewHolder
方法中設置滑動監聽器:private OnItemSwipeListener mListener;
public MyAdapter(OnItemSwipeListener listener) {
mListener = listener;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.itemView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mStartX = event.getX();
mStartY = event.getY();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
float endX = event.getX();
float endY = event.getY();
float deltaX = endX - mStartX;
float deltaY = endY - mStartY;
if (Math.abs(deltaX) > Math.abs(deltaY)) {
if (deltaX > 0) {
if (mListener != null) {
mListener.onItemSwiped(position);
}
} else {
// Handle left swipe
}
} else {
if (deltaY > 0) {
// Handle down swipe
} else {
// Handle up swipe
}
}
}
return false;
}
});
}
ItemTouchHelper.Callback
子類,并重寫onInterceptTouchEvent
和onMove
方法:private class MyItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final MyAdapter mAdapter;
public MyItemTouchHelperCallback(MyAdapter adapter) {
mAdapter = adapter;
}
@Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent e) {
return false;
}
@Override
public void onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
if (viewHolder instanceof MyViewHolder) {
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
mAdapter.notifyItemRangeChanged(viewHolder.getAdapterPosition(), mAdapter.getItemCount());
}
}
}
ItemTouchHelper
并附加到RecyclerView:MyAdapter mAdapter = new MyAdapter(/* pass your data here */);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new MyItemTouchHelperCallback(mAdapter));
itemTouchHelper.attachToRecyclerView(recyclerView);
現在,當用戶滑動列表項時,將觸發onSwiped
方法,從而刪除相應的列表項。您可以根據需要自定義刪除動畫和其他細節。