Android如何将TabLayout定位到屏幕底部(适用于谷歌的材料设计库TabLayout)

6
我正在尝试使用TabLayout和ViewPager创建三个可滑动的片段。然而,我遇到了一个问题:我希望TabLayout位于屏幕底部,但ViewPager强制它位于顶部
TabLayout曾经在android.support.design.widget库中使用。然而,自androidx引入后,此库已被更改。新库为com.google.android.material.tabs.TabLayout。
以前(过时的)帖子(example1example2)建议通过创建垂直LinearLayout并将ViewPager和TabLayout指定为该LinearLayout的两个单独元素来解决上述问题。
由于现在必须将TabLayout指定为ViewPager内的元素(reference),因此上述解决方案已不再可行。
<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>

然后,要将ViewPagerTabLayout“合并”,必须在TabLayout实例上调用setupWithViewPager(ViewPager vp)方法:
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);

现在,我该如何使TabLayout整齐地从XML代码或编程方式移动到ViewPager的底部?

可能是重复的问题:如何将Android TabLayout设置在屏幕底部? - denvercoder9
2个回答

6
我找到了答案: 只需在xml中的TabLayout上添加android:layout_gravity="bottom"即可。因此,现在的xml实现看起来像这样:
<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"
            android:layout_gravity="bottom"
            >
        </com.google.android.material.tabs.TabLayout>
    </androidx.viewpager.widget.ViewPager>

非常出色的工作,谢谢你,这应该是答案。 - Wowo Ot

2

根据您的参考 - 要在ViewPager中包含TabLayout,请在ViewPager元素内添加TabLayout元素。

但这并不意味着您不能在ViewPager之外使用TabLayout。 因此,您可以使用先前帖子中的任何答案, 或者您可以尝试像这样:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
<androidx.viewpager.widget.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tab_layout"/>

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_height="48dp"/></RelativeLayout>

找到了更简单的解决方案…请查看我的答案:D - AnimaVivens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接