Select Page

This tutorial shows you how to add action items to the ActionBar from within your Fragments. In my previous post, you have seen that every tab in the viewpager connected with the fragment.

The action bar menu items will change based on the tab selection. This menu contains some of the common menu items and the tab specific menu items.The below image illustrates this better than words.

Fragment specific menu

Why do you need to add action items from Fragments?

In the above image shows that the menu contains common items like SearchSettings, and Status and the fragment specific options like call, chat, contacts icons. So you need to add the common menu items in the parent activity menu and fragment specific menu items from within your fragments.

How to add action items from Fragments?

Create the menu files, as usual, then you need to specify that the fragment contains menu using the below snippet.

public void onCreate(@Nullable Bundle savedInstanceState) {

Now you need to inflate the menu for this fragment using OnCreateOptionsMenu, just override this native method into your fragment and initialize the menu.

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(, menu);
    super.onCreateOptionsMenu(menu, inflater);

How to handle clicks event ?

As usual, override OnOptionsItemSelected method for handling click events of the menu items. OnOptionsItemSelected is called whenever an item in your options menu is selected.

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
            Toast.makeText(getActivity(), "Calls Icon Click", Toast.LENGTH_SHORT).show();
            return true;
            Toast.makeText(getActivity(), "Clear call log", Toast.LENGTH_SHORT).show();
            return true;
            return super.onOptionsItemSelected(item);

How to change the order of the items ?

Now most of the peoples have the same doubt, We are using the global menu from the activity so OnCreateOptionsMenu in the parent activity executes first then only the child fragment, then how to change the order of the items.

It’s so simple Android provides the attribute called orderInCategory. You can re-order the menu items using this attribute by specifying the integer values. The menu items are arranged from left to right in ascending order based on the given integer value.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""
    <item android:id="@+id/action_search"
    <item android:id="@+id/action_status"
    <item android:id="@+id/action_settings"

I made a simple sample app using this concept, it’s over on GitHub if you want to check it out.

View on GithubDownload .zip

Feel free to comment and share, keep watching this space get more updates on Android Stuff!


Jaison Fernando

Android Developer at NFN Labs