Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In order to utilize InterceptTouchEvent in Fragment, you need to override the onTouchEvent() method in the fragment and call the getParent().requestDisallowInterceptTouchEvent(true) method to prevent the parent view from intercepting the touch event.

Here's an example:

public class MyFragment extends Fragment {

    // Declare your views here

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);

        // Initialize your views here

        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Set touch listener on your view
        myView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // Disable parent view from intercepting touch event
                        getParent().requestDisallowInterceptTouchEvent(true);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // Handle move action here
                        break;
                    case MotionEvent.ACTION_UP:
                        // Handle up action here
                        break;
                }
                return true;
            }
        });
    }
}

In this example, myView is the view you want to intercept touch events for. By calling getParent().requestDisallowInterceptTouchEvent(true) in the ACTION_DOWN case, you prevent the parent view from intercepting touch events and allow your view to receive all touch events instead. You can then handle the touch events in the switch case statement as needed.