1

enter image description here

As illustrated above, I have 3 LinearLayouts, each has an ImageView and a TextView inside them. Each Image view has an OnLongClickListener attached to them. The AbsoluteLayout which encapsulates all the objects has an OnDragListener attached to it.

Inside the onDrag method I need to get the LinearLayout that is the parent of the ImageView that I am dragging so that I can reposition the entire LinearLayout setting the top and left margins.

I wrote the following code hoping I could access the parent LinearLayout but got no success.

@Override
public boolean onDrag(View view, DragEvent event) {
if(event.getAction() == DragEvent.ACTION_DROP){
View v = (View) event.getLocalState();
ImageView iv = (ImageView) v;
ViewParent parent = iv.getParent();
LinearLayout l;
if (parent == null) {
     Log.d("TEST", "this.getParent() is null");
}
else {
      if (parent instanceof ViewGroup) {
           ViewParent grandparent = ((ViewGroup) parent).getParent();
           if (grandparent == null) {
                 Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null");
                        }
       else {
            if (parent instanceof AbsoluteLayout) {
                l = (LinearLayout) grandparent;
               Log.d("TEST","Successfully acquired linear layout");
                            }
                            else {
                                Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout");
                            }
                        }
                    }
                    else {
                        Log.d("TEST", "this.getParent() is not a ViewGroup");
                    }
                }}
TheYogi
  • 976
  • 8
  • 15

1 Answers1

0

Turns out it was as easy as doing the following

@Override
public boolean onDrag(View view, DragEvent event) {
    String TAG = "DragDrop";
    switch (event.getAction()) {
        case DragEvent.ACTION_DROP: {
            View v = (View) event.getLocalState();
            ImageView iv = (ImageView) v;

            ViewParent parent = iv.getParent();
            LinearLayout l = (LinearLayout) parent;
            AbsoluteLayout.LayoutParams params = (AbsoluteLayout.LayoutParams)l.getLayoutParams();
            x = (int) event.getX() - (l.getWidth() / 2);
            y = (int) event.getY() - (l.getHeight() / 2) + 30;
            params.x = x;
            params.y = y;
            l.setLayoutParams(params);

            iv.setVisibility(iv.VISIBLE);
            //boardName.setVisibility(View.VISIBLE);

            break;
        }
    }
    return true;
}
TheYogi
  • 976
  • 8
  • 15