TabItem id not showing up in TabLayout.Tab

482 Views Asked by At

I've defined my tabs in xml like this:

<TabLayout
    android:id="@+id/tabs"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TabItem
        android:id="@+id/firstTab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/heading1"/>

But when I query the currently selected tab id like this:

tabs.getTabAt(tabs.selectedTabPosition).id

I get -1. I was expecting to get the value of firstTab. When I however query for the text:

tabs.getTabAt(tabs.selectedTabPosition).text

it correctly returns the text from heading1.

I noticed that TabItem does not define an id. Android Studio however does not complain when I slip it an id.

Now I guess I could just fall back to doing a string comparison with the text, that is correctly transfered to TabLayout.Tab. Doesn't seem right to me though. Is there another way to identify the currently selected tab?


EDIT:

What I want to achieve is something like this:

when (tabs.getTabAt(tabs.selectedTabPosition).id) {
    firstTab -> ...
1

There are 1 best solutions below

3
Daniel Knauf On

AndroidStudio does not complain because in the xml you have a TabItem which lets you set text, icon and custom layout (docu). This is then converted into a TabLayout.Tab (docu) which has an id.

You use a TabSelectionListener to store the current selected tab:

 addOnTabSelectedListener(
        object : TabLayout.OnTabSelectedListener {

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

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

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

As you know the sequence of your tabs you could use a when statement with selectedTabPosition to handle your use case:

const val HEADLINE_POSITION = 0 // or just number in when statement

when(selectedTabPosition){
    HEADLINE_POSITION -> // do logic for first tab
    -1 -> // do logic if nothing is selected 
    else -> // default
}