Monday, July 29, 2013

Starting With ActionBarSherlock

ActionBarSherlock is a library that extends the android support library to enable applications to use the action bar on devices with lower versions of the android os.

To follow this guide, you must download the ActionBarSherlock library from here.

After you have extracted the contents of the source file archive (the name of the file I downloaded is JakeWharton-ActionBarSherlock-4.4.0-0-g4a79d53.zip which, I assume, is the latest version), you must import the source file to create an android library project.

Select Import->Existing Android Code Into Workspace and navigate to the folder where you extracted the source archive. Select the folder named actionbarsherlock.


Check if the project is set as a library by viewing the project Properties->Select Android and check on the right part of properties window if the following is checked:

Create a new android project that you will use for testing the actionbarsherlock library. After the project is created, you need to reference the action bar library by viewing the Properties -> Android window again. Click add, and select the actionbarsherlock project that you imported earlier.

Please note that in my screenshot, I renamed the actionbarsherlock folder into abs.

To be able to use the action bar, your activity must extend the SherlockActivity class:

1:  package org.kaithe.android;  
2:  import com.actionbarsherlock.app.SherlockActivity;  
3:  import android.os.Bundle;  
4:  public class MainActivity extends SherlockActivity {  
5:       @Override  
6:       protected void onCreate(Bundle savedInstanceState) {  
7:            super.onCreate(savedInstanceState);  
8:            setContentView(R.layout.activity_main);  
9:       }  
10:  }  

From this point, you can already run your application. However, it will just look plain since we still haven't done any customisations on the action bar.


To test the action bar, we will add some items in it. Override the onCreateOptionsMenu method from the SherlockActivity class.
1:       @Override  
2:       public boolean onCreateOptionsMenu(Menu menu) {  
3:      menu.add("Save")  
4:        .setIcon(R.drawable.ic_compose)  
5:        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);  
6:      menu.add("Search")  
7:        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);  
8:      menu.add("Refresh")  
9:        .setIcon(R.drawable.ic_refresh)  
10:        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);  
11:      return true;  
12:       }  

In here, we created 3 menu on the action bar. Running the application, this is what our action bar will look like:


The action bar sherlock library source that I used can be found in here
The full action bar sample application source can be obtained here