android - 如果我使用导航组件在每个片段中设置工具栏,如何删除顶级片段工具栏中的后退按钮?
问题描述
我试过读这个,但我的问题有点不同。
我需要一些不同的工具栏,因此根据此处的文档,我需要在我的每个片段中设置工具栏,而不是在我的 MainActivity 中。
所以我在片段的每个 xml 中设置了工具栏。然后在每个片段中我使用这段代码来设置工具栏
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val toolbar = view.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar3)
val navHostFragment = NavHostFragment.findNavController(this);
NavigationUI.setupWithNavController(toolbar, navHostFragment)
}
但我在底部导航视图的顶级片段中有返回按钮,如下图所示。如果我从我的片段而不是我的 MainActivity 设置工具栏,我很困惑如何传递 appBarConfiguration
解决方案
我终于得到了答案。我需要appBarConfiguration
在每个顶级片段中设置
所以在 myHomeFragment
和 in 中SearchFragment
,你应该这样
val toolbar = view.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar2)
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.destination_home,
R.id.destination_search)
)
val navHostFragment = NavHostFragment.findNavController(this);
NavigationUI.setupWithNavController(toolbar, navHostFragment,appBarConfiguration)
要使用AppBarConfiguration
class ,您需要navigation-ui-ktx
artifact 并且在您使用的 gradle 应用程序中传递此编译选项和 kotlin 选项
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
推荐阅读
- azure - Azure 应用程序网关 SSL 设置
- python - 当命令 discord.py 的参数不正确时,如何显示消息?
- laravel - 如何在 whereHas laravel 中使用 groupBy
- sql - 我上次上传的数据,时间戳关闭了 2 天,我该如何解决?
- sql - 使用相同计划执行查询的巨大差异
- html - Web 应用程序的 RESTful API 重定向,更改基本 URL
- jquery - 如何在 React js 中使用 jquery
- angular - 尝试将属性用于 [(value)] 时出错
- android - Android Biometrics - 选择哪种方法(回退到密码)?
- c++ - C++意外调用继承类的函数