Martin
Martin

Reputation: 2914

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

Upvotes: 2

Views: 1658

Answers (2)

Công Hải
Công Hải

Reputation: 5241

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.

Upvotes: 3

lantian
lantian

Reputation: 176

Well. You can us View.performClick() to make it works.

Upvotes: 0

Related Questions