0

I am using Navigation components to move between fragments. I created a Fragment superclass used by all fragments with the following:

var hideMenu = false

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    menu.clear()
    if (hideMenu) return
    inflater.inflate(R.menu.standard_menu, menu)
    ....

On the main/start fragment logic sets hideMenu to true true so no menu displays. Good so far.

The user can click a number of different buttons to display other fragments that do not override hideMenu. The problem is that right after the 'target' fragment onCreateOptionsMenu is called ( hideMenu = false so the menu is inflated), the main/start onCreateOptionsMenu method is called. And since it has hideMenu = true, the menu is cleared. Bad, bad, app.

I see from other StackOverflow questions the navigation component supposedly replaces not adds fragments to the backstack. Is this not the case for the main/startup fragment? If so, any words of wisdom to get around this problem?

Eric
  • 781
  • 1
  • 10
  • 18
  • Why are you calling `menu.clear()` at all? That's never something you need to do for Fragments. – ianhanniballake Aug 27 '20 at 00:22
  • I am trying the one activity, multiple fragments architecture - along with using Navigation components. The fragments use the same menu, but the fragment may need to remove a menu option if that option is for the fragment currently being shown. I figured the best thing to do was to clear the menu on each fragment and have a small bit of code as needed in some of the fragments to tailor the menu options. I was liking navigation components until I ran into this problem. Now may just strip out navigation components and do it old fashion way. – Eric Aug 27 '20 at 16:08
  • Every time `onCreateOptionsMenu()` is called, the menu is being recreated from scratch - there is nothing to manually remove since there's no previous state that exists. Please remove `menu.clear()` and rewrite your question to show what problem you're having when you do that. – ianhanniballake Aug 27 '20 at 17:39

0 Answers0