Search code examples
androidcoordinate-systems

getting wrong absolute coordinates android


I am trying to get absolute screen coordinates of a button on android. But I am getting them wrong!

I have written my code in a such a way that when my finger goes over the button, it should change its background color to blue. But that's not what's happening. Instead, It changes the background color to blue of the button below it.

Here is my code:

int x = (int) event.getX();
int y = (int) event.getY();

int pos[] = new int[2];
button.getLocationOnScreen(pos);
int x1 = pos[0], y1 = pos[1];
int x2 = x1 + button.getWidth();
int y2 = y1 + button.getWidth();

if(x <=x2 && x >= x1  && y <= y2 && y >= y1)
{
    button.setBackgroundColor(Color.BLUE);
}
else
{
    button.setBackgroundColor(Color.YELLOW);
}

What could be the issue?

Thanks!


Solution

  • I got the answer myself. It's quite simple.

    Intead of using :

    int x = (int) event.getX();
    int y = (int) event.getY();
    

    I used:

    int x = (int) event.getRawX();
    int y = (int) event.getRawY();
    

    And the problem is solved!