//添加控件拖动监听
mediaCardImg = findViewById(R.id.media_card);
mediaCardImg2 = findViewById(R.id.media_card2);
DragStartHelper helper = new DragStartHelper(mediaCardImg,this);
DragStartHelper helper2 = new DragStartHelper(mediaCardImg2, this);
helper.attach();
helper2.attach();
//添加要传递的数据,然后调用startDragAndDrop把数据传递的目标控件
@Override
public boolean onDragStart(@NonNull View v, @NonNull DragStartHelper helper) {
if (v.getId() == R.id.media_card) {
ClipData.Item item = new ClipData.Item("1");
ClipData data = new ClipData((CharSequence) v.getTag(), new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item);
//也可以添加多个数据
//ClipData.Item item2 = new ClipData.Item("2");
//ClipData.Item item3 = new ClipData.Item("3");
//data.addItem(item2);
//data.addItem(item3);
//设置拖动的阴影,可以自定义,这边直接使用ImageView
DragShadowBuilder myShadow = new DragShadowBuilder(v);
int flags = View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ;
//开始拖动
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
v.startDragAndDrop(data, myShadow, null, flags);
} else {
v.startDrag(data, myShadow, null, 0);
}
}
if (v.getId() == R.id.media_card2) {
ClipData.Item item = new ClipData.Item("2");
ClipData data = new ClipData((CharSequence) v.getTag(), new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item);
//设置拖动的阴影,可以自定义,这边直接使用ImageView
DragShadowBuilder myShadow = new DragShadowBuilder(v);
int flags = View.DRAG_FLAG_GLOBAL | View.DRAG_FLAG_GLOBAL_URI_READ;
//开始拖动
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
v.startDragAndDrop(data, myShadow, null, flags);
} else {
v.startDrag(data, myShadow, null, 0);
}
}
return false;
}
//目标控件添加监听,上面的控件拖动到该位置时会触发监听回调,然后可以获取传递过来的数据
frameLayout.setOnDragListener((v, event) -> {
final int action = event.getAction();
switch (action) {
//开始拖动
case DragEvent.ACTION_DRAG_STARTED:
//离开底部删除按钮
case DragEvent.ACTION_DRAG_EXITED:
//拖动到底部删除按钮中
case DragEvent.ACTION_DRAG_ENTERED:
return true;
case DragEvent.ACTION_DROP:
if (event.getClipData() == null) {
Log.i(TAG, "data is null");
} else {
String id = event.getClipData().getItemAt(0).getText().toString();
//用framlayout的添加和移除来实现布局的替换
frameLayout.removeAllViews();
frameLayout.addView(getView(id));
}
return true;
//拖放结束
case DragEvent.ACTION_DRAG_ENDED:
return true;
default:
break;
}
return false;
});