How to use TabLayout with ViewPager2 in Android

前端 未结 7 1743
春和景丽
春和景丽 2020-12-29 18:24

I want to use com.google.android.material.tabs.TabLayout component with Android\'s new ViewPager implementation androidx.viewpager2.widget.Vi

7条回答
  •  梦毁少年i
    2020-12-29 19:11

    Initialize the TabLayoutMediator object with an object of TabLayout, ViewPager2 , autoRefresh -- boolean type, and an object of OnConfigurationChangeCallback.

    TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, true, new TabLayoutMediator.OnConfigureTabCallback() {
      @Override
      public void onConfigureTab(TabLayout.Tab tab, int position) {
        // position of the current tab and that tab  
      }
    });
    

    Finally just call attach() to the TabLayoutMediator object to wire up the tablayout to the viewpager :-

     tabLayoutMediator.attach();
    

    autoRefresh - key if set to true -- ( By default its set to true )

    RECREATES all the tabs of the tabLayout if notifyDataSetChanged is called to the viewpager adapter.

    Use the contents of TabLayoutMediator.java

提交回复
热议问题