底部导航的实现
- menu的创建
在menu.xml中创建底部导航的项。包括图标和标题:1
2
3
4
5
6
7
8
9
10
11
12
13
14<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/homeFragment"
android:icon="@drawable/icon_home_foreground"
android:title="@string/home" />
<item
android:id="@+id/writeFragment"
android:icon="@drawable/icon_write_foreground"
android:title="@string/write" />
<item
android:id="@+id/myFragment"
android:icon="@drawable/icon_my_foreground"
android:title="@string/my" />
</menu> - 在activity_main中添加BottomNavigationView,并将上述menu设置于BottomNavigationView
1
app:menu="@menu/bottom_nav_menu"
- 创建三个Fragment:HomeFragment、WriteFragment、MyFragment,并创建对应的xml文件
- 创建navigation文件:nav_graph,将上述三个Fragment置于该文件中
- 在activity_main中添加FragmentContainerView用于展示以上三个Fragment
- 实现点击底部导航切换对应Fragment
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_host);
final NavController navController = navHostFragment.getNavController();
AppBarConfiguration configuration = new AppBarConfiguration.Builder(R.id.homeFragment, R.id.writeFragment,R.id.myFragment).build();
NavigationUI.setupActionBarWithNavController(this, navController, configuration);
NavigationUI.setupWithNavController(bottomNavigationView, navController);
bottomNavigationView.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
public void onNavigationItemReselected( MenuItem menuItem){
if (currentId != menuItem.getItemId()){
navController.navigate(menuItem.getItemId());
currentId = menuItem.getItemId();
}
}
}); - 关键之处
menu.xml中对应item的id应与对应Fragment的id一致