I have just migrated my old ActionBar
to new TabLayout
( Support Material Design ).
Everything is great but I can\'t intercept tab selectio
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.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();
}
});