Horizontal view swiping is an important user interface feature which facilitates users to traverse from one view to another view by swiping the screen horizontally.
This feature is very commonly found in news applications like BBC, CNN, FOX etc. In this article we will develop an application to demonstrate horizontal view swiping.
We will make use the classes ViewPager and FragmentPagerAdapter for horizontal swiping feature. At the end of this article we will add an interactive and non-interactive pager title to the screen.
Since ViewPager class is available only in Android’s support library, we need to add the library to this project. ViewPager is compatible for Android 1.6 and above.
This application is developed in Eclipse ( 3.7.2 ) with ADT plugin ( 20.0.2 ) and Android SDK ( R20.0.1 )
1. Create a new Android application project namely “ViewPagerDemo”
2. Design Application launcher icon
3. Create a new blank activity
4. Enter MainActivity details
5. Add Android Support library to this project
Android support library is added by default in to the project automatically by ADT plugin. If the library is not added, then we can do it manually as follows :
- Open the project explorer
- Right click this project
- Select Android Tools from the popup menu
- Click Add Support library …
6. Update the layout file res/layout/activity_main.xml to include pager in the main activity
<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="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
7. Create a layout file for the fragment in src/in/wptrafficanalyzer/viewpagerdemo/myfragment_layout.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" > </TextView>
8. Create a fragment class called MyFragment in the file src/in/wptrafficanalyzer/viewpagedemo/MyFragment.java
package in.wptrafficanalyzer.viewpagerdemo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class MyFragment extends Fragment{ int mCurrentPage; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /** Getting the arguments to the Bundle object */ Bundle data = getArguments(); /** Getting integer data of the key current_page from the bundle */ mCurrentPage = data.getInt("current_page", 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.myfragment_layout, container,false); TextView tv = (TextView ) v.findViewById(R.id.tv); tv.setText("You are viewing the page #" + mCurrentPage + "\n\n" + "Swipe Horizontally left / right"); return v; } }
9. Create a FragmentPagerAdapter class in the file src/in/wptrafficanalyzer/viewpagedemo/MyFragmentPagerAdapter.java
package in.wptrafficanalyzer.viewpagerdemo; 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 = 5; /** 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) { MyFragment myFragment = new MyFragment(); Bundle data = new Bundle(); data.putInt("current_page", arg0+1); myFragment.setArguments(data); return myFragment; } /** Returns the number of pages */ @Override public int getCount() { return PAGE_COUNT; } }
10. Update the MainActivity class in the file src/in/wptrafficanalyzer/viewpagedemo/MainActivity.java
package in.wptrafficanalyzer.viewpagerdemo; 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 { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** Getting a reference to the ViewPager defined the layout file */ ViewPager pager = (ViewPager) findViewById(R.id.pager); /** Getting fragment manager */ FragmentManager fm = getSupportFragmentManager(); /** Instantiating FragmentPagerAdapter */ MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(fm); /** Setting the pagerAdapter to the pager object */ pager.setAdapter(pagerAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
11. Update the file AndroidManifest.xml to change the application’s title in the launcher
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="in.wptrafficanalyzer.viewpagerdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="4" 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" > <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>
12. Screenshot of the application in execution
13. Adding Non Interactive Pager Title to the View
Please see the screen given below, where a non interactive pager title is added to the screen.
In order to add a non-interactive pager title, do the given below modifications :
- Update the layout file res/layout/activity_main.xml with the highlighted code
<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="fill_parent" android:layout_height="fill_parent"> <android.support.v4.view.PagerTitleStrip android:id="@+id/pager_title_strip" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:background="#33b5e5" android:textColor="#fff" android:paddingTop="4dp" android:paddingBottom="4dp" /> </android.support.v4.view.ViewPager> </RelativeLayout>
- Override the method getPageTitle() of the class MyFragmentAdapter in the file /src/in/wptrafficanalyzer/viewpagerdemo/MyFragmentPagerDemo.java
package in.wptrafficanalyzer.viewpagerdemo; 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 = 5; /** 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) { MyFragment myFragment = new MyFragment(); Bundle data = new Bundle(); data.putInt("current_page", arg0+1); myFragment.setArguments(data); return myFragment; } /** Returns the number of pages */ @Override public int getCount() { return PAGE_COUNT; } @Override public CharSequence getPageTitle(int position) { return "Page #" + ( position + 1 ); } }
14. Adding An Interactive Pager Title to the View
Please see the screen given below, where an interactive pager title is added to the screen.
In order to add an interactive pager title, do the given below modifications:
- Update the layout file res/layout/activity_main.xml with the highlighted code
<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="fill_parent" android:layout_height="fill_parent"> <android.support.v4.view.PagerTabStrip android:id="@+id/pager_title_strip" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:background="#33b5e5" android:textColor="#fff" android:paddingTop="4dp" android:paddingBottom="4dp" /> </android.support.v4.view.ViewPager> </RelativeLayout>
- Override the method getPageTitle() of the class MyFragmentAdapter in the file /src/in/wptrafficanalyzer/viewpagerdemo/MyFragmentPagerDemo.java
package in.wptrafficanalyzer.viewpagerdemo; 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 = 5; /** 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) { MyFragment myFragment = new MyFragment(); Bundle data = new Bundle(); data.putInt("current_page", arg0+1); myFragment.setArguments(data); return myFragment; } /** Returns the number of pages */ @Override public int getCount() { return PAGE_COUNT; } @Override public CharSequence getPageTitle(int position) { return "Page #" + ( position + 1 ); } }
15. Download
Source code for the horizontal View Swiper with an Interactive Pager Title is given below :

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

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
this is working fine in 4.0 and above.
If we compile using 1.6 to 2.3 its not supporting.
Can you please tel me wats the reason behind this?
Seems to just fine using Android 2.2.
Here’s what I did:
*Download the source files from the link above
*Delete the /res/values-v11 and /res/values-v14 folders
*Delete ‘activity.xml’ from /res/menu
*Comment the following line in ‘MainActivity.java’
getMenuInflater().inflate(R.menu.activity_main, menu);
This should do it.
FragmentPagerAdapter its not supported to the nested fragment
data will not restored on UI
Great! Ideal demo source code for a newbie. Well done.
Have one doubt , i have successfully done this tutorial , now my problem each screen can be linked to a different layout xml , what if i want to spilt the layout into fragments like fragments basics all over again , if landscape then show body and menu pane
or else just menu , and on click we can swift to body of the article(textview or some other elements)
Hope my query is understandable
, if not please do the needful and help me on this
Great demo!!!!
How to create a listview in first fragment ?
How can we choose which page will be first one to start?
This we can do by the method setCurrentItem() on the pager object after the adapter is set.
Tnx. I tried and it is working.
Is it possible to make it circular?
It seems, no such option is available in ViewPager. But we can achieve it to “some extend” by following given below steps :
* Implement the interface OnPageChangeListener in the class MainActivity
* Change “pager” variable as a member variable
* Declare the member variables private int previousState, currentState;
* Override the method onPageScrollStateChanged() with the given below code :
@Override
public void onPageScrollStateChanged(int arg0) {
// Get the currently selected page
int currentPage = pager.getCurrentItem();
// 0 => Idle
// 1 => Begins Dragging
// 2 => Settling to the current page
// if last page or first page
if (currentPage == 4 || currentPage == 0) {
previousState = currentState;
currentState = arg0;
// For the first and last page, state changes from 1 to 0,
// if not settled to new page
if (previousState == 1 && currentState == 0) {
pager.setCurrentItem(currentPage == 0 ? 4 : 0);
}
}
}
Its not working for me.
I tried to debug code and when I scroll onPageScrollStateChanged is not even fired.
This was the problem:
stackoverflow.com/questions/12729416/android-viewpagers-onpagescrollstatechanged-never-gets-called
I am getting the following error
android.view.InflateException: Binary XML file line #18: Error inflating class android.support.v4.view.PagerTitleStrip
11-19 18:06:50.853: E/AndroidRuntime(773): Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class android.support.v4.view.PagerTitleStrip
11-19 18:06:50.853: E/AndroidRuntime(773): Caused by: java.lang.ClassNotFoundException: android.support.v4.view.PagerTitleStrip in loader
Hi Raam Kumar,
It looks like, the problem is with your Android Support Library. Ensure that, the library is properly added to the project.
When I ran the downloaded code, its running successfully but after adding PagerTitleStrip in the xml file as you mentioned, it shows error .Please help me.
Many thanks. i can go home to my weekend job done.
Excellent explanation. Thanks a lot!
Just one comment. Within “onCreateView” (section number 8) the returned view should be the whole layout linked to the fragment (myfragment_layout.xml), not only the “TextView”. The code you have written works correctly but it would be better to return the whole layout as a general solution.
Hi,
nice guide!
Is it possible to get different layouts for each site?
Yes, it is possible.
Specify the layout for each page at the time of layout inflation in the method onCreateView() of the class MyFragment.
Thanks for reply. But my trials were not positiv. Could you give me some code?
I also want code please help in this part
my correo :yhonaqc@hotmail.com
Hi! Is it possible to implement a google map view?
hello friend, I would like you to help me in the class to add different activitys Thanks
I need help with this please:
I recreated everything like the tutorial said. But I get a few errors:
MyFragmentPagerAdapter.java:
public MyFragmentPagerAdapter(FragmentManager fm){
super(fm); //
}
–> super(fm)is giving next error:
The constructor FragmentPagerAdapter(FragmentManager) is undefined
public Fragment getItem(int arg0) {
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putInt(“current_page”, arg0+1);
myFragment.setArguments(data);
return myFragment;
}
–> Fragment is giving next error:
The return type is incompatible with FragmentPagerAdapter.getItem(int)
Mainactivity.java
FragmentManager fm = getSupportFragmentManager();
–> getSupportFragmentManager is giving next error:
Type mismatch: cannot convert from android.support.v4.app.FragmentManager to android.app.FragmentManager
Can you help me please?
I’m getting the same error too…
Someone please help!
me too…getting same error..
Is there anybody to help…plz
Ok…I got it guys…
In MainActivity.java…extends FragmentActivity..
That’s we wrong…
It is very wonderful tutorial…Thank u very much!
Also, we need to ensure that, the Android classes Fragment, FragmentManager etc are imported from supported library
Hi !
Nice Guide!
But how do you specify the different pages in the onCreateView ?
Thanks !
Thnks for provding me this owesume tutorial
Thanks for nice tutorial, can i save data on diffrent screens like form or setting data ?
Thanks
How can update die TextView after onActivityCreated
This is a very good tutorial. Thank you!
in main activity my getSupportFragmentManager(); give an error ?
how can i set a different layout for each page id
Great share. Learnt something new today. Thanks.
Hello, I downloaded the source code and imported it into Ecliplse, however it is not working. It was working a couple of months ago, but it is not anymore. This is the logcat:
06-27 22:34:15.252: W/dalvikvm(765): Unable to resolve superclass of Lin/wptrafficanalyzer/viewpagerdemo/MainActivity; (3)
06-27 22:34:15.273: W/dalvikvm(765): Link of class ‘Lin/wptrafficanalyzer/viewpagerdemo/MainActivity;’ failed
06-27 22:34:15.273: D/AndroidRuntime(765): Shutting down VM
06-27 22:34:15.322: W/dalvikvm(765): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-27 22:34:15.332: E/AndroidRuntime(765): FATAL EXCEPTION: main
06-27 22:34:15.332: E/AndroidRuntime(765): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.viewpagerdemo/in.wptrafficanalyzer.viewpagerdemo.MainActivity}: java.lang.ClassNotFoundException: Didn’t find class “in.wptrafficanalyzer.viewpagerdemo.MainActivity” on path: /data/app/in.wptrafficanalyzer.viewpagerdemo-1.apk
Hello,
The source code is rebuild and updated the article
Thank you very much. It works now.
Can you please tell me what was wrong with the previous version? Why was it getting the error?
From ADT plugin 22.0.1 onwards, we need to ensure that, “Android Private Libraries” is checked in “Properties -> Java Build Path -> Order and Export tab”
thanks for your tutorial.I have a question.now i have many text save in sqlite
first question:
.so how to load text in sqlite on each page in Fragment?
second question:
how to save current postion of page i’m reading and can restore it when i came back.sorry my bad english.I hope received your feedback.
Thank you so much!
Hi,
How can I implement auto swipe (forward) after 10 seconds if the user doesn’t do anything?
Thanks a lot in advance.
Fikru
Great tutorial! Thanks.
Is it possible to implement it like the google play? That means when you scroll the tab, the page won’t be changed. The page only be changed when you click on the tab.
Hi Sir George, I am wondering if you could do a tutorial that puts a google map v2 on one of the fragments. Thanks!
Hey, great tutorial. Can you guide me how to add a new page on selecting a list item from previous page.
E.g. I’ve a list of folders on page#1 on clicking any folder it should open in page#2 so that user can swipe between pages easily.
how we can swipe image only not the text?
is there any way to change th textview in tabs to webview.
Thank you for this tutorial, It’s very good
problem of Restore UI in fragment when viewpager is used with nested fragments
have any solution with pagerFragment adapter
HI
how can create project have side menu navigator and tabhost in the same fragment
best regard
thanks a lot for source code
اجرکم عندالله
how can i set a different layout for each page id?
please help me!
Thank you very much, It’s helpful for me
Great code, worked for me very nicely……Thanks
hello sir , thats a very nice tutorial u have explained here , but i have a problem in mine , i want to display images in my viewpager , but i have problems displaying my image , if u could help me a little bit , it would be of a great help to me
please reply so that i can post my demoapp here or on your emailid
thanking you
How to change the font of Pager Title Strip. Could you share code for that.
Sir, is it possible to extend “MyFragment” class to Activity instead of fragment
help me please ! i get error on return myFragment
@Override
public Fragment getItem(int arg0) {
MyFragment myFragment = new MyFragment();
Bundle data = new Bundle();
data.putInt(“current_page”, arg0+1);
myFragment.setArguments(data);
return myFragment;
}
Hello!!
Thank you for de tutorial. I´ve got a question. It´s posible to give the tabs a circle aspect?
Thanks!!
hello george,
i create 4 fragment inside 5 static radio button for ON/OFF along with respective radiogroup,in this when i clicking the radio button it will send sms message to relevant number.when i swipe the fragments,and clicking the sms then when i swipe to previous one,it taking as a new fragment sending the sms repeadtly..how to resolve this,please help out in this
Hey! Is there any way to add images above text. I want to add images but there is no option available.
sir ,how to insert data int two table using one database
plz reply
plz tell me how can i use sqlite for getting required data each time when user swipe the page
Hi,
I need to implement both horizontal and vertical for the same content. Please help me how it can be achieved?