Android Fragment Menu Example

Fragment can has it’s own menu, the fragment menu items are also displayed in android application action bar. This article will show you how to add menu items in android fragment and how to use fragment menu items with activity menu items.

1. How To Add Menu Items For Android Fragment.

  1. Create a fragment menu items layout xml file. You can read article Android Actionbar Example for more detail.
  2. Override Fragment class onCreate(@Nullable Bundle savedInstanceState) method, set hasOptionsMenu to true.
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
  3. Override Fragment class onCreateOptionsMenu(Menu menu, MenuInflater inflater) method, inflate the fragment menu layout xml file in this method as below.
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_menu_items, menu);
    }

2. How To Handle Fragment Menu Item Click Event.

  1. You can override Fragment class’s onOptionsItemSelected(MenuItem item) method to handle Fragment menu item click event like below.
  2. Activity also have onOptionsItemSelected(MenuItem item) method. When you click a menu item, no matter where the menu item exist ( fragment or activity), activity and fragment will all trigger this method.
  3. So you need to add code in this method to check which menu item is clicked.
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
    
        String message = "You click fragment ";
    
        if(itemId == R.id.fragment_menu_search)
        {
            message += "Search menu";
        }else if(itemId == R.id.fragment_menu_news)
        {
            message += "News menu";
        }else if(itemId == R.id.fragment_menu_tech)
        {
            message += "Tech menu";
        }
    
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
        alertDialog.setMessage(message);
        alertDialog.show();
    
        return super.onOptionsItemSelected(item);
    }

3. How To Make Fragment Menu Items Order First In Action Bar.

  1. If both your activity and fragments all has their own menu items. All the menu items will be displayed in the action bar.
  2. But when you open a fragment in activity, of course you want fragment menu items order first than activity menu items, this can make it user friendly.
  3. To implement this, you need to set android:orderInCategory attribute value for each menu items in all the menu layout xml file.
  4. The menu item with small value will order first in the action bar.
  5. But when you hide or detach the fragment, the fragment menu items will disappear from the action bar also.

4. Android Fragment Menu Items Example.

  1. In this example there is a fragment and a activity. Each has their own menu items.
  2. When the activity start, you can see the activity menu items.
  3. When you click the show button to open a fragment, you can see the fragment menu items ordered before activity menu items. This is because of the menu item’s android:orderInCategory attribute value.
  4. When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also.
  5. You can also click back menu to exit the fragment and the activity. Because we have add the fragment in the back stack.

5. Example Source Code.

5.1 Main Layout XML File.

  1. Below is the main activity layout XML file activity_fragment_menu.xml‘s content.
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <Button
            android:id="@+id/show_menu_fragment_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show Menu Fragment"
            android:textSize="20dp" />
    
        <FrameLayout
            android:id="@+id/fragment_menu_frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </LinearLayout>

5.2 Fragment Layout XML File.

  1. Below is the fragment layout XML file fragment_menu.xml‘s content.
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="Fragment menu example."
            android:textSize="20dp"
            android:gravity="center"
            android:textColor="@android:color/holo_red_light"/>
    
    </LinearLayout>

5.3 Activity Menu Items XML File.

  1. The activity menu items XML file is fragment_menu_activity_menu_items.xml.
  2. It is saved in app/res/menu folder.
  3. Below is the file source code.
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/fragment_activity_menu_movie"
            android:icon="@drawable/icon_movie_32"
            android:title="Movie"
            android:orderInCategory="4"
            app:showAsAction="ifRoom|withText" />
    
        <item
            android:id="@+id/fragment_activity_menu_music"
            android:icon="@drawable/icon_music_32"
            android:title="Music"
            android:orderInCategory="5"
            app:showAsAction="ifRoom|withText" />
    
        <item
            android:id="@+id/fragment_activity_menu_sports"
            android:icon="@drawable/icon_sports_32"
            android:title="Sports"
            android:orderInCategory="6"
            app:showAsAction="ifRoom|withText" />
    
    </menu>

5.4 Fragment Menu Items XML File.

  1. The fragment menu items XML file is fragment_menu_items.xml.
  2. It is saved in app/res/menu folder.
  3. Below is the XML file source code.
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/fragment_menu_search"
            android:icon="@drawable/icon_search_32"
            android:title="Search"
            android:orderInCategory="1"
            app:showAsAction="ifRoom|withText" />
    
        <item
            android:id="@+id/fragment_menu_news"
            android:icon="@drawable/icon_news_32"
            android:title="News"
            android:orderInCategory="2"
            app:showAsAction="ifRoom|withText" />
    
        <item
            android:id="@+id/fragment_menu_tech"
            android:icon="@drawable/icon_tech_32"
            android:title="Tech"
            android:orderInCategory="3"
            app:showAsAction="ifRoom|withText" />
    
    </menu>

