dragandrop将外部view拖拽进入recycleview示例代码
时间: 2023-09-12 18:08:04 浏览: 99
好的,以下是一个示例代码,演示如何将一个外部的View拖拽进入RecyclerView中:
```
// 创建一个View对象,设置LayoutParams,并将其添加到RecyclerView的父布局中
View view = new View(context);
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(
RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT
);
layoutParams.setMargins(50, 50, 50, 50);
layoutManager.addView(view, layoutParams);
// 在RecyclerView的Item上设置setOnLongClickListener()监听器
itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// 创建一个DragShadowBuilder对象和一个ClipData对象
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
ClipData data = ClipData.newPlainText("", "");
// 调用View.startDragAndDrop()方法来开始拖拽操作
v.startDragAndDrop(data, shadowBuilder, v, 0);
return true;
}
});
// 在onCreate()方法中重写onDragEvent()方法
@Override
public boolean onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取RecyclerView的父布局
ViewGroup parent = (ViewGroup) recyclerView.getParent();
// 重写onDragEvent()方法,将拖拽的View添加到RecyclerView中
parent.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DROP:
// 将拖拽的View添加到RecyclerView中
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(
RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT
);
int x = (int) event.getX();
int y = (int) event.getY();
View view = event.getLocalState();
layoutManager.addView(view, layoutParams);
// 拖拽结束,返回true
return true;
case DragEvent.ACTION_DRAG_ENDED:
// 从RecyclerView中移除拖拽的View
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
View view = event.getLocalState();
layoutManager.removeView(view);
// 拖拽结束,返回true
return true;
default:
break;
}
return false;
}
});
}
```
在这个示例代码中,我们创建了一个View对象,并将其添加到RecyclerView的父布局中。接着,我们在RecyclerView的Item上设置setOnLongClickListener()监听器,在其回调方法中创建一个DragShadowBuilder对象和一个ClipData对象,然后调用View.startDragAndDrop()方法来开始拖拽操作。
在重写的onDragEvent()方法中,我们判断传入的事件是否为拖拽事件。如果是,则根据事件的坐标和拖拽的View的LayoutParams来计算出View在RecyclerView中的位置,并将其添加到RecyclerView中。在拖拽结束时,我们需要将拖拽的View从RecyclerView中移除。
阅读全文