Search code examples
androidandroid-custom-viewtouch-eventontouchlistenercustom-view

Use touch event for custom view without interfering with the user's touch event


I create a library for a custom view. I use OnTouchListener() to handle custom touch events, but I want the user to be able to set their own OnTouchListener(). How can I handle it?!


Solution

  • You should override onTouchEvent() for custom views

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Toast.makeText(this.getContext(), "Touched layout", Toast.LENGTH_SHORT).show();
        Log.d("TOUCH", "Touched layout");
    
        return super.onTouchEvent(event);
    }
    

    According to official docs

    onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.