androidandroid-fragmentsandroid-viewpagerfragmentstatepageradapter

How do I disable swiping on FragmentStatePagerAdapter?


I'm following the tutorial here which uses a TabLayout with a FragmentStatePagerAdapter. Everything is great, except I need to disable swiping on my second tab, as it uses horizontal scrolling. It's okay if scrolling is disabled for all tabs, but It would be awesome if it were only disabled for the second one.

It looks like for a ViewPager I would override the onInterceptTouchEvent() method, but this does not appear to be an option for FragmentStatePagerAdapter. Any ideas on how to do this? Thanks.

Edit: I only have two fragments, so if FragmentStatePagerAdapter is not appropriate, I'm open to suggestions.

Edit 2: the problem of not swiping has been solved. However, I'd still like to know how to prevent swiping for only the 2nd fragment.


Solution

  • Modify the onInterceptTouchEvent and onTouchEvent to exclude only the tab index that you want:

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        switch(getCurrentItem()){
            case 1:
                return false;
            default:
                return super.onInterceptTouchEvent(event);
        }
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch(getCurrentItem()){
            case 1:
                return false;
            default:
                return super.onTouchEvent(event);
        }
    }