Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of ImageView relative to screen programmatically

I want to get the position of my ImageView programmatically. By position, I mean the distance in pixel from top of the screen to that ImageView. I have tried every other solution posted in stackoverflow but it's not working for me. My minimum API level is 8.

These are the codes I have tried-

ImageView image = (ImageView) findViewById(R.id.imageView1);
1) image.getTop();

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

3) image.getLocationOnScreen(int[] locaiton);
like image 867
Naddy Avatar asked Oct 21 '13 14:10

Naddy


2 Answers

You need to wait for the callback when the layout has been placed with children views. This is the listener you need to add to your root view in order to calculate the coordinates for your image. Otherwise it will return 0.

getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
        getViewTreeObserver().removeGlobalOnLayoutListener(this);

        int[] locations = new int[2];
        image.getLocationOnScreen(locations);
        int x = locations[0];
        int y = locations[1];
    }
});
like image 110
Carnal Avatar answered Nov 17 '22 16:11

Carnal


Use View.getLocationOnScreen() or getLocationInWindow() BUT ONLY after the view has been layout. getTop(), getLeft(), getBottom() and getRight() return the position relative to its parent.

like image 7
gunar Avatar answered Nov 17 '22 16:11

gunar