重写recyclerview中ontouchevent
时间: 2023-05-26 09:06:10 浏览: 107
我不知道具体情况,但是重写 RecyclerView 中的 onTouchEvent 通常是为了实现一些特殊的触摸行为,比如滑动删除、拖拽排序等。以下是可能的一些代码实现:
1. 滑动删除
```
@Override
public boolean onTouchEvent(MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
mIsSwiping = false;
mDownX = e.getX();
mDownY = e.getY();
return super.onTouchEvent(e);
case MotionEvent.ACTION_MOVE:
float dx = e.getX() - mDownX;
float dy = e.getY() - mDownY;
if (Math.abs(dx) > mTouchSlop && Math.abs(dy) < mTouchSlop) {
mIsSwiping = true;
int position = getChildAdapterPosition(findChildViewUnder(e.getX(), e.getY()));
if (position != RecyclerView.NO_POSITION) {
mSwipePosition = position;
}
}
return super.onTouchEvent(e);
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mIsSwiping) {
if (dx > 0) {
// swiped right, perform delete action
mAdapter.deleteItem(mSwipePosition);
} else {
// swiped left, reset item view
mAdapter.notifyItemChanged(mSwipePosition);
}
mIsSwiping = false;
mSwipePosition = RecyclerView.NO_POSITION;
return true;
}
return super.onTouchEvent(e);
}
return super.onTouchEvent(e);
}
```
2. 拖拽排序
```
@Override
public boolean onTouchEvent(MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
mDragPosition = getChildAdapterPosition(findChildViewUnder(e.getX(), e.getY()));
if (mDragPosition != RecyclerView.NO_POSITION) {
mDraggedViewHolder = getChildViewHolder(findChildViewUnder(e.getX(), e.getY()));
mDragStartX = mDraggedViewHolder.itemView.getX();
mDragStartY = mDraggedViewHolder.itemView.getY();
mDragStartTouchX = e.getX();
mDragStartTouchY = e.getY();
if (mItemTouchHelper != null) {
mItemTouchHelper.startDrag(mDraggedViewHolder);
}
}
return super.onTouchEvent(e);
case MotionEvent.ACTION_MOVE:
return mDraggedViewHolder != null && mItemTouchHelper != null && mItemTouchHelper.onTouchEvent(e);
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mDraggedViewHolder != null) {
mDraggedViewHolder.itemView.animate().x(mDragStartX).y(mDragStartY).setDuration(150).start();
mDraggedViewHolder = null;
mDragPosition = RecyclerView.NO_POSITION;
return true;
}
return super.onTouchEvent(e);
}
return super.onTouchEvent(e);
}
```
阅读全文