Shadow builder in android

android, java

Solution

I may be late, but… You have to compute the offset between the touched point and your draggable top left corner, and use it with a custom DragShadowBuilder.

Here is the code for the offset :

@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;
}

And here is the code for the custom builder :

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);
}
// ------------------------------------------------------------------------------------------
}

Problem

I am working on a dragdrop game, but I have small problem, that when I click in a view the shadow builder appears first at the right-top-corner and then it moves with the touch place. Also the shadow builder is smaller than the initial view. How can I make it as the initial view? ``` 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; } } } ```

Original source