Android recycleview 在多布局使用ItemTouchHelper
时间: 2023-10-14 10:04:19 浏览: 163
可以使用ItemTouchHelper来实现RecycleView多布局的拖拽和滑动删除功能。下面是一个简单的示例代码:
1. 创建ItemTouchHelper.Callback
```
public class MyItemTouchHelperCallback extends ItemTouchHelper.Callback {
private final ItemTouchHelperAdapter mAdapter;
public MyItemTouchHelperCallback(ItemTouchHelperAdapter adapter) {
mAdapter = adapter;
}
@Override
public boolean isLongPressDragEnabled() {
return true;
}
@Override
public boolean isItemViewSwipeEnabled() {
return true;
}
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
return makeMovementFlags(dragFlags, swipeFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
mAdapter.onItemDismiss(viewHolder.getAdapterPosition());
}
}
```
2. 创建ItemTouchHelperAdapter
```
public interface ItemTouchHelperAdapter {
void onItemMove(int fromPosition, int toPosition);
void onItemDismiss(int position);
}
```
3. 在Adapter中实现ItemTouchHelperAdapter接口
```
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemTouchHelperAdapter {
private List<MyData> mData;
...
@Override
public void onItemMove(int fromPosition, int toPosition) {
MyData item = mData.get(fromPosition);
mData.remove(fromPosition);
mData.add(toPosition, item);
notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
mData.remove(position);
notifyItemRemoved(position);
}
}
```
4. 在Activity或Fragment中添加ItemTouchHelper
```
ItemTouchHelper.Callback callback = new MyItemTouchHelperCallback(mAdapter);
ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
touchHelper.attachToRecyclerView(mRecyclerView);
```
注意:以上代码只是示例,具体实现需要根据自己的需求进行调整。
阅读全文