How do I implement the onCreateOptionsMenu method in a SherlockFragment?

user2426316 picture user2426316 · Aug 17, 2013 · Viewed 12.3k times · Source

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) {
       // ???
    }
}

Answer

David picture David · Aug 17, 2013

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;