0

My question is how can I prevent that my programmatically created toolbar menuItem (Menu with submenus) gets overridden with the xml layout every time the fragment resumes. I want to create my expensive toolbar menuitem only when fragment is first time created and not when it is resumes.

I inflat my toolbar in the onCreateOptionsMenu() and store an instance of the menu item.

private MenuItem menuItem;

private SubMenu expessiveSubmenu;

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_layout, menu);
    menuItem= menu.findItem(R.id.menuItem);
}

The menuItem gets populated when the async loader finishs.

   @Override
    public void onLoadFinished(Loader<> loader, Data data) {
                 //Expensive call
          expensiveSubmenu= makeExpensiveSubMenu(menuItem, data);
}

Now the menu is fully populated and visible in the toolbar and I also have an instance of my submenu.

Because onCreateOptionsMenu() is called evertime the fragment is resumed my menu get's overridden with the xml layout and I have to create the expensive submenu again. A mehtod like menu.addSubmenu(Menu) would solve my needs but I couldn't find one. Any ideas would be appreciated.

shalama
  • 1,133
  • 1
  • 11
  • 25
  • off-topic comment: make `makeExpensiveSubMenu` `makeNotExpensiveSubMenu` or use something other than menu ... could you share why it is so expensive (not the code - just what are you doing there) - maybe someone could help you with this ...because you heve only 2 choices: do not reacreate the whole Activity at all (by blocking configuration changes) or ... make use something else then menu – Selvin Feb 05 '16 at 15:30
  • makeExpensiveSubMenu() makes multiple REST calls to build a tree hierarchy. – shalama Feb 05 '16 at 15:33
  • 1
    then don't do this .... just separate data from UI ... build your tree hierarchy only once as some POJO class ... in onCreateOptionsMenu just create menu from the cached data ... – Selvin Feb 05 '16 at 15:36
  • 1
    fx. it whould be done automatically if you would move build of a tree hierarchy into `loadInBackground` of your abstractloader implementation and changing onLoadFinished to `onLoadFinished(Loader<> loader, MyTreeDataPOJO data) { notSoExpensiveSubmenu = donNotUseRestHereButBuildMenuFromData(data); } ` – Selvin Feb 05 '16 at 15:42
  • I think separating the tree into a pojo is the right way to do it. thx – shalama Feb 05 '16 at 15:44

0 Answers0