In the menu.xml
you should add all the menu items. Then you can hide items that you don't want to see in the initial loading.
<item
android:id="@+id/action_newItem"
android:icon="@drawable/action_newItem"
android:showAsAction="never"
android:visible="false"
android:title="@string/action_newItem"/>
Add setHasOptionsMenu(true)
in the onCreate() method to invoke the menu items in your Fragment class.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
You don't need to override onCreateOptionsMenu
in your Fragment class again. Menu items can be changed (Add/remoev) by overriding onPrepareOptionsMenu
method available in Fragment.
@Override
public void onPrepareOptionsMenu(Menu menu) {
menu.findItem(R.id.action_newItem).setVisible(true);
super.onPrepareOptionsMenu(menu);
}