RecyclerView ItemTouchHelper实现拖拽、侧滑功能
作者:互联网
ItemTouchHelper
ItemTouchHelper:是一个工具类,可实现滑动删除和拖拽移动,使用这个工具类需要配合RecyclerView和ItemTouchHelper.Callback使用。
使用方法
1.新建类继承自ItemTouchHelper.Callback
实现这个类需要重写三个方法:
class MyCallback extends ItemTouchHelper.Callback {
//该方法用于返回可以滑动的方向,比如说允许从右到左侧滑,允许上下拖动等。
@Override
public int getMovementFlags(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//允许上下的拖动
int swipeFlags = ItemTouchHelper.LEFT;//只允许从右向左侧滑
return makeMovementFlags(dragFlags,swipeFlags);
}
//当用户拖动一个Item进行上下移动从旧的位置到新的位置的时候会调用该方法
@Override
public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getBindingAdapterPosition();
int targetPosition = target.getBindingAdapterPosition();
if (fromPosition < targetPosition) {
for (int i = fromPosition; i < targetPosition; i++) {
Collections.swap(functionList, i, i + 1);
}
} else {
for (int i = fromPosition; i > targetPosition; i--) {
Collections.swap(functionList, i, i - 1);
}
}
functionAdapter.notifyItemMoved(fromPosition, targetPosition);
return true;
}
//当用户左右滑动Item达到删除条件时,会调用该方法,一般手指触摸滑动的距离达到RecyclerView宽度的 一半时,再松开手指,此时该Item会继续向原先滑动方向滑过去并且调用onSwiped方法进行删除,否则会反向滑回原来的位置。
@Override
public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getBindingAdapterPosition();
functionList.remove(position);
functionAdapter.notifyItemRemoved(position);
}
}
2.或者直接使用ItemTouchHelper.SimpleCallback
//其中第一个参数设置拖拽的方向,第二参数设置滑动的方向,0为不可拖拽或滑动
//重写onMove和onSwiped方法,同上面的自定义类
private ItemTouchHelper.Callback itemTouchCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
@Override
public boolean onMove(@NonNull @NotNull RecyclerView recyclerView,
@NonNull @NotNull RecyclerView.ViewHolder viewHolder,
@NonNull @NotNull RecyclerView.ViewHolder target) {
int fromPosition = viewHolder.getBindingAdapterPosition();
int targetPosition = target.getBindingAdapterPosition();
if (fromPosition < targetPosition) {
for (int i = fromPosition; i < targetPosition; i++) {
Collections.swap(functionList, i, i + 1);
}
} else {
for (int i = fromPosition; i > targetPosition; i--) {
Collections.swap(functionList, i, i - 1);
}
}
functionAdapter.notifyItemMoved(fromPosition, targetPosition);
return true;
}
@Override
public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) {
}
};
3.绑定RecyclerView
RecyclerView rvFunctionList;
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemTouchCallback);
itemTouchHelper.attachToRecyclerView(rvFunctionList);
标签:侧滑,int,targetPosition,NotNull,ItemTouchHelper,RecyclerView,fromPosition 来源: https://blog.csdn.net/gxlgxjhll/article/details/112494569