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 -> ...
AndroidStudio does not complain because in the xml you have a
TabItemwhich lets you set text, icon and custom layout (docu). This is then converted into aTabLayout.Tab(docu) which has an id.You use a TabSelectionListener to store the current selected tab:
As you know the sequence of your tabs you could use a
whenstatement withselectedTabPositionto handle your use case: