Android Action Bar Tutorial

 
The action bar helps access the most important and relevant to current context actions much quicker and easier. Buttons that appear in the action bar are called action buttons, and in case some of them can't fit in the action bar, they are hidden in the action overflow
     Action bar also gives a dedicated space in your application to identify users location in the app, which can be very useful if your application has a complex hierarchy. 

Now there are three things that we need to do to make our action bar work:

Create menu and add items to it

         By default you will already have a menu file created for you,so go to the the res\menu directory and paste the following code into your main.xml file (in case you want to create a new menu just right click on menu directory and select New->Android XML File):

main.xml file:


         As you can see the menu we've created has four items, each one of them has an icon (I am using social network icons that I've downloaded from here http://sixrevisions.com/freebies/icons/free-set-of-social-media-icons-large-icons-social/) and a title. 
           The value of android:showAsAction is set to "ifRoom", which means that the item will be shown in the action bar if there is room left for it. Alternatively the value can be set to never or always.

Inflate a menu resource 

 Now we need to inflate the menu resource that we've just created by adding the following method to the activity class:



Handle clicks on action items

In the example application the value of  TextView and an ImageView of a main layout will be changed when one of the action button is clicked, so first we need to modify application layout file like this:
activity_main.xml file:

The last step is to handle clicks on action items. When the user presses an action button, system calls onOptionItemSelected() method, which we now will add to the activity file:
Each action has its on unique ID provided by the item tag's id attribute (in the menu.xml file). This way by calling getItemId() we can identify every action.

Full Activity Code


Demo
Android ActionBar Example
Android Action Bar Example
Source Code


References: