Search code examples
androidactionbarsherlockandroid-optionsmenu

How do I implement the onCreateOptionsMenu method in a SherlockFragment?


I am really struggling to set up the onCreateOptionsMenu method in my Sherlock Fragment, as I usually don't use Sherlock fragments that much. Can someone tell what I have to import and how the implementation works?

Some code that I have:

public class MyFragment extends SherlockFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {        

        View rootView = inflater.inflate(R.layout.custom_list, container, false);

        // SOME CODE ...

        return rootView;
    }   

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       // ???
    }
}

Solution

  • The onCreateOptionsMenu() function of SherlockFragment is exactly like the Fragment one.

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

    Also you have to add the following to your onCreate() function

    setHasOptionsMenu(true);
    

    The imports are:

    import com.actionbarsherlock.view.Menu;
    import com.actionbarsherlock.view.MenuInflater;