tags:

views:

42

answers:

2

Can I get a View's x/y position (relative to the root layout of my Activity) in Android?

+2  A: 

From Android View docs.

Position The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel.

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth() (see Size for more information about the width.)

Serapth
I wanted to know something a bit diferent - if I can get position relative to the root layout of my Activity.
fhucho
A: 

Try...

private int getRelativeLeft(View myView){
    if(myView.getParent()==myView.getRootView())
        return myView.getLeft();
    else
        return myView.getLeft() + getRelativeLeft(myView.getParent());
}


private int getRelativeTop(View myView){
    if(myView.getParent()==myView.getRootView())
        return myView.getTop();
    else
        return myView.getTop() + getRelativeTop(myView.getParent());
}

Let me know if that works. It should recursively just add the top and left positions from each parent container. You could also implement it with a Point if you wanted.

jandjorgensen
getRelativeLeft() this is need add cast,but when i add (View) or (button) ((Object) myView.getParent()).getRelativeTop(),it is also not right
pengwang
I did something very similar but i checked for the root view by getId == R.id.myRootView.
fhucho
Fixed some mistakes
jandjorgensen
Log.i("RelativeLeft", ""+getRelativeLeft(findViewById(R.id.tv))); Log.i("RelativeTop", ""+getRelativeTop(findViewById(R.id.tv))); i get all is 0;textView in layout is as follows<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:id="@+id/tv" android:layout_marginBottom="69dip" android:layout_marginLeft="69dip" />
pengwang