Implement Swiping between Tabs with ViewPager in Action Bar using Sherlock library

August 7, 2012
By

In this article we will see how to navigate between tabs in action bar by simply swiping the tab content horizontally. For this we will make use the concepts used in the articles “Adding Navigation tabs containing listview to Action Bar in Pre Honeycomb versions using Sherlock library” and “Implementing Horizontal View Swiping Using ViewPager and FragmentPagerAdapter in Android” .

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


1. Setup Sherlock library in Eclipse IDE

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 a new Android project namely “ActionBarSherlockNavTabSwipe”

New Android Project

Figure 1 : New Android Project


3. Design application launcher icon

Design Application launcher

Figure 2 : Design Application launcher


4. Create a blank activity

Create a blank activity

Figure 3 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


6. Delete Android’s default support library if exists from the project

By default, Eclipse adds Android’s Support library to the project. We don’t want to use this library for this project. This library will be available in the folder “libs” in the name “android-support-v4.jar“. Delete this jar file from the “libs” folder.

Delete the file android-support-v4.jar from libs folder

5. Delete the file android-support-v4.jar from libs folder


7. Add Action Bar Sherlock library to this project

  • Open Project Explorer
  • Right click the project
  • Open Properties
  • Select “Android” tab from the Properties Window
  • Then the given below screen will be appeared
  • Using Add button, add the Sherlock library to this project
Adding Action bar Sherlock library to this project

Figure 6 : Adding Action bar Sherlock library to this project


8. Update the file res/values/strings.xml


<resources>
    <string name="app_name">ActionBarSherlockNavTabSwipe</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Swiping between Tabs</string>
</resources>

Note : Title of the MainActivity is updated here


9. Update the layout file activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    />

</RelativeLayout>

Note : The layout file contains only ViewPager


10. Create a fragment class namely AndroidFragment in the file src/in/wptrafficanalyzer/actionbarsherlocknavtabswipe/AndroidFragment.java


package in.wptrafficanalyzer.actionbarsherlocknavtabswipe;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockListFragment;

public class AndroidFragment extends SherlockListFragment{

    /** 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);
    }
}


11. Create a fragment class namely AppleFragment in the file src/in/wptrafficanalyzer/actionbarsherlocknavtabswipe/AppleFragment.java

package in.wptrafficanalyzer.actionbarsherlocknavtabswipe;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockListFragment;

public class AppleFragment extends SherlockListFragment{

    /** 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);

    }
}



12. Create a FragmentPagerAdapter class namely MyFragmentPagerAdapter in the file src/in/wptrafficanalyzer/actionbarsherlocknavtabswipe/MyFragmentPagerAdapter.java


package in.wptrafficanalyzer.actionbarsherlocknavtabswipe;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{

    final int PAGE_COUNT = 2;

    /** Constructor of the class */
    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    /** This method will be invoked when a page is requested to create */
    @Override
    public Fragment getItem(int arg0) {
        Bundle data = new Bundle();
        switch(arg0){
            /** Android tab is selected */
            case 0:
                AndroidFragment androidFragment = new AndroidFragment();
                data.putInt("current_page", arg0+1);
                androidFragment.setArguments(data);
                return androidFragment;

            /** Apple tab is selected */
            case 1:
                AppleFragment appleFragment = new AppleFragment();
                data.putInt("current_page", arg0+1);
                appleFragment.setArguments(data);
                return appleFragment;
        }
        return null;
    }

    /** Returns the number of pages */
    @Override
    public int getCount() {
        return PAGE_COUNT;
    }
}


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


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


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


16. Create a new folder called “drawable” in the folder res


17. Create a new file called android.xml in the folder res/drawable


<?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>


18. Create a new file called apple.xml in the folder res/drawable folder


<?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>


19. Update the file src/in/wptrafficanalyzer/actionbarsherlocktabswipe/MainActivity.java


package in.wptrafficanalyzer.actionbarsherlocknavtabswipe;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

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

public class MainActivity extends SherlockFragmentActivity {
    ActionBar mActionBar;
    ViewPager mPager;

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

        /** Getting a reference to action bar of this activity */
        mActionBar = getSupportActionBar();

        /** Set tab navigation mode */
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        /** Getting a reference to ViewPager from the layout */
        mPager = (ViewPager) findViewById(R.id.pager);

        /** Getting a reference to FragmentManager */
        FragmentManager fm = getSupportFragmentManager();

        /** Defining a listener for pageChange */
        ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mActionBar.setSelectedNavigationItem(position);
            }
        };

        /** Setting the pageChange listner to the viewPager */
        mPager.setOnPageChangeListener(pageChangeListener);

        /** Creating an instance of FragmentPagerAdapter */
        MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);

        /** Setting the FragmentPagerAdapter object to the viewPager object */
        mPager.setAdapter(fragmentPagerAdapter);

        mActionBar.setDisplayShowTitleEnabled(true);

        /** Defining tab listener */
        ActionBar.TabListener tabListener = new ActionBar.TabListener() {

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

            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                mPager.setCurrentItem(tab.getPosition());
            }

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

        /** Creating Android Tab */
        Tab tab = mActionBar.newTab()
                .setText("Android")
                .setIcon(R.drawable.android)
                .setTabListener(tabListener);

        mActionBar.addTab(tab);

        /** Creating Apple Tab */
        tab = mActionBar.newTab()
                .setText("Apple")
                .setIcon(R.drawable.apple)
                .setTabListener(tabListener);

        mActionBar.addTab(tab);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


