如何在片段中使用viewpager和tablayout?

时间:2019-03-30 08:46:07

标签: android android-viewpager fragment

我需要我的应用具有底部导航栏和可滑动标签。因此,我需要用viewpager在底部导航所使用的每个片段内嵌套的片段之间进行交换。我该怎么办?

1 个答案:

答案 0 :(得分:1)

首先,创建一个包含这样的ViewPager和TabLayout的片段

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".FragmentThatHasViewPagerAndTabLayout">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

然后创建一个包含FrameLayout(将用作片段容器)和BottomNavigation的Activity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@color/colorPrimary"
        app:itemIconTint="#FFF"
        app:itemTextColor="#FFF"
        app:menu="@menu/menu_bottom_navigation"/>

</LinearLayout>

活动的代码段

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                  //Change fragment when select another item in BottomNavigation
            }
        }
        getFragmentManager().beginTransaction().replace(R.id.fragment_container, new FragmentThatHasViewPagerAndTabLayout(), "TAG_TO_REUSE_FRAGMENT_AFTER_CONFIG_CHANGES").commit();
}

还有包含ViewPager和TabLayout的Fragment中的代码,您只需像平常一样编写即可(例如拥有FragmentPagerAdapter等)