希望它对你有用
SwipeAndDragHelper swipeAndDragHelper = new SwipeAndDragHelper(adapter);
ItemTouchHelper touchHelper = new ItemTouchHelper(swipeAndDragHelper);
adapter.setTouchHelper(touchHelper);
recyclerview.setAdapter(adapter);
touchHelper.attachToRecyclerView(recyclerview);
//SwipeAndDragHelper 类
public class SwipeAndDragHelper extends ItemTouchHelper.Callback {
private ActionCompletionContract contract;
public SwipeAndDragHelper(ActionCompletionContract contract) {
this.contract = contract;
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
contract.onViewMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
// contract.onViewSwiped(viewHolder.getAdapterPosition());
}
@Override
public boolean isLongPressDragEnabled() {
return false;
}
@Override
public void onChildDraw(Canvas c,
RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder,
float dX,
float dY,
int actionState,
boolean isCurrentlyActive) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
float alpha = 1 - (Math.abs(dX) / recyclerView.getWidth());
viewHolder.itemView.setAlpha(alpha);
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
public interface ActionCompletionContract {
void onViewMoved(int oldPosition, int newPosition);
void onViewSwiped(int position);
}
}
// 调用触摸方法
holder.imageview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
touchHelper.startDrag(holder);
}
return false;
}
});
public void setTouchHelper(ItemTouchHelper touchHelper) {
this.touchHelper=touchHelper;
}
//实现方法
public class CustomDetail extends RecyclerView.Adapter<CustomDetail.ViewHolder> implements
SwipeAndDragHelper.ActionCompletionContract {
@Override
public void onViewMoved(int oldPosition, int newPosition) {
FavouriteListResponse.Data listdat=listview.get(oldPosition);
listview.remove(oldPosition);
listview.add(newPosition, listdat);
notifyItemMoved(oldPosition, newPosition);
}
@Override
public void onViewSwiped(int position) {
listview.remove(position);
notifyItemRemoved(position);
}