Android ViewPager Example

, , 33 Comments

In this tutorial you will learn android horizontal view swiping with ViewPager. This feature has been showcased in several high profile applications like the Android Market application and the Google+ Android client. There are a number of classes in the Android compatibility package that can be used to implement horizontal page swiping behavior in your Android packages. The ViewPager control (android.support.v4.view.ViewPager) provides the horizontal swiping behavior. It can be used within your layouts much like a Gallery or other adapter-populated user interface control would be. The PagerAdapter (android.support.v4.view.PagerAdapter) class is used to define the data displayed by the ViewPager control.

Horizontal view paging is based upon APIs only available with the Android Compatibility package v4, Revision 3 ; these APIs are not available in the standard Android SDK at this time. Therefore, you will need to add the Android compatibility package to your Android project to access the appropriate APIs.

Step 1 :  Define ViewPager in layout (main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <TableLayout
        style="@style/layout_f_w"
        android:stretchColumns="*" >
        <TableRow
            android:id="@+id/tableRow1"
            android:background="#dddddd"
            style="@style/layout_wrap">

              <!-- First Tab -->
	            <LinearLayout
		        style="@style/layout_f_w"
		        android:id="@+id/first_text"
		        android:orientation="vertical" >

	                  <TextView
	                    android:id="@+id/textView1"
	                    style="@style/text_title"
	                    android:text="Tab1" />
	           </LinearLayout>

	        <!-- Second Tab -->
	            <LinearLayout
		        style="@style/layout_f_w"
		        android:id="@+id/second_text"
		        android:orientation="vertical" >

	                <TextView
	                    android:id="@+id/textView1"
	                    style="@style/text_title"
	                    android:text="Tab2" />

	           </LinearLayout>

        </TableRow>
    </TableLayout>
    <!-- Include Tab Indicator  -->
 <include layout="@layout/indicator" android:layout_width="fill_parent" android:layout_height="wrap_content"  />

 <android.support.v4.view.ViewPager
		android:layout_width="fill_parent" android:layout_height="fill_parent"
		android:id="@+id/viewPager" />
</LinearLayout>

Step 2 : Create ViewPager Tab indicator layout (indicator.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TableLayout
        style="@style/layout_f_w"
        android:stretchColumns="*" >
        <TableRow
            android:background="#dddddd"
            android:id="@+id/tableRow1"
            style="@style/layout_wrap" >

             <!-- First Tab indicator -->
	            <LinearLayout
		        style="@style/indicator_style"
		        android:id="@+id/first_tab" >
	           </LinearLayout>

	        <!-- Second Tab indicator -->
	            <LinearLayout
		        style="@style/indicator_style"
		        android:id="@+id/second_tab"
		        android:visibility="invisible" >
	           </LinearLayout>
        </TableRow>
    </TableLayout>

    <!-- Bottom line -->
    	<LinearLayout
	    style="@style/h_line"
	    android:orientation="vertical" >
	  </LinearLayout>

</LinearLayout>

Step 3 :  Create ViewPager Activity (ViewPagerStyle1Activity.java)

I have used the FragmentActivity to define the view pager.

package com.manishkpr.viewpager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;

public class ViewPagerStyle1Activity extends FragmentActivity {
	private ViewPager _mViewPager;
	private ViewPagerAdapter _adapter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpView();
        setTab();
    }
    private void setUpView(){
   	 _mViewPager = (ViewPager) findViewById(R.id.viewPager);
     _adapter = new ViewPagerAdapter(getApplicationContext(),getSupportFragmentManager());
     _mViewPager.setAdapter(_adapter);
	 _mViewPager.setCurrentItem(0);
    }
    private void setTab(){
			_mViewPager.setOnPageChangeListener(new OnPageChangeListener(){

						@Override
						public void onPageScrollStateChanged(int position) {}
						@Override
						public void onPageScrolled(int arg0, float arg1, int arg2) {}
						@Override
						public void onPageSelected(int position) {
							// TODO Auto-generated method stub
							switch(position){
							case 0:
								findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
								findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
								break;

							case 1:
								findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
								findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
								break;
							}
						}

					});

    }
}

Step 4 :  Create ViewPager Adapter java file (ViewPagerAdapter.java)

  package com.manishkpr.viewpager;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {
	private Context _context;

	public ViewPagerAdapter(Context context, FragmentManager fm) {
		super(fm);
		_context=context;

		}
	@Override
	public Fragment getItem(int position) {
		Fragment f = new Fragment();
		switch(position){
		case 0:
			f=LayoutOne.newInstance(_context);
			break;
		case 1:
			f=LayoutTwo.newInstance(_context);
			break;
		}
		return f;
	}
	@Override
	public int getCount() {
		return 2;
	}

}

Step 5 :  Create Xml Layout one (layout_one.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:gravity="center|center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Layout" />

</LinearLayout>

Step 7 :  Create Java file (layout_two.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:gravity="center|center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Layout" />

</LinearLayout>

Step 8 :Create Java file (LayoutOne.java)


package com.manishkpr.viewpager;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LayoutOne extends Fragment {

	public static Fragment newInstance(Context context) {
		LayoutOne f = new LayoutOne();

		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
		return root;
	}

}

Step 9 : Create Java file (LayoutTwo.java)


package com.manishkpr.viewpager;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class LayoutTwo extends Fragment {

	public static Fragment newInstance(Context context) {
		LayoutTwo f = new LayoutTwo();

		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_two, null);
		return root;
	}

}

Step 10 : Define styles (values/styles.xml)

<?xml version="1.0" encoding="utf-8"?>
<resources>

	<style name="Theme" parent="android:Theme">
		<item name="android:background">@null</item>
		<item name="android:windowNoTitle">true</item>
	</style>

	<style name="text_title">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:textColor">@color/d_gray</item>
		<item name="android:gravity">center</item>
    </style>

	<style name="text_option">
		<item name="android:layout_width">wrap_content</item>
		<item name="android:layout_height">wrap_content</item>
		<item name="android:textColor">@color/black</item>
    </style>

	<style name="layout_wrap">
		<item name="android:layout_width">wrap_content</item>
		<item name="android:layout_height">wrap_content</item>
    </style>

    <style name="layout_fill">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">fill_parent</item>
    </style>

    <style name="layout_f_w">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">wrap_content</item>
    </style>

    <style name="h_line">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">1.5dip</item>
		<item name="android:background">@color/l_blue</item>
    </style>

        <style name="indicator_style">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">4dip</item>
		<item name="android:background">@color/l_blue</item>
		<item name="android:orientation">vertical</item>
    </style>

</resources>

Screen shoot :

Download Source code from here

Be Sociable, Share!
Follow us on Twitter
 

33 Responses

  1. Aljaz

    06/09/2012, 05:36 pm

    Thanks for the tutorial. I did everything as it is shown, but somehow the app crashes when trying to start this activity. Any clue :) ?

    Reply
  2. Aljaz

    06/10/2012, 01:34 pm

    Fixed the problem. I had to right click the project, then select Android Tools–> Add Support Library…

    Thanks again for excelent tutorial!

    Reply
  3. Karthick

    08/31/2012, 02:52 pm

    I’m getting this error.. :(

    08-31 20:09:44.757: E/AndroidRuntime(483): Caused by: java.lang.ClassNotFoundException: com.manishkpr.viewpager.ViewPagerStyle1Activity in loader dalvik.system.PathClassLoader[/data/app/com.manishkpr.viewpager-2.apk]

    Reply
  4. Munish Kapoor

    08/31/2012, 04:54 pm

    1.) select your project and right click select the option properties.
    2) in the properties menu go to java build path then select the order and export tab
    3) the check to android support jar file…

    then run the project.

    cheerss :)

    Reply
  5. bry

    09/03/2012, 03:51 pm

    Hello,
    how to insert my own activity on tab1 or tab2. In Your tutorial its one possibility to change items on layout file. What do I must to insert my activity in first layout and other activity in second layout?

    Reply
    • Munish Kapoor

      09/05/2012, 05:14 pm

      Fragment use the multiple views in it you can’t add the activity in fragments. you can access to the layoutone resorces Id by following code.

      yourButton=(Button)root.findViewById(R.id.yourButton);

      Reply
  6. Nagaraj

    11/29/2012, 05:32 am

    Thanks for this blog manish…Everything works fine for me…
    I have a question…I am trying to add Menu for each Fragment…I got the onCreateOptionsMenu() method defined under each Fragment class…but it does not really inflate the menu..i.e, the menu is not showing up when I click the menu button…any idea? My requirement is to have separate menu to be displayed for each Fragment like how it works for tabbed activities…please reply.
    Thanks.

    Reply
  7. gaurav

    11/30/2012, 11:22 am

    Hi could you please help me with one issue… I have implemented your tutorial in my project, and it’s work fine. But How can I implement, if I click on top “Tab1″, “Tab2″ and it will call respective layout… ? pls help me

    Reply
  8. Ricardo Almeida

    12/10/2012, 01:34 pm

    Been looking how to make something like this for some time, finally found the way to do it. Thanks for the help, you were very helpful.

    Reply
  9. Hardyesh Gupta

    01/07/2013, 07:58 am

    Thanks for the sample.

    But I am doing some background task in both fragment and show dialog in UI, When I start the app it instantiate both fragment simultaneously, which causes i get the dialog of second fragment in first fragment.

    It seems like getItem() method of Adapter called twice….

    How do I restrict it from calling getitem() method twice..? please help me….
    Thanks in Advance..

    Reply
  10. BruceWayne

    02/18/2013, 06:16 pm

    Hello Munish , i try your source code to setOnClick Listener but still get error FATAL EXCEPTION:MAIN
    This is my source code , thank you for your answer!

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    final ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);

    Button btn=(Button)root.findViewById(R.id.imageButton1);
    btn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub

    return;

    }
    });
    return btn;

    Reply
  11. pratik

    05/02/2013, 10:29 am

    on account of your efforts and knowledge i am able to run application…..I have dug around but couldn’t find the solution..thank you dude….carry on your efforts…!

    Reply

Leave a Reply

(*) Required, Your email will not be published