带有bottomNavigationView的后退键

问题描述 投票:0回答:2

在我的应用程序中,我将bottomNavigationView与jetpack导航一起使用看图片enter image description here

我有2页当我单击到第二页,然后单击返回时,我返回到第一个片段,但我想关闭应用程序一些代码

private fun initView() {
    setSupportActionBar(toolbar)
    bottomNavigationView = findViewById(R.id.bottom_navigation)
    val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.nav_host_fragment) as NavHostFragment
    navController = navHostFragment.navController

    navController?.apply {
        appBarConfiguration = AppBarConfiguration(setOf(
            R.id.action_home,
            R.id.action_favorite
        ))
        appBarConfiguration?.let {
            setupActionBarWithNavController(this, it)
        }
        bottomNavigationView?.let {
            NavigationUI.setupWithNavController(it, this)
        }
    }
}
android bottomnavigationview
2个回答
1
投票

一种方法是,如果要通过后退按钮自定义行为,则需要在活动中覆盖onBackPressed()


0
投票
override fun onBackPressed() {
    if (R.id.action_favorite == navController?.currentDestination?.id) {
        finish()
    } else {
        super.onBackPressed()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.