且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用导航组件处理片段内的向上按钮

更新时间:2022-12-29 08:36:13

最后,我找到了解决方案.

Finally, I found the solution.

首先在activity onCreate方法中,我必须像以前那样连接导航:

First In the activity onCreate method I had to connect the navigation like I did:

val navController = this.findNavController(R.id.host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)

然后仍然在MainActivity中覆盖onSupportNavigateUp():

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

然后在Fragment onCreateView中,我必须启用选项菜单:

Then In the Fragment onCreateView I had to enable option menu:

setHasOptionsMenu(true)

然后在fragment中我覆盖了onOptionsItemSelected:

override fun onOptionsItemSelected(item: MenuItem): Boolean
{
    // handle the up button here
    return NavigationUI.onNavDestinationSelected(item!!,
        view!!.findNavController())
            || super.onOptionsItemSelected(item)
}

注意:我想如果您有多个选项菜单,那么我认为您必须执行when (item)语句来检查已选择了哪个选项.

Note: I think if you have more than one option menu, then I think you have to do a when (item) statement to check what option has been chosen.

此外,如果您想操作设备后退按钮,则可以在fragment onCreateViewMethod中这样做:

Also if you want to handle the device back button then you can do like this in your fragment onCreateViewMethod :

requireActivity().onBackPressedDispatcher.addCallback(this)
    {
        // handle back button

// change this line to whatever way you chose to navigate back          
findNavController().navigate(NoteEditFragmentDirections.actionNoteEditFragmentToNoteListFragment())
        }