Android MenuProvider在Fragment内部不起作用

huangapple go评论75阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年8月9日 04:02:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定