Chinmay Dabke
Chinmay Dabke

Reputation: 5140

Pass ontouchlistener to parent

I have 4 buttons in my activity and each of these buttons have a onTouchListener. I want to pass that event to the button's parent which is a Linear Layout. To achieve that, I have used THIS :

button.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }

        public boolean onInterceptTouchEvent(MotionEvent ev)
        {
            onTouchEvent(ev);
            return true;
        }
    });

but it doesn't work. What could be the problem?

Upvotes: 0

Views: 757

Answers (1)

desseim
desseim

Reputation: 8248

OnTouchListener documentation indicates that onTouch() returns

True if the listener has consumed the event, false otherwise.

So since you return true, you indicate that the touch listener of your button consumed the event, and the even doesn't get propagated any further. Returning false instead will make the event be propagated further up the view hierarchy.

Note though, that a button which unconditionally doesn't listen to touch events isn't a button. I would make sure whether a TextView for example isn't enough.


Although this would be true and sufficient for a simple TextView (or any View for that matter), you should note that Button is a clickable view and by default behaves as such. This means that whatever you return as a result of onTouch(), the touch event won't be propagated further and the Button's onClick() method will be called.

To disable this behavior and have it behave as you expect, just make it non-clickable:

button.setClickable(false);

Again, using a button doesn't make much sense anymore though.

Upvotes: 1

Related Questions