Android TabLayout prevent activation of tabs adjacent to selected

I have a tab-based app. I am using A TabLayout for my tabs and a subclass of FragmentStatePagerAdapter to instantiate the fragment for the selected tab. I have disabled swiping between tabs. I am still seeing a callback to create a fragment for tabs adjacent to the selected tab. In other words, if the tab at index 0 is activated, I also see a callback to GetItem for the tab at index 1.

I want to disable that behaviour. In other words, it should only request a fragment for the active tab. Is that possible?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root">
    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabPaddingStart="0dp"
        app:tabPaddingEnd="0dp"
        app:tabPaddingTop="0dp"
        app:tabMode="fixed"
        app:tabGravity="fill" />
    <jockusch.calculator.droid.AndroidViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

2 answers

  • answered 2018-07-12 01:09 RoyalGriffin

    viewPager.setOffscreenPageLimit(0)
    

    is what you are looking for. But a ViewPager doesn't allow offscreen limit less than 1.

    source

    Use something else than a viewPager to get your desired effect. One way of doing it without viewPager would be to have a frameLayout instead and inflate a new fragment and destroy the previous one when a tab is selected.

  • answered 2018-07-12 01:12 Jackey

    The reason this is happening is due to you using a ViewPager.

    ViewPager, by default, will auto-create the adjacent Fragments because this allows the user to swipe to them whenever they wish. Creating them only when they're ready to swipe might cause lag or some unpleasant visual effects.

    ViewPager has a method called setOffscreenPageLimit(int limit) which can limit the amount of adjacent it keeps in memory, however I believe it's not possible to decrease it to 0 due to ViewPager's innate behavior.

    If you've already disabled swiping between tabs, then it sounds like what you want isn't a ViewPager. Consider just using FragmentTransactions to replace the active Fragment.