Why does location on screen always return 0?

2.7k views Asked by At

I want to know the position of an image view but its always returns 0 neither the x coordinate or y coordinate. Here is my code

    ImageView credits = (ImageView) v.findViewById(R.id.credits);
    int[] coor = {0,0};
    credits.getLocationOnScreen(coor);
    x = coor[0];
    y = coor[1];

I already use many method such as getTop(), etc. but still its return 0.

Anyone know why? I'm new to android so I really appreciate to any answers.

4

There are 4 answers

1
Topsy On BEST ANSWER

Are you doing that in the onCreate method ?

If yes, it's too early to check for getLocationOnScreen() in onCreate()

Solution here : https://stackoverflow.com/a/13244091/5392383

0
yotam hadas On

Are you using this code inside onCreate() method?

After quick search I found THIS POST.

shortly, it sayd onCreate() is too early to use getLocationOnScreen, you should use it in side the method onWindowFocusChanged() when your Activity gains focus.

0
Manish On

Pls try this

  @Override
    protected void onResume() {
        super.onResume();
        ImageView credits = (ImageView) v.findViewById(R.id.credits);
        int[] coor = {0,0};
        credits.getLocationOnScreen(coor);
        x = coor[0];
        y = coor[1];
    }
0
Manthan Patel On
  credits.post(new Runnable() {
        @Override
        public void run() {
           int[] coor = {0,0};
           credits.getLocationOnScreen(coor);
           x = coor[0];
           y = coor[1]; 
        }
    })

try like this