4

我正在开发一个拖放游戏,但我有一个小问题,当我在视图中单击时,阴影生成器首先出现在右上角,然后随着触摸位置移动。

阴影生成器也比初始视图小。我怎样才能使它成为初始视图?

private final class MyTouchListener implements OnTouchListener {
    public boolean onTouch(View view, MotionEvent motionEvent) {

        if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
            ClipData data = ClipData.newPlainText("", "");
            DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
            view.startDrag(data, shadowBuilder, view, 0);
            view.setVisibility(View.INVISIBLE);
            return true;
        } else {
            return false;
        }
    }
}
4

1 回答 1

7

我可能迟到了,但是……您必须计算触摸点和可拖动左上角之间的偏移量,并将其与自定义 DragShadowBuilder 一起使用。

这是偏移量的代码:

@Override
public boolean onTouch(View view, MotionEvent event) {

    switch(event.getAction()) {

        case MotionEvent.ACTION_DOWN : {

            Point offset = new Point((int) event.getX(), (int) event.getY());

            ClipData data = ClipData.newPlainText("", "");
            DragShadowBuilder shadowBuilder = new CustomDragShadowBuilder(container, offset);
            view.startDrag(data, shadowBuilder, container, 0);
            view.setVisibility(View.INVISIBLE);
        }
    }

    return true;
}

这是自定义构建器的代码:

import android.graphics.Point;
import android.view.View;

public class CustomDragShadowBuilder extends View.DragShadowBuilder {

// ------------------------------------------------------------------------------------------
// Private attributes :
private Point _offset;
// ------------------------------------------------------------------------------------------



// ------------------------------------------------------------------------------------------
// Constructor :
public CustomDragShadowBuilder(View view, Point offset) {

    // Stores the View parameter passed to myDragShadowBuilder.
    super(view);

    // Save the offset :
    _offset = offset;
}
// ------------------------------------------------------------------------------------------



// ------------------------------------------------------------------------------------------
// Defines a callback that sends the drag shadow dimensions and touch point back to the system.
@Override
public void onProvideShadowMetrics (Point size, Point touch) {

    // Set the shadow size :
    size.set(getView().getWidth(), getView().getHeight());

    // Sets the touch point's position to be in the middle of the drag shadow
    touch.set(_offset.x, _offset.y);
}
// ------------------------------------------------------------------------------------------
}
于 2013-03-05T16:50:04.430 回答