Search code examples
androiddrag-and-dropontouchlisteneronlongclicklistenermotionevent

Android: Different Drag and Drop Actions onLongClick and onTouch


I want to implement two different Drag and Drop interactions with one Button. If the user clicks long on the Button, he can move the button. This is no Problem, I implemented OnLongClickListener:

@Override
public boolean onLongClick(View v) {
    ClipData dragData = ClipData.newPlainText(
            AbstractFragment.BUTTON_ID_TAG, "" + v.getId());
    DragShadowBuilder shadow = new DragShadowBuilder(v);
    v.startDrag(dragData, shadow, null, 0);
    return true;
}

If the user touches the Button and drags immediately he can draw a line from this button to another. I think I have to implement the OnTouchListener interface, but I'm not sure about the condition to recognize this userinteraction. Which MotionEvent or rather which combination of MotionEvents do I need to recognize this input.

I hope you can give me some hints!

grtz warci


Solution

  • Here is my solution:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            Toast.makeText(getActivity(), "onClick", Toast.LENGTH_LONG).show();
            ClipData dragData = ClipData.newPlainText(
                    AbstractFragment.BUTTON_ID_TAG, "" + v.getId());
            DragShadowBuilder shadow = new CanvasDragShadow(v);
            v.startDrag(dragData, shadow, null, 0);
            return true;
        }
        return false;
    }
    

    I added this Method, and it works. Maybe it's necessary to check the History of MotionEvents to have a better user-experience.