Android中的事件坐标和视图坐标不匹配? [英] mismatch of event coordinates and view coordinates in Android?

查看:163
本文介绍了Android中的事件坐标和视图坐标不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编写一个可以识别Android中的自定义事件的应用程序:您可以在TextView上握住一段时间,并改变颜色。我正在使用MotionEvent坐标,并检查它们是否在特定TextView的范围内,该视图位于表内。

I've been trying to write a little application that recognizes custom events in Android: you hold your finger over a TextView for a certain length of time, and it changes color. I'm using the MotionEvent coordinates and checking if they are within the bounds of a particular TextView, which is within a table.

private boolean checkBounds(TextView v, MotionEvent event) {

        int[] origin = new int[2];
        v.getLocationOnScreen(origin);

        if ((event.getX() > origin[0]) && (event.getX() < (origin[0] + v.getMeasuredWidth()))) {
            if ((event.getY() > origin[1]) && (event.getY() < (origin[1] + v.getMeasuredHeight()))) {
                return true;
            }
        }
        return false;
    }

我只是将onTouch监听器附加到活动中的表中。但是我有奇怪的错误:坐标似乎被一个视图关闭(即如果我触摸上面的视图下面的视图反应);或者有时候会有反应,而另一个则不会。任何想法可能会发生什么?

I am just attaching the onTouch listener to the table within the activity. But I get weird errors: the coordinates seem to be off by one view (i.e. if I touch the view below the view above reacts); or sometimes one will react, and the other will not. Any idea what might be going on?

推荐答案

我通常会因为通知栏的大小而发生...尝试这样做:

I usually happens because of the size of the notification bar.... try to do this:

private boolean checkBounds(TextView v, MotionEvent event) {
    // here you will have to get a reference of the global view (the View that holds the UI)
    View globalView = ...; // the main view of my activity/application
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(dm);
    int topOffset = dm.heightPixels - globalView.getMeasuredHeight();

        int[] origin = new int[2];
        v.getLocationOnScreen(origin);

    final int x = origin[0];
    final int y = origin[1] - topOffset;


        if ((event.getX() > x) && (event.getX() < (x + v.getMeasuredWidth()))) {
            if ((event.getY() > y) && (event.getY() < (y + v.getMeasuredHeight()))) {
                return true;
            }
        }
    return false;
}

无论如何...我相信有更好的方法来实现你想。据我所知, TextView 可以发送 OnClik 事件。

Anyway... I'm sure there are better ways to implement what you want. As far as I know, TextViews are able to send OnClik events.

这篇关于Android中的事件坐标和视图坐标不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