我想将ImageView
拖到RelativeLayout
内的任何位置。当我尝试拖动它ImageView
时它可以工作,但是当我从屏幕上松开手指时它会消失。我无法找到错误的位置。
这是我的代码结构:
OnLongClickListener 适用于ImageView
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item);
View.DragShadowBuilder myShadow = new View.DragShadowBuilder(imageView);
v.startDrag(dragData,myShadow,null,0);
v.setVisibility(View.GONE);
return true;
}
});
DragListener 方法
imageView.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
layoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams(); //layoutParams is defined on Top.
Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
break;
case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
Log.d(msg,"Drag Location Entered "+x_cord+" Ycord "+y_cord);
break;
case DragEvent.ACTION_DRAG_EXITED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
Log.d(msg, "Drag Exited xcord " + x_cord + " Ycord " + y_cord);
layoutParams.leftMargin = x_cord;
layoutParams.topMargin = y_cord;
v.setLayoutParams(layoutParams);
Log.d(msg, "layoutparams set success.");
v.setVisibility(View.VISIBLE);
Log.d(msg,"Made View Visible");
break;
case DragEvent.ACTION_DRAG_LOCATION:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
Log.d(msg,"Drag Location xcord "+x_cord+" Ycord "+y_cord);
break;
case DragEvent.ACTION_DRAG_ENDED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
break;
case DragEvent.ACTION_DROP:
Log.d(msg, "ACTION_DROP event");
break;
default:
break;
}
return true;
}
});
OnTouchListener 方法
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(imageView);
imageView.startDrag(data, shadowBuilder, imageView, 0);
return true;
}
else
{
return false;
}
}
});
答案 0 :(得分:0)
我怀疑你弄错了。在底线,您没有看到ImageView
,因为您致电:
v.setVisibility(View.GONE);
在OnCLickListener
内,你永远不会改回来。
问题是您要将DragListener
分配给您希望收到有关View
的通知的布局中的任何DragEvents
,但无论如何拖动都会发生,即使您赢了&# 39;只需通过调用View
系统开始使用startDrag()
进行拖动,将任何听众分配给任何ShadowBuilder
。
总而言之,如果您拖动一个View
,那么通常会将DragListener
分配给布局中的其他Views
,将其悬停在其上方。你似乎认为通过调用:
v.setLayoutParams(layoutParams);
这导致View
跟随你的手指而实际上是通话的原因:
v.startDrag()
对此负责。
无论如何,如果你打电话:
case DragEvent.ACTION_DRAG_ENDED:
case DragEvent.ACTION_DRAG_ENDED:
v.setVisibility(View.VISIBLE);
break;
您应该看到ImageView
返回。