简体   繁体   中英

Android NavigationDrawerFragment: Control whether the child fragment or parent activity's onCreateOptionsMenu gets called, but not both

So like I mentioned in the title, I have a setup with a NavigationDrawerFragment and another fragment in a containing activity.

Ideally I'd like my behavior to be something as follow.

  1. When the drawer is opened, call the containing activities onCreateOptionsMenu but do not call the other fragment's (the current visible fragment's) onCreateOptionsMenu.
  2. When the drawer is closed, calling the visible fragment's onCreateOptionsMenu method but do not call the containing fragment's onCreateOptionsMenu method.

Is there anyway to achieve this using lifecycle callbacks? Or should I look into using an event bus instead.

In your Activity let have this:

@Override
public boolean onCreateOptionsMenu(MenuInflater inflater, Menu menu){
  boolean onlyFragments = !mDrawerLayout.isOpened(GravityCompat.START);
  Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.content_layout);
  visibleFragment.setHasOptionsMenu(onlyFragments);
  if(onlyFragments){
    return super.onCreateOptionsMenu(inflater,menu);
  }else{
     //here only activity inflates menu
     inflater.inflate(R.menu.activity_menu, menu);
     return true;
  }
}

and in onDrawerClosed(View v) and onDrawerOpened(View v) call invalidateOptionsMenu() or it's respective support method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM