通过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);