Home » Android » java – How to get current selected tab index in TabLayout?

java – How to get current selected tab index in TabLayout?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&Answers:

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)

Answer:

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) {
        }
    });

Answer:

You can simply do it by calling getSelectedTabPosition() on your TabLayout instance like:

int tab_position=tabLayout.getSelectedTabPosition();

and in Kotlin

val tabPosition = mTabLayout.selectedTabPosition

Answer:

if you are using tabs with viewpager then the asked task could be done as follows:

use the following code after tabLayout.setUpWithViewPager(viewPager)

tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
        switch(tab.getPosition()){
            // do something here
        }
        super.onTabSelected(tab);
    }
});

Answer:

If you are using TabLayout inside ViewPager (and initializing it with setupWithViewPager()), you can do it using ViewPager instance.

    View view = inflater.inflate(R.layout.fragment_view_pager_tabs, container, false);
    ViewPager viewPager = view.findViewById(R.id.view_pager_tabs);
    viewPager.setAdapter(pagerAdapter);
    TabLayout tabLayout = viewPager.findViewById(R.id.tab_layout);
    tabLayout.setupWithViewPager(viewPager);
    int item = viewPager.getCurrentItem(); // get
    viewPager.setCurrentItem(item, true);  // set