问题描述
我正在制作一个简单的笔记应用程序,我有2个带有导航组件的片段,一个片段具有一个笔记列表,另一个片段用于编辑或创建新笔记.
I am making a simple note taking app, I have 2 fragments with navigation component, one fragment has a list of notes and the other is for editing or creating a new note.
在MainActivity
我添加了
val navController = this.findNavController(R.id.host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)
,然后覆盖onSupportNavigateUp()
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.host_fragment)
return navController.navigateUp()
}
在NoteEditFragment
requireActivity().onBackPressedDispatcher.addCallback(this) {
saveOrUpdateNote(noteId, note)
}
现在在按设备中的后退按钮"时一切正常,但是,当我按屏幕左上方的上按钮"时,会触发onBackPressedDispatcher.addCallback()
音符.
now it all works well when pressing the "back button" in the device, However onBackPressedDispatcher.addCallback()
is note triggered when I press the "up button" the one on the top left of the screen.
我的问题是:如何从NoteEditFragment
处理此向上按钮?
My question is : How do I handle this up button from my NoteEditFragment
?
预先感谢
推荐答案
最后,我找到了解决方案.
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())
}
这篇关于如何使用导航组件处理片段内的向上按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!