How to get current selected tab index in TabLayout?

Semyon Tikhonenko picture Semyon Tikhonenko · Jul 2, 2015 · Viewed 57.1k times · Source

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

JARP picture JARP · Jul 2, 2015

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)