Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same option menu in all Activities in Android

I have 10-15 activities in my project. I want to have the option menu mostly in all Activities. Then is their any way we can do it at one place and it appears in all activities.

Also, I will like to hide the option menu in some. So, is it possible or I have to write option menu code in all activities.

Regards

Sunil

like image 808
sunil Avatar asked Jul 17 '10 04:07

sunil


People also ask

How pass data from one activity to multiple activity in Android?

We can send the data using putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.

What is the role of option menu in Android?

The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings." See the section about Creating an Options Menu.


1 Answers

Create a Class (say BaseActivity) that extends Activity, and override onCreateOptionsMenu and onOptionsItemSelected functions.

public class BaseActivity extends Activity {      // Activity code here      @Override     public boolean onCreateOptionsMenu(Menu menu) {         MenuInflater inflater = getMenuInflater();         inflater.inflate(R.menu.options_menu, menu);         return true;     }      @Override     public boolean onOptionsItemSelected(MenuItem item) {         switch (item.getItemId()) {             case R.id.item:                 // do what you want here                 return true;             default:                return super.onOptionsItemSelected(item);         }     } } 

Now, in the other 15-16 activities, instead of extending an Activity, you should extend BaseActivity.

public class FooActivity extends BaseActivity {       // Activity code here  } 

This way, all your activities derive the options menu. For activities where you want the options menu disabled, you can override it again in that particular activity.

public class BarActivity extends BaseActivity {       // Activity code here     @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Do Nothing    }     @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Do Nothing    } } 

Hopefully, it doesn't give you problems in the manifest file.

like image 143
st0le Avatar answered Oct 14 '22 02:10

st0le