Understanding onCreateOptionsMenu in Android
Q: What is the purpose of the onCreateOptionsMenu method in an Android Activity? Can you give an example of how to use it?
- Android
- Junior level question
Explore all the latest Android interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create Android interview for FREE!
The onCreateOptionsMenu method in an Android Activity
is used to inflate a menu resource and display it as an options menu when the
user presses the "menu" button on their device or the overflow button
on the action bar. The method is called only once, when the activity is
created.
Here's an example of how to use onCreateOptionsMenu in
an Android Activity:
public class MyActivity extends Activity { public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu resource getMenuInflater().inflate(R.menu.my_menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { // Handle menu item clicks switch (item.getItemId()) { case R.id.action_settings: // Open settings activity Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); return true; case R.id.action_help: // Show help dialog showHelpDialog(); return true; default: return super.onOptionsItemSelected(item); } } }
In this example, the onCreateOptionsMenu method
inflates a menu resource called my_menu.xml, which defines two menu
items: "Settings" and "Help". The onOptionsItemSelected
method is used to handle clicks on these menu items. When the
"Settings" menu item is clicked, the method starts a new activity to
display the app's settings. When the "Help" menu item is clicked, the
method displays a help dialog.
Note that the onCreateOptionsMenu method should
return true to indicate that the menu was successfully created. If it
returns false, the menu will not be displayed.


