Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
Semyon Avatar asked Jul 01 '15 22:07

Semyon


People also ask

How do I change tab position in android programmatically?

By default if you select a tab it will be highlighted. If you want to select Explicitly means use the given commented code under onTabSelected(TabLayout. Tab tab) with your specified tab index position. This code will explains about change fragment on tab selected position using viewpager.

How do you use TabLayoutMediator?

Establish the link by creating an instance of this class, make sure the ViewPager2 has an adapter and then call attach() on it. Instantiating a TabLayoutMediator will only create the mediator object, attach() will link the TabLayout and the ViewPager2 together.


2 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)

like image 106
JARP Avatar answered Sep 20 '22 16:09

JARP


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) {         }     }); 
like image 20
DoronK Avatar answered Sep 23 '22 16:09

DoronK