Android ViewPager2 + TabLayout + BottomNavigationView 实际案例
本篇主要介绍一下 ViewPager2 + TabLayout + BottomNavigationView 的结合操作
概述
相信大家都看过今日头条的的样式 如下: 顶部有这种tab 并且是可以滑动的, 这就是本篇所介绍的 ViewPager2 + TabLayout 的组合 下面来看看如何实现把
实现思路
1.Activity 布局文件中引入BottomNavigationView 和 FragmentContainerView控件
2.编写 TabLayoutHomeFragment 布局文件
3.编写 Fragment 用于集成ViewPager2 和TabLayout
4. 编写 RecFragment 用于继承RecycleView 展示
5.实现 ViewPager2TabLayoutActivity
代码实现
1.Activity 布局文件中引入BottomNavigationView 和 FragmentContainerView控件
其中 menu 使用上一篇中的指定的 menu
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPager2TabLayoutActivity">
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container_view"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/bootomnav3"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bootomnav3"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="@menu/bottom_item_menu"
app:labelVisibilityMode="labeled"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
2.编写 TabLayoutHomeFragment 布局文件
主要想在这个 Home首页 Fragment 中 实现TabLayout 和 ViewPager2滑动功能
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".tablayout.TabLayoutHomeFragment">
<com.google.android.material.tabs.TabLayout
android:id="@+id/mytablayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="auto"
app:tabGravity="start"
app:tabBackground="@color/pink"
app:tabTextColor="@color/white"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/myviepage2"
/>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/myviepage2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/mytablayout2"
app:layout_constraintBottom_to