【发布时间】:2014-02-22 09:09:59
【问题描述】:
我正在尝试获取 android 上按钮的绝对屏幕坐标。但我理解错了!
我以这样一种方式编写了我的代码,当我的手指越过按钮时,它应该将其背景颜色更改为蓝色。但事实并非如此。而是将其下方按钮的背景颜色更改为蓝色。
这是我的代码:
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);
}
可能是什么问题?
谢谢!
【问题讨论】:
-
不要忘记与密度无关的像素:developer.android.com/guide/practices/… 仅使用 getX() 或 getY() 无法获得实际像素位置,因为您没有考虑屏幕的密度.
-
那么我如何获得实际的像素位置?
-
@DroidFan 他误导了你。您正在使用实际像素。问题可能来自不同的坐标系。
-
@AlaksiejN。谢谢。你能帮我找到灵魂吗?
-
@user3126670 在 Android SDK 中。
标签: android coordinate-systems