Mateus Zitelli
Mateus Zitelli

Reputation: 1302

Make views intercept taps but not scroll events

My problem is that I can't find a way where I intercept taps without blocking the propagation of other events, such as scroll, to the views bellow it.

I'm using a custom view to handle the tap events:

public class TapableImageView extends AppCompatImageView {
    private GestureDetectorCompat mDetector;
    ...
    public void setOnTapListener(OnTapListener onTapListener){
        mDetector = new GestureDetectorCompat(getContext(), new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent event) {
                onTapListener.onTap(TapableImageView.this);
                return true;
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        if(mDetector != null)
            return !mDetector.onTouchEvent(ev);
        return false;
    }
}

Upvotes: 0

Views: 413

Answers (2)

rafsanahmad007
rafsanahmad007

Reputation: 23881

try this code:

view.setOnTouchListener(new OnTouchListener() {

        private long startClickTime;

        @Override
        public boolean onTouch(View view, MotionEvent event) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {

                startClickTime = System.currentTimeMillis();
                yourview.dispatchTouchEvent(event);

            } else  if (event.getAction() == MotionEvent.ACTION_MOVE) {

                yourview.dispatchTouchEvent(event);

            }
            else if (event.getAction() == MotionEvent.ACTION_UP) {

                if (System.currentTimeMillis() - startClickTime < ViewConfiguration.getTapTimeout()) {

                    // Touch was a simple tap
                    return true;

                } else {

                    // Touch was a not a simple tap.
                    return false;

                }

            }

            return true;
        }

    });

check if the time between the ACTION_DOWN and ACTION_UP events is lower or higher than the value given by ViewConfiguration.getTapTimeout()

Upvotes: 1

firegloves
firegloves

Reputation: 5709

You must return false to indicate that the event is not consumed

Upvotes: 0

Related Questions