Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23972

How to intercept all touch events?

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(...);

Upvotes: 14

Views: 13067

Answers (2)

Oleksandr Nos
Oleksandr Nos

Reputation: 617

If you wonder how to intercept all touch events in DialogFragments, here you go:

abstract class BaseDialogFragment : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return object : Dialog(requireContext()){
            override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
                // do your thing here
                return super.dispatchTouchEvent(ev)
            }
        }
    }

}

Upvotes: 0

Chris
Chris

Reputation: 724

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);
        }
    }
}

Upvotes: 25

Related Questions