codeofaninja
website

Android Action Bar Tutorial with 2.2+ Compatibility

Photo of Mike Dalisay
Modified Monday, February 10, 2014
by - @ninjazhai
Note: The code is working but we are currently improving this article.

This is a step by step guide on how you can create an ActionBar for your awesome Android app.


DOWNLOAD SOURCE CODE

1. Create new project.

Go to File > New > Android Application Project

2. Add three icons to the project's res/drawable-hdpi/ directory


You can download the Android design icon pack.


3. Modify res/menu/main.xml and add three ActionBar items.


<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/refresh"
        android:icon="@drawable/ic_action_refresh"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="Refresh"/>
    <item
        android:id="@+id/copyLink"
        android:icon="@drawable/ic_action_copy"
        android:orderInCategory="100"
        android:showAsAction="collapseActionView"
        android:title="Copy Link"/>
    <item
        android:id="@+id/share"
        android:icon="@drawable/ic_action_share"
        android:orderInCategory="100"
        android:showAsAction="always"
        android:title="Share"/>

</menu>

4. Create the onOptionsItemSelected() method

This is inside MainActity.java

// handle click events for action bar items
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    
        case R.id.refresh:
            showToast("Refresh was clicked.");
            return true;
            
        case R.id.copyLink:
            showToast("Copy link was clicked.");
            return true;
            
        case R.id.share:
            showToast("Share was clicked.");
            return true;
            
        default:
            return super.onOptionsItemSelected(item);
    }
} 

5. Create the showToast() for each case

This is inside MainActity.java

// so that we know something was triggered
public void showToast(String msg){
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}

6. Create getOverflowMenu()

This is inside MainActity.java

// put the other two menu on the three dots (overflow)
private void getOverflowMenu() {

    try {
        
       ViewConfiguration config = ViewConfiguration.get(this);
       java.lang.reflect.Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
       if(menuKeyField != null) {
           menuKeyField.setAccessible(true);
           menuKeyField.setBoolean(config, false);
       }
   } catch (Exception e) {
       e.printStackTrace();
   }
    
} 

Call it from onCreate() to show unshown actions as three dots

getOverflowMenu();

Final Code

MainActivity.java

package com.example.actionbarexample;

import com.example.actoinbarexample.R;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        getOverflowMenu();
        
    }

    // inflate for action bar
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    // handle click events for action bar items
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
        
            case R.id.refresh:
                showToast("Refresh was clicked.");
                return true;
                
            case R.id.copyLink:
                showToast("Copy link was clicked.");
                return true;
                
            case R.id.share:
                showToast("Share was clicked.");
                return true;
                
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    // put the other two menu on the three dots (overflow)
    private void getOverflowMenu() {

        try {
            
           ViewConfiguration config = ViewConfiguration.get(this);
           java.lang.reflect.Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
           if(menuKeyField != null) {
               menuKeyField.setAccessible(true);
               menuKeyField.setBoolean(config, false);
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
        
     }
    
    // so that we know something was triggered
    public void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}


Lower Android (2.2+) Version Compatibility


Android ActionBar only works for Honeycomb and Up. To make it work with pre-honeycome devices, you should use the Android support library. Download it first using your SDK manager and then follow the step by step guide here.

This link might also help you.

I found the following video helpful too.



More about the ActionBar:

The Code of a Ninja Resources

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
 
 
Fundamentals
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.