RecyclerView拖放位置不起作用的android

时间:2016-07-01 10:27:43

标签: android drag-and-drop android-recyclerview adapter

我使用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中遇到与拖放位置相似的问题,请告诉我。

1 个答案:

答案 0 :(得分:0)

我在使用Android-advancedRecyclerView库时在GridView中实现Drag and Drop时遇到了同样的问题,我也在StackOverflow here上询问了它的问题,我也向库的作者提问,他们有实现了这个功能,请参阅我的问题。

虽然我发现了非常有用的博客here,但是没有必要使用任何外部库,您可以使用RecyclerView的内部功能,也许它对您有所帮助。