I have just migrated my old ActionBar
to new TabLayout
( Support Material Design ).
Everything is great but I can't intercept tab selection The method onTabSelected
is only called the first time TabLayout
is displayed, but when clicking tabs, nothing happens! Any idea what's wrong with this code?
tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); mViewPager = (ViewPager) findViewById(R.id.pager); if (mViewPager != null) { setupViewPager(); } tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { numTab = tab.getPosition(); prefs.edit().putInt("numTab", numTab).apply(); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); tabLayout.setupWithViewPager(mViewPager);
When you call setupWithViewPager
, this will internally call setOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager));
, overriding your OnTabSelectedListener
.
Instead, your listener should extend TabLayout.ViewPagerOnTabSelectedListener, then override onTabSelected()
and call setOnTabSelectedListener()
after setupWithViewPager()
:
tabLayout.setupWithViewPager(mViewPager); tabLayout.setOnTabSelectedListener( new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) { @Override public void onTabSelected(TabLayout.Tab tab) { super.onTabSelected(tab); numTab = tab.getPosition(); prefs.edit().putInt("numTab", numTab).apply(); } });
Here is a somewhat fuller example with three tabs. It uses the newer addOnTabSelectedListener
rather than setOnTabSelectedListener
.
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); tabLayout.addTab(tabLayout.newTab().setText("Tab 2")); tabLayout.addTab(tabLayout.newTab().setText("Tab 3")); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); final ViewPager viewPager = (ViewPager) findViewById(R.id.pager); final PagerAdapter adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount()); viewPager.setAdapter(adapter); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); Log.i("TAG", "onTabSelected: " + tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { Log.i("TAG", "onTabUnselected: " + tab.getPosition()); } @Override public void onTabReselected(TabLayout.Tab tab) { Log.i("TAG", "onTabReselected: " + tab.getPosition()); } });
Notes:
onTabSelected
and onTabUnselected
are called every time there is a change in tabs.onTabReselected
is called whenever a tab is clicked again while it is already showing.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With