繁体   English   中英

使用 android 导航组件的默认返回按钮行为

[英]Use default back button behavior with android navigation component

我在我的应用程序中使用导航图。 我有一个底部导航栏。 我在我的主要活动中盯着我的导航组件:

setContentView(R.layout.activity_main)
val navView: BottomNavigationView = findViewById(R.id.nav_view)

val navController = findNavController(R.id.nav_host_fragment)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(setOf(
        R.id.navigation_artist_list, R.id.navigation_dashboard, R.id.navigation_notifications))
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)

这将启动我的导航组件,它会膨胀R.id.navigation_artist_list中的片段设置。

从该片段中的观察者,我正在导航到另一个片段:

viewModel.selectedAlbum.observe(this, Observer { artist ->
    val action = HomeFragmentDirections.actionNavigationHomeToAlbumFragment(artist)
    root.findNavController().navigate(action)
})

但是,任何可用于导航的机制都不能正常工作。 后退按钮只是刷新片段并再次填充片段中的列表。 操作栏上的后退按钮被完全忽略。

我是否需要做其他事情才能获得正确的后退按钮行为,以 go 回到上一个片段?

问题视频

在您的MainActivity中,覆盖onSupportNavigateUp()方法以调用导航 controller 中的navigateUp()

override fun onSupportNavigateUp(): Boolean {
    val navController = this.findNavController(R.id.nav_host_fragment)
    return navController.navigateUp()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM