Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

mismatch of event coordinates and view coordinates in Android?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...