Android: How to have a shared menu in each (List) Activity without re-writing the overridden methods?

android, android-activity, listactivity, menu

Solution

I see no reason this wouldn't work perfectly:

public abstract class MyListActivity extends ListActivity
{
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      menu.add(0, AIS, 0, "Activity Inventory Sheet").setIcon(android.R.drawable.ic_menu_upload);
      // ...
      return true;
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      Intent i;
      switch (item.getItemId()) {
          case AIS: i = new Intent(this, ActivityInventorySheet.class);
          startActivity(i);
          return true;
          // ...
      }
      return false;
   }    
}

Then just have your Activities extend MyListActivity instead of ListActivity.

I've already seen that sub-classing one of my ListActivity does not work very well (threads that retrieve objects from a database are giving problems).

This sounds like a completely different problem. You might want to post a separate question regarding this. Simply extending a class in Java shouldn't create any problems like the one you are describing.

Problem

I know that Android provides some useful methods to be overridden in order to define a menu: ``` @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, AIS, 0, "Activity Inventory Sheet").setIcon(android.R.drawable.ic_menu_upload); // ... return true; } public boolean onOptionsItemSelected(MenuItem item) { Intent i; switch (item.getItemId()) { case AIS: i = new Intent(this, ActivityInventorySheet.class); startActivity(i); return true; // ... } return false; } ``` I would like to have this menu shared by each Activity and ListActivity of my Android application. This is for having a standard menu in each (List) Activity that lets the user jump to every part of the application within a click. Right now, the easiest way to achieve this is to copy-and-paste both methods in every (List) Activity of the application. I don't like this redundancy of code written :) Is sub-classing a reasonable choice? I've already seen that sub-classing one of my ListActivity does not work very well (threads that retrieve objects from a database are giving problems). Are there other ways to share a menu though Activities? Thanks

Original source