Android Horizontal Swiping in Action Bar Tabs using ViewPager

May 7, 2013
By

In this article, we will develop an Android application which explains how to implement horizontal swiping in Action Bar tabs . The horizontal swiping is achieved using ViewPager container.



The minimum required Android version for running this application is Android API level 11. In order to implement this horizontal swiping of Action Bar tabs in prior versions of  Android API level 11,  please refer the article titled “Implement Swiping between Tabs with ViewPager in Action Bar using Sherlock library“.

This application is developed in Eclipse ( 4.2.1 ) with ADT plugin (21.1.0 ) and Android SDK library ( R21.1.0 ) .



1. Create new Android application project namely “ActionBarNavTabSwipe”

Create new Android application project

Figure 1 : Create new Android application project


2. Configure the project

Configure the application project

Figure 2 : Configure the application project


3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon


4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity details

Figure 5 : Enter MainActivity details


6. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

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


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Swiping between tabs</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
</resources>


8. Update the layout file res/layout/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"
    tools:context=".MainActivity" >

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

</RelativeLayout>


9. Create a fragment class namely AndroidFragment in the file src/in/wptrafficanalyzer/actionbarnavtabswipe/AndroidFragment.java


package in.wptrafficanalyzer.actionbarnavtabswipe;

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

public class AndroidFragment extends ListFragment{

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

10. Create a fragment class namely AppleFragment in the file src/in/wptrafficanalyzer/actionbarnavtabswipe/AppleFragment.java


package in.wptrafficanalyzer.actionbarnavtabswipe;

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

public class AppleFragment extends ListFragment{

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

11. Create a FragmentPagerAdapter class namely MyFragmentPagerAdapter in the file src/in/wptrafficanalyzer/actionbarnavtabswipe/MyFragmentPagerAdapter.java


package in.wptrafficanalyzer.actionbarnavtabswipe;

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;
    }

}


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


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


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


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


16. 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>


17. 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>


18. Update the file src/in/wptrafficanalyzer/actionbartabswipe/MainActivity.java


package in.wptrafficanalyzer.actionbarnavtabswipe;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends FragmentActivity {

    ActionBar mActionBar;
    ViewPager mPager;

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

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

        /** 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 onTabReselected(Tab arg0,
                android.app.FragmentTransaction arg1) {
                // TODO Auto-generated method stub
            }

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

            @Override
            public void onTabUnselected(Tab tab,
                android.app.FragmentTransaction ft) {
                // TODO Auto-generated method stub
            }
        };

        /** 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) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}


19. Update the file AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.actionbarnavtabswipe"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.actionbarnavtabswipe.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


20. Screenshot of the application

Swiping Action Bar tabs using ViewPager

Figure 6 : Swiping Action Bar tabs using ViewPager


21. Download Source Code


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

8 Responses to Android Horizontal Swiping in Action Bar Tabs using ViewPager

  1. Nazrul on July 20, 2013 at 7:05 am

    Hi there,

    This source compiles, but crashes on start with the MainActivity not found exception.

    I have not changed anything, just simply compiled it. Please can you help?

    Thanks

    • george on July 20, 2013 at 8:16 am

      Hi,
      Please do the following :

      * Open properties window by right clicking the project from project explorer

      * Select Java Build Path -> Order and Export tab

      * Ensure “Android Private Libraries” is checked

      * If unchecked, “check” it and click ok

      * Clean and Build the project and run the application

  2. Aamir on September 30, 2013 at 8:40 pm

    Hi..
    Great Tutorial.. Sir i want to save the state of the checkbox even after exiting the application.. how can i do that?? can you please help me Using the above code??
    Thanks..

  3. iza on October 31, 2013 at 5:24 am

    Hi, recently I’m working with fragments, I want to use GridView on a fragment, but I have a lot of problems, do you have any example, article or implementation using it? Thank you.

  4. sarina on January 7, 2014 at 3:39 am

    hi ,
    your tutorial is very helpful for me.I have done exactly what you ve done but i ve created list view that extends baseadapter so that i can ve my own layout.But i dont know how to link it with fragment class.Plz can you plz help me.

  5. Pratik Borole on May 21, 2014 at 8:07 pm

    Hi,
    can you please tell me how to make the tab indicator transit smoothly between tabs much like the new facebook app on android? Is any native support given by the action bar?

  6. Alireza on December 13, 2014 at 7:37 pm

    hi , what should i do if i want to have navigation drawer and this kind of tab together, i have tried both but the navigation drawer only cover the the tab not all of the screen like google play app

  7. jomel on January 7, 2016 at 12:26 pm

    Hi, can i know what is the version of the refractor?

Leave a Reply to iza Cancel reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner