简体   繁体   中英

onCreateOptionsMenu is not called after a fragment add & remove

I have a fragment where I can call ActivityCompat.invalidateOptionsMenu(getActivity()); and the method onCreateOptionsMenu() is successfully called on both: Activity and Fragment.

However, when I add a fragment on top of the fragment with:

transaction.add(R.id.fragment_home, fragment2, "fragment_ID");
transaction.addToBackStack(null);
transaction.commit();

and later close it (either by backPress or by getSupportFragmentManager().popBackStack(); ), ActivityCompat.invalidateOptionsMenu(getActivity()); becomes unresponsive. onCreateOptionsMenu() is not called at all.

I know for sure, that it will work if I use replace() instead of add() , however, for some reasons, I need to use add() .

on Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
    if (fragment != null)
        fragment.onCreateOptionsMenu(menu, getMenuInflater());
    return true;
}

on Fragment 1:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.d(TAG, "onCreateOptionsMenu() called with: ...");
    // additional code
    super.onCreateOptionsMenu(menu, inflater);
}

Please try below code :

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_home);
    if (fragment != null) {
        fragment.onCreateOptionsMenu(menu, getMenuInflater());
        return true;
    }
    getMenuInflater().inflate(R.menu.menu_layout, menu);
    return super.onCreateOptionsMenu(menu);
}

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