Felix Froschauer Felix Froschauer - 1 year ago 84
Android Question

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
Lineup lineup=new Lineup(x,y);
return lineup;

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

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

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

case MotionEvent.ACTION_MOVE:

.x(event.getRawX() + dX)
.y(event.getRawY() + dY)
return false;
return true;

Answer Source

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

int[] outLocation = new int[2];

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download