Search code examples
androidkotlinandroid-tablayout

TabLayout onTabSelected is not called if I select Tab programatically, but UI is changing


I want to implement simple TabLayout with 2 Tabs. But I noticed if I select tab programmatically, it will not trigger onTabSelected, only if I tap on it in UI.

Any suggestions how to trigger it?

tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {
                    lastSelected = tab.position
                    startFragment()
                }

                override fun onTabUnselected(tab: TabLayout.Tab) {}
                override fun onTabReselected(tab: TabLayout.Tab) {}
            })


tabs.getTabAt(0)?.select()

Solution

  • When you call tabs.getTabAt(0)?.select() If your tab already select 0 it means onTabSelected is not called, it will be call onTabReselected. Common mistake when you call tabs.addTab() or using XML to setup TabItem it already select first tab you init. To fix it you should addTab(tab, false) it will be work like you want.