1

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.

NSouth
  • 5,067
  • 7
  • 48
  • 83
  • 1
    Your example is using a `ViewPager`. There is a difference between the pager and the adapter. – tachyonflux Sep 16 '15 at 00:36
  • @karaokyo, thank you. You are completely right. I was confusing the `FragmentStatePagerAdapter` with the ViewPager. I used the solution suggested below and it works great. Cheers! http://stackoverflow.com/a/9650884/3165621 – NSouth Sep 16 '15 at 00:46
  • How did you implement onInterceptTouchEvent() ?? – Ali Obeid Nov 24 '17 at 11:37

1 Answers1

1

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);
    }
}
tachyonflux
  • 20,103
  • 7
  • 48
  • 67
  • The `getCurrentItem()` was exactly the piece I was missing. Thank you! – NSouth Sep 16 '15 at 01:46
  • Is there any solution for an actual FragmentStatePagerAdapter, for the millions of people that are lead here? – behelit Aug 15 '19 at 06:28
  • Hey @behelit I believe you can use FragmentStatePagerAdapter as it is but you will have to chage the ViewPager defined in xml to CustomViewPager. And to achieve this we have to create new class eg.CustomViewPager extending ViewPager and overide the function. check this to see how to create custom viewpager. https://stackoverflow.com/questions/41656902/disable-swipe-in-fragmentpageradapter-android/41657057#41657057 – Kunchok Tashi May 06 '20 at 11:49