Search code examples
javaandroidpositionimageview

Find real position of an ImageView


I would like to find the real position of an ImageView drawable. Currently it returns 0, because the ImageView is resized by relative layout. But the drawable inside the image view is not fill all in the relative layout. It fills the full width, and it is centered vertically with empty space at the top and bottom of it.

    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relative_layout_main"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:gravity="center"
    >

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/drawable"/>

</RelativeLayout>

Please see the attached screenshot. I am searching for x and y of red rectangle and the width, height of it.

enter image description here


Solution

  • You have to wait until the Views have been measured. You can use an OnGlobalLayoutListener.

    imageView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
        public void onGlobalLayout() {
            int height = imageView.getHeight();
            int width = imageView.getWidth();
            int x = imageView.getLeft();
            int y = imageView.getTop();
    
            // don't forget to remove the listener to prevent being called again 
            // by future layout events:
            imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        }
    });
    

    Because your ImageView fills the entire screen, it will probably give the device's width as width, and the window height as height. To get the actual width and height of the image inside the ImageView, set the RelativeLayout's height to match_parent and set the ImageView's height to wrap_content, and set the ImageView's layout_gavity to center_vertical.