When I use ActionBar tabs, I use this code.
private int getCurrentTabIndex() {
ActionBar actionBar = activity.getSupportActionBar();
ActionBar.Tab selectedTab = actionBar.getSelectedTab();
if(selectedTab == null){
return 0;
}
return selectedTab.getPosition();
}
But how can I do it using TabLayout?
If you are using
TabLayout
insideViewPager
(and initializing it withsetupWithViewPager()
), you can do it using ViewPager instance.Use OnTabSelectedListener.
And then in this listener get the
getPosition()
.Something like this:
UPDATE
This method
setOnTabSelectedListener()
is deprecated . UseaddOnTabSelectedListener(OnTabSelectedListener)
if you are using tabs with viewpager then the asked task could be done as follows:
use the following code after
tabLayout.setUpWithViewPager(viewPager)
setOnTabSelectedListener is now deprecated. you can use addOnTabSelectedListener instead. To remove the listener you can use removeOnTabSelectedListener
You can simply do it by calling
getSelectedTabPosition()
on yourTabLayout
instance like:and in Kotlin