Schnodahipfe
Schnodahipfe

Reputation: 1053

Android - perform drag and drop programmatically

I would like to programmatically drag one view and release it on top of another for initialization purposes, is this possible?

EDIT: I'm looking for a way to simulate a drag&drop

Upvotes: 4

Views: 3312

Answers (1)

zapl
zapl

Reputation: 63955

You can remove Views from Layouts and add them to other Layouts (if that's what you are looking for)

ViewGroup oldGroup = (ViewGroup) findViewById(R.id.some_layout);
ViewGroup newGroup = (ViewGroup) findViewById(R.id.some_other_layout);

Button button = (Button) oldGroup.findViewById(R.id.a_button);

oldGroup.removeView(button);
newGroup.addView(button);

There is no drag&drop animation and it might give strange results but it's possible.

A ViewGroup would be a LinearLayout, RelativeLayout and those.


For simulating Drag&Drop events you could call the onDragListener manually but there is one problem:

public boolean onDrag(View v, DragEvent event);

expects a DragEvent which has no public constructor so you can only call it with null

There might be a way to create one via a faked Parcel but that going to be ugly.

private void initializationTest() {
    DragEvent event = null;
    /* maybe sth like that
    Parcel source = Parcel.obtain();
    source.writeInt(1234);
    event  = DragEvent.CREATOR.createFromParcel(source);
    */
    onDrag(theTargetView, event);
}

Another possibility is maybe to create touchevents but Idk if that would work. At least the monkey could probably do that.

Upvotes: 3

Related Questions