【发布时间】:2026-02-12 20:10:02
【问题描述】:
我在屏幕上使用 Android Drag and Drop 到 drag 我的图像。当我drop 时,图像返回到其原始位置。但我希望图像保留在它被放入的位置。
我的尝试:我将图像的 X 和 Y 位置保存在 ACTION_DROP,然后尝试使用相同的 X 和 Y 坐标设置新的 view 位置。
有人可以帮忙吗?
如果我需要提供更多代码,请告诉我。
代码:
class MyDragListener implements View.OnDragListener {
@Override
public boolean onDrag(View v, DragEvent event) {
int action = event.getAction();
switch (event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
break;
case DragEvent.ACTION_DRAG_ENTERED:
if(v==findViewById(R.id.linear_layout_button))
findViewById(R.id.removeText).setVisibility(View.VISIBLE);
break;
case DragEvent.ACTION_DRAG_EXITED:
if(v==findViewById(R.id.linear_layout_button))
findViewById(R.id.removeText).setVisibility(View.GONE);
break;
case DragEvent.ACTION_DROP:
if(v==findViewById(R.id.linear_layout_image)) {
View view = (View) event.getLocalState();
float posx = view.getX();
float posy = view.getY();
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
LinearLayout container = (LinearLayout) v;
container.addView(view);
view.setX(posx);
view.setY(posy);
view.setVisibility(View.VISIBLE);
}
break;
case DragEvent.ACTION_DRAG_ENDED:
default:
break;
}
return true;
}
}
【问题讨论】:
-
尝试从事件变量中获取 x,y 值。
标签: android button drag-and-drop android-linearlayout