Search code examples
androidandroid-fragmentslayout-inflateroncreateoptionsmenu

onCreateOptionsMenu inside Fragments


I have placed setHasOptionsMenu(true) inside onCreateView, but I still can't call onCreateOptionsMenu inside fragments.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
                         Bundle savedInstanceState) {   
   setHasOptionsMenu(true);             
   return inflater.inflate(R.layout.facesheet, container, false);
}

Below is my onCreateOptionsMenu code.

@Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
    getSupportMenuInflater().inflate(R.menu.layout, menu);
    return (super.onCreateOptionsMenu(menu));
}

The error message I get:

The method onCreateOptionsMenu(Menu) of type Fragment must override or implement a supertype method.


Solution

  • try this,

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_sample, menu);
        super.onCreateOptionsMenu(menu,inflater);
    }
    

    Finally, in onCreateView method, add this line to make the options appear in your Toolbar

    setHasOptionsMenu(true);