英文:
Android MenuProvider not working inside Fragment
问题
根据用户所查看的片段,我需要添加一个菜单。
我尝试在我的片段的onViewCreated
方法中使用新的MenuProvider
:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val menuHost: MenuHost = requireActivity()
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu_main, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
}
}
这对我的主活动中的工具栏没有任何影响。我需要在某个地方启用菜单吗?
编辑1
根据我在类似问题的答案中看到的,将以下代码放入我的MainActivity中并没有起作用:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
return true
}
编辑2
将我的菜单项移动到一个组中也没有解决问题。
编辑3
我在menuInflater.inflate()
处设置了断点,但它没有被触发,这告诉我活动不关心菜单提供程序。
英文:
I need to add a menu depending on the fragment the user is looking at.
I tried to use the new MenuProvider
in the onViewCreated
-Method of my Fragment:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val menuHost: MenuHost = requireActivity()
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.menu_main, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
return true
}
}
}
This doesn't do anything with my Toolbar in the Main-activity. Do I have to enable menus somewhere?
Edit 1
As I saw in an answer to a similar problem, putting this into my MainActivity didn't do the trick:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
return true
}
Edit 2
Moving my menu item into a group didn't fix it either.
Edit 3
I put a breakpoint at menuInflater.inflate()
but it wasn't activated, which tells me, the activity does not care about the menu provider.
答案1
得分: 0
在我的MainActivity的onCreate
方法中,我错过了一个setSupportActionBar(findViewById(R.id.toolbar))
。
英文:
I missed a setSupportActionBar(findViewById(R.id.toolbar))
in the onCreate
of my MainActivity
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论