解决ViewPager2+TabLayout懒加载问题,Fragment被创建多次

ViewPager2默认只加载当前页面,相当于官方处理了Fragment的懒加载问题,当你使用代码

     new TabLayoutMediator(tabLayout, viewPager, true, new TabLayoutMediator.TabConfigurationStrategy() {

            @Override

            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {

                tab.setText(titles.get(position));

            }

        }).attach();

此时当你滑动ViewPager2时,滑动到某个Fragment页面才会加载,执行onCreateView()方法,

但是当你手动点击TabLayout时,此时懒加载就会失效,onCreateView()会被执行多次,

原因就是...此时ViewPager2默认是平滑滚动的,滚动滑过的Fragment都会被加载,

只需修改代码

       new TabLayoutMediator(tabLayout, viewPager, true,false, new TabLayoutMediator.TabConfigurationStrategy() {

            @Override

            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {

                tab.setText(titles.get(position));

            }

        }).attach();

其中,第二个boolean参数为smoothScroll 一定要填false,便可实现懒加载