Select a Tab without invoking OnTabSelectedListener
Asked Answered
A

2

5

I am trying to use TabLayout in my Activity. Each Tab takes user to a fragment.

  1. Suppose user is on Tab1 which has fragment1.
  2. He clicks Tab2 which has fragment2.
  3. Now when user is on Tab2 and presses back button I want user to go back to Fragment1 on Tab1. I do this by doing 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?

Archimage answered 19/5, 2016 at 23:50 Comment(0)
A
6

just do this:

TabLayout.Tab tab = tabLayout.getTabAt(index);

tabLayout.removeOnTabSelectedListener(this);
tab.select();
tabLayout.addOnTabSelectedListener(this);

enjoy:)

Amann answered 11/1, 2019 at 19:59 Comment(0)
T
2

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.

  1. Add a field for the currently active tab position
  2. 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.
  3. 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
        }
    }
Tessy answered 20/5, 2016 at 0:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.