Search code examples
androidandroid-fragmentsontouchlistenerontouch

Using onInterceptTouchEvent in a class that extends Fragment


I have Fragment with a View which contains some clickable elements (ToggleButtons and a GridView).

I have set an onTouchListener on the View which I use to detect simple swipe gestures, this works perfectly well as long as the swipe doesn't start on any of the clickable items. I would like the swipe to work regardless of where it starts.

I understand that the ToggleButtons and GridView are probably consuming the touch event and in classes which extend ViewGroup I could override onInterceptTouchEvent or dispatchTouchEvent in subclasses of Activity.

Any ideas how I could deal with this situation when extending Fragment?

The closest I've found here is: Android adding onInterceptTouchEvent to a fragment Unfortunately there have been no replies to this question.

Thanks in anticipation.


Solution

  • Okay, got there in the end.

    I create a subclass of RelativeLayout which is the root of my layout and then within this I override onInterceptTouchEvent.

    public class RootLayout extends RelativeLayout {
    
        public RootLayout(Context context) {
            super(context);
        }
    
        public RootLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public RootLayout(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev){
            return true;
        }
    }
    

    Then replace the RelativeLayout in my xml with the new subclass.

    <com.walker.leigh.dipswitch2.RootLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/root_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    

    Thanks for your help :)