binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); BottomNavigationView navView = findViewById(R.id.nav_view); // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder( R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main); NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); NavigationUI.setupWithNavController(binding.navView, navController);
时间: 2024-04-13 19:24:52 浏览: 30
这段代码是在 Android 中使用 Navigation 组件和 BottomNavigationView 的示例。它结合了 View Binding 和 Navigation 组件的使用。
首先,通过使用 View Binding 将布局文件 `activity_main.xml` 转换为一个绑定类 `ActivityMainBinding` 的实例,并将其根视图设置为当前 Activity 的布局。
然后,通过 `findViewById(R.id.nav_view)` 获取了布局文件中的 `BottomNavigationView` 实例,即底部的导航栏。
接下来,使用 `AppBarConfiguration.Builder` 构建了一个 `AppBarConfiguration` 实例 `appBarConfiguration`。这个实例指定了底部导航栏的每个菜单项(即每个标签)作为顶级目的地。
然后,使用 `Navigation.findNavController(this, R.id.nav_host_fragment_activity_main)` 获取了导航控制器 `navController`,并将其与包含导航图的 `nav_host_fragment_activity_main` 关联起来。
然后,使用 `NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)` 将顶部应用栏与导航控制器关联起来,以便在导航过程中更新应用栏的标题和导航按钮。
最后,使用 `NavigationUI.setupWithNavController(binding.navView, navController)` 将底部导航栏与导航控制器关联起来,以便在导航过程中更新选中的标签和处理导航操作。
这段代码的作用是实现底部导航栏与导航图的联动和同步,通过点击底部导航栏的标签切换到对应的目的地,并在顶部应用栏显示当前目的地的标题和导航按钮。
如果您对 View Binding、Navigation 组件或其他内容有更多的疑问,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![go](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)