我使用RecyclerView
创建了一个列表,该列表具有拖放功能。列表如下所示
列表
列出项目1
清单第2项
清单第3项
如果用户想要将列表项3拖动到列表项1的位置,则当项3接近列表项2时,列表会更新。因此列表将更新如下
列表
列出项目1
清单第3项
清单第2项
上述场景的适配器类:
public class VehicleAdapter extends RecyclerView.Adapter<ViewHolder> implements ItemTouchHelperAdapter {
private VehicleInfoBean mVehicleInfoBean;
private Context ctx;
private HashMap<Integer, Boolean> expandedMap;
private int indexOfSwipe;
private LayoutInflater inflater;
private final int row1 = 0, rowrest = 1;
private RecyclerView recyclerView;
private ItemTouchHelper mItemTouchHelper;
public VehicleAdapter(VehicleInfoBean vehicleInfoObj, Context ctx, RecyclerView recyclerView) {
this.bean = vehicleInfoObj;
this.ctx = ctx;
inflater = LayoutInflater.from(ctx);
ItemTouchHelper.Callback callback = new SimpleItemTouchHelperCallback(this);
mItemTouchHelper = new ItemTouchHelper(callback);
this.recyclerView = recyclerView;
mItemTouchHelper.attachToRecyclerView(recyclerView);
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
ViewHolder viewHolder;
v = inflater.inflate(R.layout.card_odometer, parent, false);
viewHolder = new OdometerViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
FCALog.d("adapter -- onBindViewHolder ---- " + position);
VehicleInfoViewHolder vehicleInfoViewHolder = (VehicleInfoViewHolder) holder;
vehicleInfoViewHolder.getIvDragItem().setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mItemTouchHelper.startDrag(holder);
}
return false;
}
});
}
@Override
public int getItemCount() {
return bean.getInfoBeanHashMap().size();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public void onItemMove(int fromPosition, int toPosition) {
Collections.swap(bean.getSequence(), fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onItemDismiss(int position) {
}
}
如果在RecyclerView
中遇到与拖放位置相似的问题,请告诉我。