20. Update the file AndroidManifest.xml


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

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

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

</manifest>


21. Screenshot of the application

Swiping Between Tabs using View Pager

Figure 7 : Swiping Between Tabs using View Pager


22. Download


23. 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: , , , , , , , ,

23 Responses to Implement Swiping between Tabs with ViewPager in Action Bar using Sherlock library

  1. Abhinov on August 30, 2012 at 6:33 pm

    Hi thanks for the great tutorial but i have a small problem i need to extend activity for the sherlock so that i can include buttons dynamically for the listview could u please help me in adding the layouts so that i can add buttons in that

    Thanks in advance

  2. Hector on September 24, 2012 at 10:31 am

    Amazing!

  3. ZHicham on November 23, 2012 at 8:40 pm

    Thanks for this nice tutorial,i have a question ,how we can add more listView such Windows Phone,Bada? i tried but didn’t work

  4. Darsh on November 24, 2012 at 5:26 pm

    Hi, if I am using this implementation in one of my android apps, all I need is to include a copy of the Apache License 2.0 in the project right?

  5. Pkmmte Xeleon on November 25, 2012 at 8:18 am

    This is the best tabs tutorial I found! Thanks!

    I have a question:
    How do I set up a different content view depending on the selected tab? I want the fragment to load up an XML layout instead.

  6. Maarten Pennings on December 5, 2012 at 5:08 am

    Suppose that eg AndroidFragment has a method, say addVersion(). Suppose that I want to call that method from the MainActivity. How does the MainActivity get a handle to the AndroidFagment?

  7. ZHicham on December 18, 2012 at 5:21 am

    Very professional tutorial,thank you very much,,,,i have an issue ;how i can make fragment getting data from other activity (like SplashActivity) using intents; instead of this initializing String apple_versions[] = new String[]{
    “Mountain Lion”,
    “Lion”,
    “Snow Leopard”,
    “Leopard”,
    “Tiger”,
    “Panther”,
    “Jaguar”,
    “Puma”
    };
    inside fragments,we initializate it within SplashScreen,clearly i want to initializate apple_versions[] using RSS within a SplashActivity and then passing it to the Fragments

  8. DaRear on January 7, 2013 at 12:12 pm

    Hi, how to run apps in android 2.3.4
    Thanks

  9. DaRear on January 7, 2013 at 12:13 pm

    i try to run this apps on android 4.1 is ok but for gingerbread can’t

  10. Ashish on January 11, 2013 at 4:41 pm

    Nice tutorial !
    I wanted to add 6 tabs but in pair of 3-3 and swipeable. Can you please tell me how can I achieve that ??

  11. Bruno AP on January 15, 2013 at 4:14 am

    Nice ! How could I inflate a new layout inside?

  12. Jieme on March 26, 2013 at 3:20 am

    Hi, very great tutorial.
    Thanks!

  13. shailesh on March 28, 2013 at 5:27 pm

    Code crashes before the Launcher activity Loads with the following exception:
    FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.actionbarsherlocknavtabswipe/in.wptrafficanalyzer.actionbarsherlocknavtabswipe.MainActivity}: java.lang.ClassNotFoundException: in.wptrafficanalyzer.actionbarsherlocknavtabswipe.MainActivity
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
    at android.app.ActivityThread.access$600(ActivityThread.java:123)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4424)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.ClassNotFoundException: in.wptrafficanalyzer.actionbarsherlocknavtabswipe.MainActivity
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
    … 11 more

    • shailesh on March 28, 2013 at 5:59 pm

      Sorry for this post… i was making a silly mistake.

    • Moacir on May 23, 2013 at 11:17 pm

      How did you fix this?
      I have the smae problem..

  14. shailesh on March 28, 2013 at 5:58 pm

    Sorry I was making some mistake …
    thanks alot for your supporting post.
    It worked for me…!!! thanks

    • Julien on June 16, 2013 at 3:48 am

      Hi, how did you fix it? I have the same error message and I’m blocked. Thanks a lot

  15. chinaman on May 6, 2013 at 10:43 am

    can you give a example not using sherlock library, i’m very need.

  16. chuck on May 15, 2013 at 3:31 pm

    Great tutorial. But how can I replace the fragment inside a tab to another. Let’s say, I have tab1, tab2, tab3 with their respective fragments. Then, inside tab1, there is a button that says go to detail fragment. If a user clicks that button, the fragment inside tab 1 will change into detail fragment without affecting tab2 & tab3′s content.
    Please reply, thanks in advance.

  17. Maksim on July 1, 2013 at 9:20 pm

    How to fix it:
    1) Right click on project-> Android Tools -> add suport library
    2) Project properies -> Java build path -> Order and Export
    select: src, gen and “Android Private Libraries”

  18. Joe on September 28, 2014 at 8:20 am

    Congrats this is one of the best(perhaps the only one most accurate) samples on the Web. THANK YA VERY MUCH 4 SHARING!!

  19. Vinay on December 22, 2015 at 2:46 pm

    Hey Awesome tut :)
    here in this case u have 2 tabs Android and Apple when u launch the app we get default fragment as Android How can we change it to Apple when activity gets launched first instead of Android. Plz help me :)

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