navigation实现导航栏的小例子

通过navigation来实现一个简单的导航栏功能

1.导包

implementation 'androidx.navigation:navigation-fragment:2.2.2'
implementation 'androidx.navigation:navigation-ui:2.2.2'

2.创建navigation包以及nav_graph.xml文件(xml文件名字自选)

收到添加fragment即可,你需要几个页面就添加几个fragment

3.建立一个menu包 创建一个xml文件

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="头条" android:id="@+id/nav_news" android:icon="@drawable/ic_home_24"/>
    <item android:title="地区" android:id="@+id/nav_place" android:icon="@drawable/ic_baseline_search_24"/>
    <item android:title="服务" android:id="@+id/nav_service" android:icon="@drawable/ic_service_24"/>
    <item android:title="我的" android:id="@+id/nav_mine" android:icon="@drawable/ic_baseline_person_24"/>
</menu>

注意这里的id要和fragment的id对应一致

4.在主页面xml文件中设置BottomNavigationView和fragment

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/bottomNavView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    app:menu="@menu/buttom_nav_menu"/>
<fragment
    android:id="@+id/nav_frg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:name="androidx.navigation.fragment.NavHostFragment"
    app:navGraph="@navigation/nav_graph"
    android:layout_alignParentTop="true"
    android:layout_above="@id/bottomNavView"/>

5.在主Activity中完成绑定即可

// 1.获取bottomNavigationView
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavView);
//2.设置appbarconfigration
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_graph, R.id.nav_news).build();
//3.获取Navcontroller
NavController navController = Navigation.findNavController(this, R.id.nav_frg);
//4.设置Navcontroller和appbarconfigration的关系
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
//5.设置获取bottomNavigationView和Navcontroller
NavigationUI.setupWithNavController(bottomNavigationView, navController);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值