在片段事务期间不调用 OnCreateOptionsMenu

OnCreateOptionsMenu is not called during fragment transaction

我有一个片段,其中包含工具栏中的搜索菜单。当用户第一次点击导航项时,Fragment被添加到activity中,它使用FragmentManageradd方法,然后它将是show,[=16] =] 或 remove 根据逻辑来自片段容器。

我的问题是,当我第一次单击导航项时,搜索菜单显示在工具栏中,但之后当我返回此片段时,有时会出现没有搜索菜单的空白工具栏。我该如何解决这个问题?

片段主要部分代码如下:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_search, container, false);

    searchFragmentInstance = this;
    filterManager = new FilterManager();

    //set toolbar
    Toolbar toolbar = view.findViewById(R.id.toolbar_search);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

    //other code...

    return view;
    }

使用这个在工具栏中显示搜索菜单​​:

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

    super.onPrepareOptionsMenu(menu);
    inflater.inflate(R.menu.search, menu);
    MenuItem item = menu.findItem(R.id.action_search);

    SearchManager searchManager = (SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE);

    SearchView searchView = (SearchView) item.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
    searchView.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));

  //other code...
}

我通过添加以下代码解决了这个问题:

//this method is called when the hidden state of the fragment is changed
//so when fragment is beign displayed using show method of fragment transaction
//this will be called

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);

    if(!hidden){
        //when fragment is not hidden anymore
        //convert the toolbar into actionbar
        Toolbar toolbar=(Toolbar)(((AppCompatActivity)getActivity()).findViewById(R.id.toolbar_search));
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

    }
}