Adding Navigation tabs containing listview to Action Bar in Pre Honeycomb versions using Sherlock library

July 30, 2012
By

In the article titled “Adding Navigation Tabs containing listview to Action Bar in Android“, we added navigational tabs to action bar. Action bar is introduced with Android 3.0 ( Honeycomb ) and is not supported in its previous versions. In order to create action bar in pre Honeycomb versions, we could use Sherlock library which can mimic action bar in pre Honeycomb versions. In this article we will create navigational tabs in action bar using Sherlock library.

An extension to this application is available in the article titled “Implement Swiping between Tabs with ViewPager in Action Bar using Sherlock library ” , where swiping between tabs is additionally implemented.

In order to create navigation tabs using tabhost and fragments, see the article “Creating Navigation tabs using TabHost and Fragments in Android“.

This application is developed in Eclipse 3.7.2 with ADT plugin ( 20.0.2 ) and Android SDK ( R20.0.1 )


1. Setting up Sherlock library for Eclipse 3.7.2

Please see the article titled “Setting up Sherlock library for action bar in pre Honeycomb Android Applications“, for setting up the Sherlock library for Eclipse 3.7.2


2. Create new Android application project namely “ActionBarSherlockNavTab”

New Android application Project

Figure 1 : New Android application Project


3. Design application launcher

Design Application Launcher

Figure 2: Design Application Launcher


4. Create a blank  activity

Create a new blank activity

Figure 3 : Create a new blank activity


5. Enter Activity details

Enter activity Details

Figure 4 : Enter activity Details


6. Delete Android’s support library for the backward compatibility


7. Add Sherlock library to the project

Add Sherlock library to this project

Figure 5 : Add Sherlock library to this project


8. Download the given below file and extract to drawable-ldpi


9. Download the given below file and extract to drawable-mdpi


10. Download the given below file and extract to drawable-hdpi


11. Create a new folder drawable in res and create a new file namely android.xml with the given below code

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:state_pressed="false"
        android:drawable="@drawable/android_selected" />
    <item
        android:drawable="@drawable/android_unselected" />
</selector>

12. Create new file namely apple.xml in res/drawable directory created in the above step and add the given below code

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:state_pressed="false"
        android:drawable="@drawable/apple_selected" />

    <item
        android:drawable="@drawable/apple_unselected" />
</selector>


13. Create the file src/in/wptrafficanalyzer/actionbarsherlocknavtab/AndroidFragment.java


package in.wptrafficanalyzer.actionbarsherlocknavtab;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockListFragment;

public class AndroidFragment extends SherlockListFragment implements ActionBar.TabListener{

    /** An array of items to display in ArrayList */
    String android_versions[] = new String[]{
        "Jelly Bean",
        "IceCream Sandwich",
        "HoneyComb",
        "Ginger Bread",
        "Froyo"
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /** Creating array adapter to set data in listview */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, android_versions);

        /** Setting the array adapter to the listview */
        setListAdapter(adapter);

        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();
        /** Setting the multiselect choice mode for the listview */
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(android.R.id.content, this,"android");
        ft.attach(this);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
         ft.detach(this);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}

Note : In the highlighted code (line 15 ) above, we used SherlockListFragment instead of ListFragment.


14. Create the file src/in/wptrafficanalyzer/actionbarsherlocknavtab/AppleFragment.java


package in.wptrafficanalyzer.actionbarsherlocknavtab;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockListFragment;

public class AppleFragment extends SherlockListFragment  implements ActionBar.TabListener{

    /** An array of items to display in ArrayList */
    String apple_versions[] = new String[]{
        "Mountain Lion",
        "Lion",
        "Snow Leopard",
        "Leopard",
        "Tiger",
        "Panther",
        "Jaguar",
        "Puma"
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        /** Creating array adapter to set data in listview */
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_multiple_choice, apple_versions);

        /** Setting the array adapter to the listview */
        setListAdapter(adapter);

