【Android】Fragment实现顶部、底部导航栏

前言

无论是顶部还是底部导航栏,都是大多数APP的标配,网络上的相关实现教程也非常之多。最近回忆起以前写的小项目,发现对这块内容有些遗忘,不妨就再整理一遍代码逻辑,记录下来,方便日后查阅(指复制粘贴)。

▶ 实现的方式有很多,本文采用以下方式实现:

  • 底部导航栏:Fragment + BottomNavigationView
  • 顶部导航栏:Fragment + ViewPager2 + TabLayout

底部导航栏

<布局文件>

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <FrameLayout
        android:id="@+id/main_page_controller"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="50dp"
        android:background="#EFEEEE"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/main_navigation_bar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="#ffffff"
        app:itemIconTint="@color/navigation_bar_color"
        app:itemTextColor="@color/navigation_bar_color"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/navigation_items"/>

</RelativeLayout>

<menu文件>

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/home"
        android:icon="@mipmap/home"
        android:title="首页"/>
    <item
        android:id="@+id/plan"
        android:icon="@mipmap/plan"
        android:title="日程"/>
    <item
        android:id="@+id/game"
        android:icon="@mipmap/game"
        
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值