views:

178

answers:

2

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?

A: 

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.

Cristian
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.
Nicholas Chubrich
A: 

using getRawX() getRawY() seems to work.

Nicholas Chubrich