Search code examples
androiddrag-and-dropmarginslayoutparams

How to get the margins of a View, moved to a position which isn't known at run time


As of right now I'm working on an Android App which provides some tools trainers can use to communicate with their trainees, one of the tools is a lineup editor which consists out of drag and drop able spinners*.

*there is a default Layout set->football Lineup: 4/4/2

If the User presses the saveBtn, the lineup gets saved as Custom obj. called lineup which holds 2 Arrays with x and y coords. It gets repsesented in a Recyclerview which holds a button called "Edit". By pressing on the edit button i want to show the saved lineup by setting those x and y coords to the spinners in the default edit-mode activity.

My problem with all this is, that the programm always returns the default margins set in the .xml.

I tried it with .getLeft and .getBottom which you can see here:

public Lineup saveLineup(){
    int[] x=new int[10];
    int[] y=new int[10];
    LayoutParams[] layouts=new LayoutParams[10];

    for(int i=0; i<10; i++){
        x[i]=positions[i].getLeft();//positions contains all the spinners used in the .xml
        y[i]=positions[i].getBottom();
    }
    Lineup lineup=new Lineup(x,y);
    return lineup;
}

To drag and drop i am overwriting the OnTouch Methode as follows:

@Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:

                dX = view.getX() - event.getRawX();
                dY = view.getY() - event.getRawY();
                break;

            case MotionEvent.ACTION_MOVE:

                view.animate()
                        .x(event.getRawX() + dX)
                        .y(event.getRawY() + dY)
                        .setDuration(0)
                        .start();
                break;
            default:
                return false;
        }
        return true;
    }

Solution

  • Instead of getLeft(), getBottom() methods, use getLocationOnScreen(int[] outLocation) to get coordinates of the view relative to the screen.

    int[] outLocation = new int[2];
    position[i].getLocationOnScreen(outLocation);
    
    int marginleft=outLocation[0];
    int margintop=outLocation[1];
    

    See this for details: https://developer.android.com/reference/android/view/View.html#getLocationOnScreen(int[])