Reputation: 2914
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
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