0

My Android app works perfectly. Fragment with TabLayout starts at first item and works as I need. But now I need to start Fragment with TabLayout from second item. And then I ran into problems.

I found a way to open a second tab (not sure if it's correct) The tabs show the title of the second item as selected. But the content has not changed.

  1. How to switch tabs programmatically?
  2. How to switch and content too?

I am new in Android dev. I cant find solution. Help me please !

Anatolii
  • 23
  • 6
  • 1
    Dear @Anatolii, please consider adding a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your code. – Kozmotronik Jul 24 '23 at 06:31
  • Yes. I completely agree with you. Excuse me please ! But this code has some licensing restrictions. I can't show even one line of code. – Anatolii Jul 24 '23 at 07:12
  • **You don't need to add anything from the original code** you have in your project. Just create minimal **example** code that can reproduce the same problem and that's it. It is well explained in [this page](https://stackoverflow.com/help/minimal-reproducible-example) so take some time to read and understand it, just as we take our time to resolve your specific problem. You need to show your logic because each problem may be specific to the design logic. – Kozmotronik Jul 24 '23 at 10:20

2 Answers2

1

You can select a tab by select() method:

int index = 1;
TabLayout.Tab tab = binding.tabLayout.getTabAt(index);
if (tab != null) tab.select();

and you can do what you need when a tab is selected:

binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int selectedTab = binding.tabLayout.getSelectedTabPosition();
        // do whatever you want
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }
});
Homayoon Ahmadi
  • 1,181
  • 1
  • 12
  • 24
0

If you implemented tabLayout with viewPager you can switch tabs using setCurrentItem (assuming you want to switch to secondTab) :

binding.viewPager.setCurrentItem(1, true)  

and if you implemented without viewpager you can use:

binding.tabLayout.getTabAt(1)?.select()