5.5 Activity Java Class File.

  1. FragmentMenuActivity.java.
    package com.dev2qa.example.fragment.menu;
    
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    
    import com.dev2qa.example.R;
    
    import java.util.List;
    
    public class FragmentMenuActivity extends AppCompatActivity {
    
        // Button text static constant variable.
        private final static String BUTTON_TEXT_SHOW_MENU_FRAGMENT = "Show Menu Fragment";
    
        private final static String BUTTON_TEXT_HIDE_MENU_FRAGMENT = "Hide Menu Fragment";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fragment_menu);
    
            setTitle("dev2qa.com - Fragment Menu Example.");
    
            // Get the button.
            final Button showMenuFragmentButton = (Button)findViewById(R.id.show_menu_fragment_button);
            showMenuFragmentButton.setOnClickListener(new View.OnClickListener() {
                // When the button is clicked.
                @Override
                public void onClick(View view) {
    
                    // Get button text.
                    String buttonText = showMenuFragmentButton.getText().toString();
    
                    // Get fragment manager and transaction object.
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
                    // If button text is show fragment.
                    if(BUTTON_TEXT_SHOW_MENU_FRAGMENT.equals(buttonText)) {
                        // Create a new fragment.
                        FragmentMenu fragmentMenu = new FragmentMenu();
    
                        // Add the fragment in activity.
                        fragmentTransaction.add(R.id.fragment_menu_frame_layout, fragmentMenu, "Fragment Menu");
    
                        // Add the fragment in back stack.
                        fragmentTransaction.addToBackStack(null);
    
                        // Commit.
                        fragmentTransaction.commit();
    
                        // Change the button text.
                        showMenuFragmentButton.setText(BUTTON_TEXT_HIDE_MENU_FRAGMENT);
                    }
                    // If button text is hide fragment.
                    else if(BUTTON_TEXT_HIDE_MENU_FRAGMENT.equals(buttonText))
                    {
                        // Get all fragment list.
                        List<Fragment> fragmentList = fragmentManager.getFragments();
                        if(fragmentList!=null)
                        {
                            // Loop the list.
                            int size = fragmentList.size();
                            for(int i=0;i<size;i++)
                            {
                                Fragment fragment = fragmentList.get(i);
                                // If correct fragment.
                                if(fragment!=null && fragment instanceof FragmentMenu)
                                {
                                    // Hide the fragment.
                                    fragmentTransaction.hide(fragment);
    
                                    // Do not forget commit at last.
                                    fragmentTransaction.commit();
                                    break;
                                }
                            }
                        }
    
                        // Change the button text.
                        showMenuFragmentButton.setText(BUTTON_TEXT_SHOW_MENU_FRAGMENT);
                    }
                }
            });
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate activity menu items.
            getMenuInflater().inflate(R.menu.fragment_menu_activity_menu_items, menu);
            return super.onCreateOptionsMenu(menu);
        }
    
        // Invoked when activity menu item is clicked.
        // It also will be invoked when use click fragment menu item.
        // So you need to write code to check which menu item trigger this click event.
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int itemId = item.getItemId();
    
            boolean showMessage = false;
    
            String message = "You click activity ";
    
            if(itemId == R.id.fragment_activity_menu_movie)
            {
                showMessage = true;
                message += "Movie menu";
            }else if(itemId == R.id.fragment_activity_menu_music)
            {
                showMessage = true;
                message += "Music menu";
            }else if(itemId == R.id.fragment_activity_menu_sports)
            {
                showMessage = true;
                message += "Sports menu";
            }
    
            if(showMessage) {
                AlertDialog alertDialog = new AlertDialog.Builder(FragmentMenuActivity.this).create();
                alertDialog.setMessage(message);
                alertDialog.show();
            }
    
            return super.onOptionsItemSelected(item);
        }
    }

5.6 Fragment Java Class File.

  1. FragmentMenu.java.
    package com.dev2qa.example.fragment.menu;
    
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v7.app.AlertDialog;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.dev2qa.example.R;
    
    public class FragmentMenu extends Fragment {
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // Confirm this fragment has menu items.
            setHasOptionsMenu(true);
        }
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View retView = inflater.inflate(R.layout.fragment_menu, container, false);
            return retView;
        }
    
        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // Inflate the fragment menu items.
            inflater.inflate(R.menu.fragment_menu_items, menu);
        }
    
        // This method will be invoked when user click the fragment menu item.
        // It also will be invoked when use click activity menu item.
        // So you need to write code to check which menu item trigger this click event.
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int itemId = item.getItemId();
    
            boolean showMessage = false;
    
            String message = "You click fragment ";
    
            if(itemId == R.id.fragment_menu_search)
            {
                showMessage = true;
                message += "Search menu";
            }else if(itemId == R.id.fragment_menu_news)
            {
                showMessage = true;
                message += "News menu";
            }else if(itemId == R.id.fragment_menu_tech)
            {
                showMessage = true;
                message += "Tech menu";
            }
    
            if(showMessage) {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setMessage(message);
                alertDialog.show();
            }
    
            return super.onOptionsItemSelected(item);
        }
    }

6. Example Demo Video.

  1. Below is the example demo video.

1 thought on “Android Fragment Menu Example”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.