I am trying to use a TabLayout joined with a ViewPager to create three swipeable fragments. However, I ran against a problem: I want the TabLayout to be at the bottom of the screen, but the ViewPager is forcing it to be at the top.
TabLayout used to be in the android.support.design.widget library. This library, however, has been changed since androidx was introduced. The new library is com.google.android.material.tabs.TabLayout.
Previous (and outdated) posts (example1, example2) suggest a simple solution to the above problem by simply creating a vertical LinearLayout and specifying the ViewPager and TabLayout as two separate elements of that LinearLayout.
The above solution is no longer viable due to the fact that now, you have to specify the TabLayout to be an element inside of the ViewPager (reference), like this:
<androidx.viewpager.widget.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="48dp"
>
</com.google.android.material.tabs.TabLayout>
</androidx.viewpager.widget.ViewPager>
Then, to "merge" the ViewPager with the TabLayout, the setupWithViewPager(ViewPager vp) method has to be called on the TabLayout instance:
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
MainPagerAdapter mpa = new MainPagerAdapter(getSupportFragmentManager(), 3);
viewPager.setAdapter(mpa);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
Now, how can I neatly make the TabLayout go to the bottom of the ViewPager, either from xml code or programmatically?