How to start TabLayout with second item ? (In Android, on Fragment, using Kotlin)

97 Views Asked by At

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 !

2

There are 2 best solutions below

0
Homayoon Ahmadi On

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) {
    }
});
0
Usman Mahmood On

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()