将视图拖放到RecyclerView项目Android

时间:2017-02-06 11:06:16

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

我正在开发一个Android应用程序,其屏幕包含以下内容:

  1. 包含类别的Recycler视图,如下图所示
  2. 按钮上的单独视图,用户应该能够将它拖到RecyclerView项目上,然后在用户放下后,用户将显示在RecyclerView项目数据处的更改(例如,类别中的项目计数)
  3. 我需要一些关于如何实现此过程的帮助 要将View拖入Recycler项目,下图将准确说明我想要做什么,但不知道如何做到这一点

    enter image description here

    非常感谢任何帮助

1 个答案:

答案 0 :(得分:9)

首先在您的回收器适配器的onCreateViewHolder中的膨胀视图中添加一个draglistener。

view.setOnDragListener(new OnDragListener() {
    @Override
    public boolean onDrag(View view, DragEvent dragEvent) {

        switch (dragEvent.getAction()) {
            case DragEvent.ACTION_DRAG_STARTED:
                // drag has started, return true to tell that you're listening to the drag
                return true;

            case DragEvent.ACTION_DROP:
                // the dragged item was dropped into this view
                Category a = items.get(getAdapterPosition());
                a.setText("dropped");
                notifyItemChanged(getAdapterPosition());
                return true;
            case DragEvent.ACTION_DRAG_ENDED:
                // the drag has ended
                return false;
        }
        return false;
    }
});

ACTION_DROP情况下,您可以更改模型并调用notifyItemChanged(),也可以直接修改视图(不会处理重新绑定的情况)。同样在onCreateViewHolder中为longClickListener添加View,并在onLongClick开始拖动:

ClipData.Item item = new ClipData.Item((CharSequence) view.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData dragData = new ClipData(view.getTag().toString(),
            mimeTypes, item);
view.setVisibility(View.GONE);
DragShadowBuilder myShadow = new DragShadowBuilder(view);

if (VERSION.SDK_INT >= VERSION_CODES.N) {
    view.startDragAndDrop(dragData, myShadow, null, 0);
} else {
    view.startDrag(dragData, myShadow, null, 0);
}

有关拖放的详细信息,请查看android developers site

相关问题