Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnClickListener on Views inside a custom ScrollView

Tags:

android

I'm havin a horizontal ScrollView inside a ViewPager. To prevent the ViewPager to be scrolled when the end of the ScrollView is reached I use this class as per hint on SO:

public class CustomScrollView extends HorizontalScrollView {

public CustomScrollView(Context p_context, AttributeSet p_attrs) {
    super(p_context, p_attrs);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent p_event) {

    return true;
}

@Override
public boolean onTouchEvent(MotionEvent p_event) {


    if (p_event.getAction() == MotionEvent.ACTION_MOVE
            && getParent() != null) {
        getParent().requestDisallowInterceptTouchEvent(true);
    }

    return super.onTouchEvent(p_event);
}
}

The onInterCeptTouchEvent seems to consume any click to that View and everything inside it. When I put Views into that ScrollView, their OnClickListeners won't be called.

When I let onInterceptTouchEvent return false, the OnClickListeners are called, but the ScrollView can't be scrolled.

How can I put clickable Views inside that ScrollView?

EDIT: After implementing Rotem's answer, the onClickListener works, but it doesn't only fire on click events but also on others, like fling. How can this be prevented?

like image 841
fweigl Avatar asked Apr 15 '13 14:04

fweigl


3 Answers

try to call onTouchEvent inside the implementation of onInterceptTouchEvent and then return false.

like image 151
Rotem Avatar answered Nov 15 '22 16:11

Rotem


Well, minutes after starting a bounty I found out how it works:

in onInterceptTouchEvent I

return super.onInterceptTouchEvent(p_event);
like image 33
fweigl Avatar answered Nov 15 '22 18:11

fweigl


Here is complete solution using answers to this question.

public class CustomHorizontalScrollView extends HorizontalScrollView {

        public CustomHorizontalScrollView(Context context) {
                super(context);

        }
        public CustomHorizontalScrollView(Context context, AttributeSet attrs) {
                super(context, attrs);
        }

        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
                boolean result = super.onInterceptTouchEvent(ev);
                if(onTouchEvent(ev)) {
                        return result;
                } else {
                        return false;
                }
        }

        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            if (ev.getAction() == MotionEvent.ACTION_MOVE
                    && getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
                return super.onTouchEvent(ev);
        }

}
like image 1
Akram Avatar answered Nov 15 '22 16:11

Akram