Ranjan Srinivas Ranjan Srinivas - 5 months ago 36
Android Question

Adding a menu to an activity than a fragment

I have a

MainActivity
along with a fragment. I have a refresh menu option that will refresh the data (Using
AsyncTask
). Is there any difference in inflating the refresh menu option in the fragment than in the MainActivity?

Note: This is in context with Udacity's Developing Android Apps, Lesson 2.

Answer

Yes, if i understand right, you want to inflate your activity toolbar menu from the the fragment. If that is the case you can do it like this

Yout Fragment class

   @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setHasOptionsMenu is important 
            //it's telling the parent activity that he wants to participate in inflation of the menu
            setHasOptionsMenu(true);
        }



        //Rest of your methods (onCreateView, onPause, onResume etc...)


        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            //inflate the menu file
            inflater.inflate(R.menu.your_menu_xml, menu);
            super.onCreateOptionsMenu(menu, inflater);
        }

        @Override
        public boolean onOptionsItemSelected(android.view.MenuItem item) {

            switch (item.getItemId()) {

                case R.id.refresh:
                    //handle click
                    return true;
            }
            return super.onOptionsItemSelected(item);
        }

You can also use setMenuVisibility(boolean) if you want to hide/show menu in certain childfragments

If you inflate the menu from within the activity, it will be shown in all of the fragments you load inside the activity, but the action will be available to activity only (This is good if you want to do some general stuff with your menu action like starting new activity, displaying information popup etc). If you inflate the menu from within the fragment you will be able to handle menu items from withing the fragment, which will allow you to create more specific menu actions based on which fragment is currently active. For example if you have viewpager with 3 different fragments lets say:

  • FragmentOne for image browsing
  • FragmentTwo for video browsing
  • FragmentThre for Text browsing

Lets say you want to allow users to upload the images only, and you want that upload button to be located in the menu.

If you inflate the the menu from within the activity your upload button will be visible inside all of your fragments, and you would have to create a custom/logic for showing hiding menu items. If you create a menu from within the fragment, you will be able to handle and show the menu for the fragment you need

Long story short i think this depends on the use case of the activity/fragment and what you want to achieve with it