0

I have an app where you can press on a screen and a method gets executed, and where you can long press and another method gets executed. The problem is, when I long press on the screen the normal onClickListener also gets executed, which I don't want. They both are simple onClickListeners, the normal one is using the MotionEvent ACTION_UP. Is there any way to prevent that from happening? So I don't want to execute the ACTION_UP in the normal onTouchListener when the onLongClickListener executed.

Code:

layout.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {

            }
            return false;
        }
    });
    layout.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
Broadwell
  • 1,343
  • 2
  • 19
  • 33

3 Answers3

1

If you still want to onTouch

    int flag=0
    layout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if(flag==0){
              //do something 
            }else{
              flag=0;
            }

        }
        return false;
    }
});
layout.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        flag=1
        return true;
    }
});
krishna
  • 609
  • 8
  • 21
1

LongClick and Click are in the same level, while Touch isn't (actually LongClick an Click are dispatched from onTouchEvent).

In your code, you always return false in onTouch method, so you don't comsume the event and it will be passed to the next level (LongClick, Click...), this is why when you long press the screen you have the both method called.

  • Suggestion1:

Use ClickListener instead of TouchListener.

  • Suggestion2:

Use GestureDetector to handle all events (touch, longclick...). This is an example

  • Suggestion3:

Use a flag to perform the desired event.

private boolean longClick = false;


layout.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
       if (longClick) {
             longClick = false;
          }
        return false;
    }
});

layout.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        longClick = true;
        return false;
    }
});
  • Suggestion4:

Use a handler with runnable. Example1 and Example2

Community
  • 1
  • 1
Rami
  • 7,879
  • 12
  • 36
  • 66
0

If onclick does the same as you intended use onclick listner instead of ontouch that way you wont trigger onclick when you longclick.

krishna
  • 609
  • 8
  • 21