【问题标题】:drag and drop - image returns to original location拖放 - 图像返回到原始位置
【发布时间】:2026-02-12 20:10:02
【问题描述】:

我在屏幕上使用 Android Drag and Dropdrag 我的图像。当我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


【解决方案1】:

发生这种情况是因为您再次使用 x y 位置。尝试通过评论这两行来尝试

   // view.setX(posx);
// view.setY(posy);

【讨论】:

  • SO 提供评论选项,使用它
  • 什么是 SO?请解释