onCreateOptionsMenu不会在popbackstack之后调用

时间:2015-05-23 16:42:18

标签: android android-fragments back

我通过单击菜单点击片段2替换一个片段1:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    if (savedItemsExist()) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_call_to_delete_filter) {
            SavedFiltersDeleteFragment newFragment = new SavedFiltersDeleteFragment();
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.flContent, newFragment);
            transaction.addToBackStack(null);
            transaction.commit();
            return true;
        }
    }

    return super.onOptionsItemSelected(item);
}

在片段2中我想通过以下方式返回到之前的片段:

 getActivity().getSupportFragmentManager().popBackStack();

但是当我出现在片段1时,我看到片段2中的菜单。

因此在{1}}中没有调用onCreateOptionsMenu。我在onStart()方法中更新了片段1的UI,那么如何更新菜单呢?

  @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        if (savedItemsExist())
            inflater.inflate(R.menu.menu_saved_filters, menu);

    }

我也在片段1的invalidateOptionsMenu()方法中调用onStart()

 this.setHasOptionsMenu(true); also added in `onCreate()` of the Fragment 1.

1 个答案:

答案 0 :(得分:-2)

所以我通过替换并提交新Fragment代替popBackStack

解决了这个问题