Question

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!

Was it helpful?

Solution 3

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!

OTHER TIPS

You are adding getWidth() to both the horizontal and vertical. Pretty sure u need to use .getHeight() on the y2 line.

 int x2 = x1 + button.getWidth();
 int y2 = y1 + button.getWidth();

Your event may pretty much not contain absolute coordinates either. Where does it come from?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top