1

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.

MWiesner
  • 8,868
  • 11
  • 36
  • 70

4 Answers4

1

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

Community
  • 1
  • 1
Topsy
  • 1,023
  • 1
  • 11
  • 26
0

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.

Community
  • 1
  • 1
yotam hadas
  • 702
  • 3
  • 14
0
  credits.post(new Runnable() {
        @Override
        public void run() {
           int[] coor = {0,0};
           credits.getLocationOnScreen(coor);
           x = coor[0];
           y = coor[1]; 
        }
    })

try like this

Manthan Patel
  • 993
  • 1
  • 9
  • 20
0

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];
    }
Manish
  • 1,071
  • 2
  • 10
  • 27