1

I have a problem with getting image view top and left position.

My image view is set in center of a relative layout. When I use getleft() and getTop() the result for me is 0 and 0.

my layout file is :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:scaleType="center"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

This is really emergency for me.

My issue:

I wrote a code for move and zooming image view and that work correctly but in first click, image view position changing to 0, 0 and I want to get default position for prevent change in first click.

Meysam Valiolahi
  • 188
  • 1
  • 1
  • 12

2 Answers2

1

Not sure if I get what you mean, but you can try:

ImageView img = (ImageView) findViewById(R.id.image_view);
img.getViewTreeObserver().addOnGlobalLayoutListener(
            new ViewTreeObserver.OnGlobalLayoutListener(){

                @Override
                public void onGlobalLayout() {

                    int left = img.getLeft();
                    int top = img.getTop();
                    //Toast the height and top...
                }

            });

Since the image will not be rendered yet into the screen in onCreate therefore you will always get 0 when you call getLeft() and getTop()

More explanation here

EDIT

Set the layout width and height of imageview to wrap_content

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:scaleType="center"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>
Community
  • 1
  • 1
Malvin
  • 692
  • 5
  • 8
  • thanks but my problem is still alive, my imageview is on center of screen but left and top return zero.. – Meysam Valiolahi Oct 08 '14 at 07:31
  • `android:layout_width="fill_parent" android:layout_height="fill_parent"` Your layout code says it's `fill_parent`, try changing to `wrap_content` – Malvin Oct 08 '14 at 07:53
0

int location[]=new int[2];

rlBoard.getLocationOnScreen(location);

You can also use getX and getY method of imageview but this method works from api 11

Pawan asati
  • 292
  • 2
  • 13