I have an Android TabLayout
, defined like this.
<com.google.android.material.tabs.TabLayout
android:id="@+id/now_playing_queues_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.tabs.TabItem
android:id="@+id/now_playing_tab_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Now Playing"
android:icon="@color/purple_700"/>
<com.google.android.material.tabs.TabItem
android:id="@+id/queues_tab_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Queues"/>
</com.google.android.material.tabs.TabLayout>
I then add listeners in Java like this:
TabLayout nowPlayingQueuesTabs;
nowPlayingQueuesTabs = findViewById(R.id.now_playing_queues_tabs);
nowPlayingQueuesTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
System.out.println(tab.getText());
if(tab.getText() == "Now Playing") {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.now_playing_tab_item, new NowPlayingFragment());
fragmentTransaction.commit();
}
else if(tab.getText() == "Queues") {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.queues_tab_item, new QueuesFragment());
fragmentTransaction.commit();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// Your code here
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
System.out.println("Reselected.");
}
});
However, I don't see anything when I click on the tabs:
How do I show the appropriate Fragment
when a tab is clicked/pressed? Is this even the right way to do this? By the way, I also need to preserve the state of the Fragment
s so, for example, if there is a switch that the user turns on in one tab, they can switch to the other tab and back again and the switch will stay on.
I looked at this answer, but the code uses a lot of depreciated APIs and I can't make it work for me. Also, I can use a ViewPager
, but can't allow swiping between tabs.