Kevin
Kevin

Reputation: 23634

Menu inside fragment not getting called

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.d("Does", "get called");
    inflater.inflate(R.menu.menuitem, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Below is my onCreateView method, where i am calling

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

I don't get the log statements or the menu getting called in my action-bar.

Update: I tried calling this from onCreate method of fragment, yet the menu is not shown.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);        
}

Menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/section" android:title="@string/section"
        android:icon="@drawable/ic_section"
        android:showAsAction="always" />

    <item android:id="@+id/refresh" android:title="@string/refresh" 
        android:icon="@drawable/ic_refresh"
        android:showAsAction="always" />

    <item android:id="@+id/edit_patient" android:title="@string/edit_patient" 
        android:icon="@drawable/ic_editpatient"
        android:showAsAction="always" />    

    <item android:id="@+id/about" android:title="@string/about"
        android:showAsAction="never" />

    <item android:id="@+id/help" android:title="@string/help"
        android:showAsAction="never" />

    <item android:id="@+id/signout" android:title="@string/signout"
        android:showAsAction="never" />

</menu>

Upvotes: 1

Views: 1448

Answers (1)

Ben Weiss
Ben Weiss

Reputation: 17970

You'll need to make a call of setHasOptionsMenu(true); from within one of the starting lifecycle methods of the Fragment. Preferably from within onCreate(...).

In a minimalistic case the onCreate method of your Fragment looks like this:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setHasOptionsMenu(true);
}

Also, calling super.onCreateOptionsMenu(menu, inflater); after you have inflated your custom menu will reset the menu you just have inflated to an empty menu.

So either call:

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.d("Does", "get called");
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menuitem, menu);
}

or:

@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    Log.d("Does", "get called");
    //no super call
    inflater.inflate(R.menu.menuitem, menu);
}

Also, if you're testing on a Gingerbread device, the menu might not be displayed if the hosting Activity does not contain a menu item of it's own.

Upvotes: 5

Related Questions