Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept all touch events?

Tags:

android

How can I get an "top" View of my application (which contains Activity and all DialogFragments)? I need to intercept all touch events to handle motion of some View between DialogFragment and my Activity.

I've tried to catch them (event) through the decor view of Activity's Window with no luck:

getWindow().getDecorView().setOnTouchListener(...);
like image 823
Dmitry Zaytsev Avatar asked Nov 06 '12 14:11

Dmitry Zaytsev


1 Answers

You can override the Activity.dispatchTouchEvent to intercept all touch events in your activity, even if you have some Views like ScrollView, Button, etc that will consume the touch event.

Combining withViewGroup.requestDisallowInterceptTouchEvent, you can disable the touch event of the ViewGroup. For example, if you want to disable all the touch event in some ViewGroup, try this:

@Override
public boolean dispatchTouchEvent(MotionEvent event) {
    requestDisallowInterceptTouchEvent(
            (ViewGroup) findViewById(R.id.topLevelRelativeLayout),
            true
    );
    return super.dispatchTouchEvent(event);
}

private void requestDisallowInterceptTouchEvent(ViewGroup v, boolean disallowIntercept) {
    v.requestDisallowInterceptTouchEvent(disallowIntercept);
    int childCount = v.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = v.getChildAt(i);
        if (child instanceof ViewGroup) {
            requestDisallowInterceptTouchEvent((ViewGroup) child, disallowIntercept);
        }
    }
}
like image 165
Chris Avatar answered Sep 20 '22 12:09

Chris