Action Bar with Menu

Action Bar with Menu:

Generally we create a menu option in our application like onCreateOptionsMenu(Menu menu)
and then with menu.add("menuItem") and if we want sub menu then we use to do
*In this way of writing is efficient when we have very less menu items .
*If we have many menu and sub menu items then its very good to write in xml and then inflate that, so
that when change menu items, icons, names…easily.

Next we ll see how to write the xml for menu

<menu xmlns:android="">

<item android:id="@+id/action_add"
<item android:id="@+id/action_sort"
android:showAsAction="ifRoom"> (we can also use this action ALWAYS, NEVER, WITHTEXT )
<item android:id="@+id/action_sort_size"
android:onClick="onSort" />
<item android:id="@+id/action_sort_alpha"
android:onClick="onSort" />
As we can see that when we want to add a menu then take a item tag, if you want to add sud menu to that item then,
don't close that item tag and then add menu tag and same way of adding items.

Next we need to inflate this xml in our java code, we can do this in below method
onCreateOptionsMenu(Menu menu)
MenuInflater inflater = getMenuInflater();
inflater.inflate(, menu);(// is the xml layout).
return true;

Next how to interact with menu buttons.
onOptionsItemSelected(MenuItem item)// these is the method called when the menu items are clicked.
//we can get the item id which is selected

Other way of accessing with menu buttons(should be done when we have very less menu items)
in the item tag when we give the menu details we need to add a line

And in Java we should write the method for this onlick
public void onSort(MenuItem item) {
note:the onclick name in xml and method name in java should be same