Android TabLayout prevent activation of tabs adjacent to selected

試著忘記壹切 提交于 2020-08-10 19:35:34

问题


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>

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/51295951/android-tablayout-prevent-activation-of-tabs-adjacent-to-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!