Fragment+ViewPager+BottomNavigationView实现页面导航

本文介绍了如何结合Fragment、ViewPager和BottomNavigationView实现页面导航。通过设置BottomNavigationView的属性,配置菜单项,创建并初始化Fragment,以及监听ViewPager和BottomNavigationView的事件,实现两者之间的联动,达到无缝切换页面的效果。
摘要由CSDN通过智能技术生成


上篇文章我们学习了 Fragment+ViewPager+BottomTab实现页面导航,实现了左右滑动切换页面。但我们底部导航按钮的实现还比较原始,使用了大量的控件拼凑而成,相对麻烦。本文将对上节案例做进一步的优化,使用BottomNavigationView这个控件快捷的实现导航按钮。

1. 目标效果

效果截图

2. 案例教学

本节内容是在上节案例基础上的优化,因此很多细节不再重复,详情参考上文即可。

2.1 主界面布局

activity_fragment_view_pager_bottom_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bnv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?android:windowBackground"
        app:itemRippleColor="@color/green_700"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/bottom_nav_menu" />

</LinearLayout>

布局结构还是类似的,只不过上文的导航按钮部分<include layout="@layout/bottom_tab_layout" />被替换为了 BottomNavigationView。这个控件是material库里的,如果你引用不到,检查下build.gradle文件的dependencies节点里是否添加了依赖implementation 'com.google.android.material:material:1.4.0'。添加上即可。

我们来具体看下BottomNavigationView里面几个属性配置:

  • app:menu
    声明导航按钮,它的值是一个menu文件。具体如下:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_home"
        android:icon="@drawable/selector_home"
        android:title="首页" />

    <item
        android:id="@+id/menu_find"
        android:icon="@drawable/selector_find"
        android:title="发现" />

    <item
        android:id="@+id/menu_mine"
        android:icon="@drawable/selector_mine"
        android:title="我的" />
</menu>

可见,跟上文我们用控件拼接出的按钮类似,也主要包括icon、文字。

  • app:labelVisibilityMode
    导航按钮的显示模式,取值有auto、selected、labeled、unlabeled

    • labeled :
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子林Android

感谢老板,老板大气!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值