how to add menu items to action bar in more than 30 activities

291 views Asked by At

I have created an app in android studio that has more than 30 activities .I created menu items in some activities by adding them in individual menu files and they worked fine .

But the problem is that it is a real headache to add all the menu items in menu files of each activity.So how to solve this issue ? can i use a custom menu file for all activities ? if yes, than how ?

Please help and thanks in advance.

1

There are 1 answers

1
npace On BEST ANSWER

Option A

A base Activity class that implements the logic for the menu items - in this case all 30 of your Activities should extend the base Activity.

This approach has the serious limitation that it forces you to extend a class even though you may need to extend another since Java does not support multiple inheritance. That's the reason for the common mantra "favor composition over inheritance".

Option B

Create a Fragment that calls setHasOptionsMenu(true) in its onCreate callback and add an instance of this fragment to all your activities in their own onCreate callbacks. The fragment does not need to override onCreateView, since it doesn't inflate any layout.

This approach has a bit of added complexity, but the payoff is that you are not forced to inherit from a base class for all your activities.