【问题标题】:Use default back button behavior with android navigation component使用带有 android 导航组件的默认后退按钮行为
【发布时间】:2020-08-06 08:43:06
【问题描述】:

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

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)
})

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

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

【问题讨论】:

    标签: android android-fragments kotlin-android-extensions


    【解决方案1】:

    在你的MainActivity中,重写onSupportNavigateUp()方法来调用导航控制器中的navigateUp()

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

    【讨论】:

    • 通过该更改,我得到了后退按钮和操作栏按钮的相同行为,它只是刷新当前片段。
    • 在onSupportNavigateUp中返回findNavController(R.id.nav_host_fragment).navigateUp(appBarConfiguration)?
    • navigateUp 不接受参数,所以这不起作用...
    • 您是否在build.gradle 中添加了navigation-ui-ktx?它是NavController 的扩展函数,以AppBarConfiguration 为参数
    • 或者你可以使用return NavigationUI.navigateUp(navController, appBarConfiguration)
    猜你喜欢
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多