ItemTouchHelper用于RecyclerView项的滑动、拖动控制。首先创建RecyclerView和Adapter,这个写法与以前写法相同。
滑动删除/拖动交换位置
//第一个参数为可拖动方向,第而个参数为可滑动方向
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN,
ItemTouchHelper.LEFT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView
.ViewHolder target) {
int fromPosition = viewHolder.getAdapterPosition();//得到拖动ViewHolder的position
int toPosition = target.getAdapterPosition();//得到目标ViewHolder的position
if (fromPosition < toPosition) {
//分别把中间所有的item的位置重新交换
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(strings, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(strings, i, i - 1);
}
}
touchAdapter.notifyItemMoved(fromPosition, toPosition);
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
strings.remove(position);
touchAdapter.notifyItemRemoved(position);
}
}).attachToRecyclerView(rv);
方向分别有6种
ItemTouchHelper.DOWN
ItemTouchHelper.LEFT
ItemTouchHelper.RIGHT
ItemTouchHelper.START
ItemTouchHelper.END
默认情况下长按可拖动改变位置,如果想直接拖动某控件改变位置的话可以
先重写ItemTouchHelper的禁用长按拖动
public boolean isLongPressDragEnabled() {
return false;
}
然后添加以下代码
viewHolder.dragButton.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mItemTouchHelper.startDrag(viewHolder);
}
return false;
}
});
其他方法
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
switch (actionState) {
case ItemTouchHelper.ACTION_STATE_IDLE:
Log.e("ACTION_STATE_IDLE", "ACTION_STATE_IDLE");
//空闲状态
break;
case ItemTouchHelper.ACTION_STATE_SWIPE:
//滑动状态
Log.e("ACTION_STATE_SWIPE", "ACTION_STATE_SWIPE");
break;
case ItemTouchHelper.ACTION_STATE_DRAG:
Log.e("ACTION_STATE_DRAG", "ACTION_STATE_DRAG");
//拖动状态
break;
}
}
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
//拖动完成
}
@Override
public boolean isItemViewSwipeEnabled() {
//启用滑动
return super.isItemViewSwipeEnabled();
}
@Override
public void onMoved(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, int fromPos,
RecyclerView.ViewHolder target, int toPos, int x, int y) {
super.onMoved(recyclerView, viewHolder, fromPos, target, toPos, x, y);
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//和SimpleCallback构造函数参数意思相同
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.RIGHT;
return makeMovementFlags(dragFlags, swipeFlags);
}