How to get current selected tab index in TabLayout?
Use OnTabSelectedListener.
And then in this listener get the getPosition()
.
Something like this:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
@Override
public void onTabSelected(TabLayout.Tab tab){
int position = tab.getPosition();
}
});
UPDATE
This method setOnTabSelectedListener()
is deprecated . Use addOnTabSelectedListener(OnTabSelectedListener)
setOnTabSelectedListener is now deprecated. you can use addOnTabSelectedListener instead. To remove the listener you can use removeOnTabSelectedListener
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});