Home » Android » android – getLocationOnScreen() returns zero

android – getLocationOnScreen() returns zero

Posted by: admin June 15, 2020 Leave a comment

Questions:

am using the following code for getting the position of a button but it always returning zero.
Why this happening

    Button b=(Button) findViewById(R.id.button2);
    final int[] x=new int[2];
    b.getLocationOnScreen(x);

Iam sure someone here can help me

How to&Answers:

Try this..

Button b; 

in Globel variable

then onCreate()

b=(Button) findViewById(R.id.button2);

After onCreate();

@Override
public void onWindowFocusChanged (boolean hasFocus) {
       final int[] x=new int[2];
        b.getLocationOnScreen(x);
}