Question

I'm learning about creating Options Menus for Android apps.

In the guide it has the following tip for staying DRY with menus:

Tip: If your application contains multiple activities and some of them provide the same Options Menu, consider creating an activity that implements nothing except the onCreateOptionsMenu() and onOptionsItemSelected() methods. Then extend this class for each activity that should share the same Options Menu. This way, you have to manage only one set of code for handling menu actions and each descendant class inherits the menu behaviors.

This appears problematic. If the Activitys that need to share the same options inherit from different classes, what should my OptionsMenuActivity inherit from? I read that Java does not support multiple inheritance, so how do you get around this?

Was it helpful?

Solution

Your activity that has the code for options menu should extend the Activity class.

public class YourRootActivity extends Activity {

// Any other stuff that you want for all activities

 public boolean onCreateOptionsMenu(Menu menu){
 // your main options menu
 }
}

Now for the classes that need this menu, make them extend the activity that we created above.

class Activity1 extends YourRootActivity {
}

In case you want slight modifications in your options menu in the subclasses, you can overwrite the onCreateOptionsMenu method in those classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top