Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: OptionMenu between Activity and Fragments

In my app I have one Activity that hosts two Fragments. If I add a MenuItem to the Menu can I retrive it in my fragments? What's the link between OptionMenu in Activity and OptionMenu in his child fragments?

like image 445
TheModularMind Avatar asked Mar 15 '13 02:03

TheModularMind


People also ask

What is difference between activity and fragment in Android?

Activity is an application component that gives a user interface where the user can interact. The fragment is only part of an activity, it basically contributes its UI to that activity. Fragment is dependent on activity. It can't exist independently.

What is the difference between fragment and fragment activity?

Let's dive into the difference Activity is an application component that gives a user interface where the user can interact with your application, whereas fragment is part of your activity embedded into it and has its UI with its elements.

Are fragments better than activities?

Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets).

Are fragments faster than activity?

Each tab will have a fragment to hold the products. The tabs could either held in activity or a fragment. I do find fragments a slightly faster than activities but really its not something you would really notice in most cases. Regardless if they was intended for speed or not they still seem/feel little quicker.


1 Answers

You have to call setHasOptionsMenu(); with the true as the argument passed to it then you can override onCreate options menu.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Enable the option menu for the Fragment
    setHasOptionsMenu(true);
}

If you want to have different optionsMenu for each fragment you will define two different menu xml file and inflate them in the onCreateOptionsMenu

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

    inflater.inflate(R.menu.fragment1_menu, menu);


}
like image 130
Shajeel Afzal Avatar answered Sep 18 '22 18:09

Shajeel Afzal