How to get current selected tab index in TabLayout

2020-06-07 01:56发布

问题:

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?

回答1:

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)



回答2:

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


回答3:

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


回答4:

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


回答5:

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