Agung
Agung

Reputation: 13813

why myTabSelectedListener not triggered if the initial tab selection is index 0?

so I want my tab programatically switch based on certain condition, so I have this code on my onResume

override fun onResume() {
        super.onResume()

        // programatically set tab position based on certain condition
        if (someConditionHere == 0) {
          tabLayout.getTabAt(0)?.select()
        } else if (someConditionHere == 1) {
          tabLayout.getTabAt(1)?.select()
        }



    }

and then I have listener to handle when the user select a tab on my tab layout like this

tabLayout.addOnTabSelectedListener(object: TabLayout.OnTabSelectedListener {

        override fun onTabSelected(tab: TabLayout.Tab?) {


            if  (tab?.position == 0) {
                performActionA()
            } else if (tab?.position == 1) {
                performActionB()
            }



        }

        override fun onTabReselected(tab: TabLayout.Tab?) {

        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {

        }


    })

}

when the first time onResume is triggered and someConditionHere == 1 , then onTabSelected will be called to trigger performActionB()

but unfortunately, when someConditionHere == 0 in the beginning, then onTabSelected will NOT be called so performActionA() will NOT be triggered at the first time. I suspect the tab layout default is on index 0 , so when the condition is also in index tab 0, then the addOnTabListener will not be triggered

how to fix this ? I want my performActionA() is get called from the beginning when someConditionHere == 0. if hard code performActionA() in onResume() it will be called twice unfortunately

java/kotlin is okay

Upvotes: 0

Views: 802

Answers (1)

Nizar
Nizar

Reputation: 2254

In the TabLayout.OnTabSelectedListener there is a method called onTabReselected, as mentioned in my comment, its purpose is for a tab that has already been selected and has been selected again.

Therefore, you would want to replace its content with the content of onTabSelected.

So, it would be better if you create a function so you don't have to repeat the code.

fun performNecessaryAction(tab: TabLayout.Tab?) {
    if  (tab?.position == 0) {
        performActionA()
    } else if (tab?.position == 1) {
        performActionB()
    }
}

And the listener would look like the following...

tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabReselected(tab: TabLayout.Tab?) {
        performNecessaryAction(tab)
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        performNecessaryAction(tab)
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }
})

Upvotes: 2

Related Questions