【问题标题】:getting wrong absolute coordinates android得到错误的绝对坐标android
【发布时间】: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


【解决方案1】:

您正在将 getWidth() 添加到水平和垂直。很确定你需要在 y2 行上使用 .getHeight() 。

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

【讨论】:

  • getHeight 代替?
  • 今晚大家都喝醉了吗? getHeight,而不是垂直的 getWidth。
  • 使用 getLeft(), getTop() 获取 x,y 相对于父视图的位置。我相信触摸事件的 x,y 也与父视图相关。
  • 谢谢你,但我得到了解决方案。请检查我的答案!
  • 只是同样的事情相反...而不是比较相对相对,你现在比较绝对和绝对。
【解决方案2】:

您的event 也可能几乎不包含绝对坐标。它来自哪里?

【讨论】:

  • 此事件为线性布局。在我的线性布局中,有两种相对布局。在其中一个相对布局中,我有这个按钮。 ontouchlistener 的两个相对布局都返回 false,所以这个事件由我的主根线性布局处理。
  • 没关系。但是不要忘记你的手机也有状态栏和类似的东西。尝试将 event 的坐标转换为屏幕坐标,并保持其余逻辑不变。
【解决方案3】:

我自己得到了答案。这很简单。

不使用:

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

我用过:

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

问题就解决了!

【讨论】:

    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多