3

I need to create an application that have a shared menu between all activities, but I hesitate between creating the same menu for all activities and make these activities 'singletones', or create multiple fragments and use them in one activity that will have the menu.

I want to make my application compatible with most devices, so I don't know which one is the best (for memory management and reusable stuffs ...)

What should I try ? if is there a better process than these two, feel free to suggest :)

Mehdi
  • 974
  • 1
  • 10
  • 24

2 Answers2

5

One way to do it is to define a parent class activity that all other activities will inherit from. In the parent's class onCreateOptionsMenu you define the menu that is common for all activities:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.common_menu, menu);
    return true;
}
Szymon
  • 42,577
  • 16
  • 96
  • 114
2

I think is much better to use Fragments. You will have a single Activity, with a menu and if a Fragment has a personal menu, you can update the actionBar easily, by adding this methods to your Fragment:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection...
}

EDIT

Remember also to add setHasOptionsMenu() in the onCreate() method of the Fragment. The Android framework calls in this case the onCreateOptionsMenu() method in the Fragment class and adds its menu items to the ones added by the Activity (refer this link).

JJ86
  • 5,055
  • 2
  • 35
  • 64
  • @Mehdi English is not my mother language and it's hard to write a very good explaination for me, sorry. For memory management, please read this link http://stackoverflow.com/questions/8482606/when-a-fragment-is-replaced-and-put-in-the-back-stack-or-removed-does-it-stay) – JJ86 Dec 13 '13 at 14:47