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?
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.
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.
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)
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) { } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With