: In Android, we have a menu tagged with ActionBar called Options Menu. To work with Options Menu, we have following steps.
1) Design XML menu file in menu sub-directory of res directory2) Attach that XML in Activity by overriding onCreateOptionsMenu method3) Handling options menu item click by overriding onOptionsItemSelected
Designing XML menu: To design menu in XML, we will create an XML file in menu sub-directory in res directory. The syntax would be as follows
<menu> <item android:title=”Settings” android:icon=”@drawable/some_icon” app:showAsAction=”always|never|ifRoom” android:id=”@+id/menu_settings”/>
<item android:title=”Edit” android:id=”@+id/menu_edit”/>
<item android:title=”Remove” android:id=”@+id/menu_remove”/> </menu>
Attaching menu to Activity: To attach menu to Activity, we override onCreateOptionsMenu method in Activity. After that, we will inflate the menu using following example.
Ex: public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } Handling menu item click: To handle menu item click, we override onOptionsItemSelected method in Activity. The item click is differentiated based on the id and provided different functionality as follows.
Ex: public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if(itemId==R.id.menu_settings){ Toast.makeText(this, “Settings is clicked”, Toast.LENGTH_SHORT).show(); }else if(itemId==R.id.menu_exit){ finish(); } return super.onOptionsItemSelected(item); }
Create an Android application to work with Options Menu
Refer source on