从同一活动中特定片段的工具栏中隐藏菜单

Hiding menu from toolbar on a specific fragment within the same activity

提问人:Carlos 提问时间:11/15/2023 最后编辑:Carlos 更新时间:11/15/2023 访问量:32

问:

我有一个托管很少片段的活动。

一旦第一个片段进入活动,它就会在活动的 AppBar 布局上膨胀一些菜单(实际上只是一个操作按钮):

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)
    inflater.inflate(R.menu.menu_info, menu)
}

将用户导航到同一活动中的第二个片段后,应隐藏此操作按钮。我无法做到这一点(请参阅下面的解决方案)。

所以,一般来说,问题是:

如何仅针对backstack中的某些片段从活动AppBarLayout中隐藏菜单?

注意:我不需要隐藏整个工具栏(标题仍然应该显示,我只想隐藏操作按钮!

我尝试了不同的解决方案,不幸的是不起作用:

  1. 在第二个片段中调用 setHasOptionsMenu(false)(在 onCreate 和 onCreateView 中都尝试过)
  2. 在片段的不同回调中调用 activity.invalidateOptionsMenu(),然后尝试隐藏 onCreateOptionsMenu 中应该在无效调用后再次调用的菜单元素。但是我看到即使在无效调用之后也没有调用它:
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    menu.forEach {
        it.isVisible = false
    }
}

还尝试将所有这些解决方案组合在一起,但它不起作用 - 按钮仍然显示在第二个片段上。

android-fragments android-fragmentactivity

评论


答:

0赞 ltp 11/15/2023 #1

onCreateOptionsMenu 已弃用。应改用 MenuProvider API。

在第一个片段或要显示特定菜单的片段上:

 private val menuProvider = object : MenuProvider {
            override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
                menuInflater.inflate(R.menu.menu_info, menu)
            }
    
            override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
                return when (menuItem.itemId) {
                    R.id.menu_info_menu1 -> {
                        //Do something
                        return true
                    }
                    R.id.menu_info_menu2 -> {
                        //Do something
                        return true
                    }
                    else -> false
                }
            }
        }

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //show the menu
        requireActivity().addMenuProvider(menuProvider, this)

       //alternatively, you can also specify the specific lifecycle state 
       //when the the menu should show and hide like the following. 
        requireActivity().addMenuProvider(menuProvider, this, Lifecycle.State.RESUMED)
       //This will hide the menu when the fragment lifecycle state is below RESUMED. 
       //If not specified, it will be hidden when fragment is destroyed.

         
           ...
     
    }