Semyon Tikhonenko Semyon Tikhonenko - 5 months ago 102
Android Question

How to get current selected tab index in TabLayout?

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?

Answer

Use https://developer.android.com/reference/android/support/design/widget/TabLayout.html#setOnTabSelectedListener(android.support.design.widget.TabLayout.OnTabSelectedListener)

And then in this listener get the getPosition()

https://developer.android.com/reference/android/support/design/widget/TabLayout.Tab.html

Something like this:

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
@Override
public void onTabSelected(TabLayout.Tab tab){
int position = tab.getPosition();
}
});