开发者

mismatch of event coordinates and view coordinates in Android?

开发者 https://www.devze.com 2023-01-05 02:46 出处:网络
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 MotionE

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;
    }

I am just attaching the onTouch listener to the table within the activity. But I get weird errors: the coor开发者_如何学Pythondinates 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;
}

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.


using getRawX() getRawY() seems to work.

0

精彩评论

暂无评论...
验证码 换一张
取 消