1

I thought this is a pretty relevant and common question, but I couldnt find an answer. At the moment I have this method:

public boolean onTouchEvent (MotionEvent evt){
  if (evt.getAction() == MotionEvent.ACTION_DOWN) {
     do stuff ...
  }
}

So if the user taps on the screen (wherever) the code is executed. Now I want the distinction between the right side of the display and the left side (left side means --> go back).

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Nina Seil
  • 53
  • 5
  • the user has to tap on a VIEW in order for you to know where they are tapping...to some extent. 0,0 is the top left corner of the device. to get the X/Y you have to get the display width/height. and figure out where in the view they tapped. – letsCode Feb 20 '18 at 17:12

2 Answers2

3

You can do this many ways. Here is one of them:

Attach onTouch listener to the view, which stretches to its edges. (For example your RelativeLayout which holds rest of views)

private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        float halfOfAScreen = mainLayout.getMaxWidth() / 2;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float fingerPosition = event.getX();
                if(fingerPosition < halfOfAScreen) {
                    onBackPressed();
                }
                return true;
            default: 
                return false;
        }
    }
};
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
Radzik
  • 244
  • 2
  • 16
  • 2
    Hey! I dont know why but the OnTouchListener didnt work for me.. but I added your code to my OnTouchEvent and this worked (a bit better). With a toast I saw that my variable "fingerPosition" was between 100 and 1000 and the "halfOfScreen" was 1.07E9.. do you have an idea why? I changed it to 560 cause this is approx my half. Now it works! – Nina Seil Feb 20 '18 at 19:54
  • Hey. I’m glad that it worked for you at least in some way I’m not sure why you are getting such result from this getWidth(). I’ll check it out and let you know if I have some clue. Good luck with your code! – Radzik Feb 21 '18 at 18:21
  • This doesn't work. You must use `getWidth()` instead of `getMaxWidth()`. Otherwise you get the problem that Nina described in her comment above – mathematics-and-caffeine Dec 29 '21 at 16:59
0

Refer to this post on how to get touch position.

It seems in your case you will use

int x = (int)event.getX();
int y = (int)event.getY();

and work within the bounds of your layout that you want the app to react to.

thugzook
  • 88
  • 9
  • I think it should be `event.getRawX()` and `event.getRawY()`. There is no way to `getX()` and `getY()` in case of event. They are the methods of `View` class. – CopsOnRoad Feb 20 '18 at 17:32