Android view's getTop(), getLeft(), getX(), getY(), getWidth(), getHeight() methods

Carmine picture Carmine · May 13, 2015 · Viewed 20.9k times · Source

I am writing a drag and drop application and got really confused because of some parameters.

Please help to figure out.

First of all, I read the documentation for the View class and got the following explanations.

getX() : The visual x position of this view, in pixels.

getY() : The visual y position of this view, in pixels.

getWidth() : Return the width of the your view.

getHeight() : Return the width of the your view.

getTop() : Top position of this view relative to its parent.

getLeft() : Left position of this view relative to its parent.

Now when we finished with the official documentation, let's see what do we have.

I have an image with original size 500x500 called circle.

enter image description here

And here's the actual screenshot of my application

enter image description here

Here is the xml for the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/circle" />
</LinearLayout>

Now what am I concerned about. When I watch my locals, I get the following, which really confuses me.

enter image description here

I don't see any problem with the getX() and getY() functions, because they actually show me where does the image begin.

As the documentation states, the getWidth() and getHeight methods return the width and height of the view but the watch window tells me that my getWidth() and getHeight are 300, which I really can't understand, because in my XML I've set them 100dp each, so do the functions return me them in a different measurement, and how do I convert it to dp.

And finally, it tells me that getTop() and getLeft are 700 and 300, and as the documentation says, they are the position of the image relative to it's parent. But isn't my parent the Linear Layout, so what do this numbers mean in sense of screen positioning?

Answer

Ivan Skoric picture Ivan Skoric · May 13, 2015

All these measurement methods return sizes in pixels( px ), not density-pixels ( dp ). If you want to convert it you can get the density by calling:

float density = getResources().getDisplayMetrics().density;

And then divide the values you get with the provided density, for example:

int widthDp = (int)(img.getWidth() / density);