mismatch of event coordinates and view coordinates in Android?
Asked Answered
L

2

1

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 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?

Lepto answered 30/6, 2010 at 18:11 Comment(0)
C
3

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.

Corkboard answered 30/6, 2010 at 18:20 Comment(1)
Thanks, that works beautifully! BTW I am using my own event framework because the click is not a standard click (it is one-second hold that ends with a swipe). Thanks, Nick.Lepto
L
1

using getRawX() getRawY() seems to work.

Lepto answered 30/6, 2010 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.