Based on the fragment APIs , we can add elements to the action bar based on each fragment with the following steps: Create res/menu/fooFragmentMenu.xml , which contains menu items, as usual for the standard menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/newAction" android:orderInCategory="1" android:showAsAction="always" android:title="@string/newActionTitle" android:icon="@drawable/newActionIcon"/> </menu>
At the top of the FooFragment onCreate method, indicate that it has its own menu items that you want to add.
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); ... }
Override onCreateOptionsMenu where you inflate the snippet menu and attach it to your standard menu.
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.fooFragmentMenu, menu); super.onCreateOptionsMenu(menu, inflater); }
Override onOptionItemSelected in your fragment, which is called only when the same host method Activity / FragmentActivity sees that it has no case to choose from.
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.newAction: ... break; } return super.onOptionsItemSelected(item); }
source share