Reputation: 2411
I am trying to use TabLayout in my Activity. Each Tab takes user to a fragment.
getFragmentManager().popBackStack()
.Now I also want to update selected tab to Tab1.Is there any way I can mark a tab as selected in TabLayout without invoking TabSelectedListener?
Upvotes: 5
Views: 2281
Reputation: 948
just do this:
TabLayout.Tab tab = tabLayout.getTabAt(index);
tabLayout.removeOnTabSelectedListener(this);
tab.select();
tabLayout.addOnTabSelectedListener(this);
enjoy:)
Upvotes: 6
Reputation: 36816
Whatever code you're running in onTabSelected
can be moved into a custom method and you can maintain the active tab state within your activity.
onTabSelected(int position, boolean update)
method. Passing false as the second parameter bypasses whatever logic you're looking to avoid running when programmatically selecting your tab.tab.select()
to update the TabLayout
, call onTabSelected(position, false)
to update the active tab field you created in step one but without running your tab selected logic. Then when your TabSelectedListener
fires, it'll short circuit because the activeTabPosition
field will already have been set to the updated position.Here's the skeleton of the new method.
private void onTabSelected(int position, boolean update) {
if (position == activeTabPosition) {
return;
}
activeTabPosition = position;
if (update) {
// Your tab selected logic
}
}
Upvotes: 2