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
menu.addSubMenu("menuSubtitle").
*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="http://schemas.android.com/apk/res/android">

<item android:id="@+id/action_add"
android:icon="@android:drawable/ic_menu_add"
android:title="@string/action_bar_add"
android:showAsAction="ifRoom"
</item>
<item android:id="@+id/action_sort"
android:icon="@android:drawable/ic_menu_sort_by_size"
android:title="@string/action_bar_sort"
android:showAsAction="ifRoom"> (we can also use this action ALWAYS, NEVER, WITHTEXT )
<menu>
<item android:id="@+id/action_sort_size"
android:icon="@android:drawable/ic_menu_sort_by_size"
android:title="@string/action_bar_sort_size"
android:onClick="onSort" />
<item android:id="@+id/action_sort_alpha"
android:icon="@android:drawable/ic_menu_sort_alphabetically"
android:title="@string/action_bar_sort_alpha"
android:onClick="onSort" />
</menu>
</item>
</menu>
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(R.menu.actions, menu);(//R.menu.actions 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
item.getItemId()

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
android:onClick="onSort"

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