        return super.onCreateView(inflater, container, savedInstanceState);

    }

    @Override
    public void onStart() {
        super.onStart();

        /** Setting the multiselect choice mode for the listview */
        getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.add(android.R.id.content, this,"apple");

        ft.attach(this);
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.detach(this);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}

Note : In the highlighted code (line 15 ) above, we used SherlockListFragment instead of ListFragment.


15. Update src/in/wptrafficanalyzer/actionbarsherlocknavtab/MainActivity.java

package in.wptrafficanalyzer.actionbarsherlocknavtab;

import android.os.Bundle;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class MainActivity extends SherlockFragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        actionBar.setDisplayShowTitleEnabled(true);

        Tab tab = actionBar.newTab()
                    .setText("Android")
                    .setTabListener(new AndroidFragment())
                    .setIcon(R.drawable.android);

        actionBar.addTab(tab);

        tab = actionBar.newTab()
                    .setText("Apple")
                    .setTabListener(new AppleFragment())
                    .setIcon(R.drawable.apple);

        actionBar.addTab(tab);

    }
}

  • Line 9 : Here MainActivity class inherits SherlockFragmentActivity instead of FragmentActivity. We used to inherit FragmentActivity when working with Android’s support library
  • Line 15 : Sherlock library returns a reference to action bar using the method getSupportActionBar()

16. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.actionbarsherlocknavtab"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".MainActivity"
                android:label="@string/title_activity_main"
                android:theme="@style/Theme.Sherlock"
            >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    </application>
</manifest>


17. Application in execution

Showing Navigational Tabs in Action Bar

Figure 6 : Showing Navigational Tabs in Action Bar


18. Download


19. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , ,

15 Responses to Adding Navigation tabs containing listview to Action Bar in Pre Honeycomb versions using Sherlock library

  1. Ivan on August 8, 2012 at 10:11 pm

    Awesome tutorial!!
    It´s easy to understand and works perfectly
    I have a couple of questions:
    – Is it possible to place the icon above the text in each tab?

  2. Ivan on August 8, 2012 at 10:13 pm

    sorry, I continue with the other post
    – can I change the text size in every tab?
    – last one, is it possible to place all the tabs into the screen?
    I don´t know if you know what I mean.

    Thanks in advance

  3. Yusuf on October 26, 2012 at 5:25 pm

    hello
    I would like to add a list of friends. List, you need to be picture.
    How do I make it.

  4. Yusuf on October 27, 2012 at 4:06 pm

    I’m sorry, I wrote the wrong.
    correction:I want to show the friends list in tabs

  5. rajeesh on December 31, 2012 at 2:51 pm

    thank you

  6. Lucas Daniel on April 13, 2013 at 11:42 pm

    thanks!!

  7. adel on May 13, 2013 at 4:27 am

    Thanks a lot for this very helpful tutorial!!!
    But I have two questions how do you deal with the landsacape mode? Because in my case the first fragment always appears in front and when I switch to the second fragment I have the two fragments one above the other.
    And don’t you use in this case the ft.commit()?
    Thanks a lot!!!

    • Julien on June 21, 2013 at 11:38 am

      I have got the same problem. Did you figure out how to solve this?

      • adel on June 21, 2013 at 12:42 pm

        Hi,

        Unfornately I can’t resolve the problem of the landscape mode. For the moment I’ve blocked my app in portrait mode for the moment. I think the best way is to create a code for the latest versions and another one for the olders one.

        I’m still searching for a better solution.

        • Julien on June 21, 2013 at 12:44 pm

          Thx for the quick answer. I’ll let you know if I figure out something on my side,

  8. Janka on August 8, 2013 at 4:58 pm

    Thank you so much, this tutorial is great

  9. Akshay on August 26, 2013 at 11:06 pm

    Hi, Will it work if I used BaseAdapter? How do I use notifydatasetchange on Tab change event.

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner