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.
- Add a field for the currently active tab position
- Create an
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.
- Before calling
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
}
}