View Pager Example in Android Development

30

This example shows how you can create an image pager in android.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it ViewPagerExample.

2.) Write following into 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:orientation="vertical" >

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

</LinearLayout>

3.) Create and write following into res/layout/details.xml:

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

    <TextView
        android:id="@+id/detailsText"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal|center_vertical"
        android:layout_marginTop="20dip"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textSize="30dip" />

</LinearLayout>

4.) Create and write following into res/layout/details.xml:

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

5.) Create and Write following into src/DetailFragment.java:

package com.example.viewpagerexample;

import com.example.viewpagerexample.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class DetailFragment extends Fragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("Test", "hello");
	}

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

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.details, container, false);
		TextView textView = (TextView) view.findViewById(R.id.detailsText);
		textView.setText("Testing");
		return view;
	}
}

6.) Create and Write following into src/ImageFragment.java:

package com.example.viewpagerexample;

import com.example.viewpagerexample.R;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class ImageFragment extends Fragment {
	private final int imageResourceId;

	public ImageFragment(int imageResourceId) {
		this.imageResourceId = imageResourceId;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e("Test", "hello");
	}

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

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.image_layout, container, false);
		ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
		imageView.setImageResource(imageResourceId);
		return view;
	}
}

7.) Run for output.

Steps:

1.) Create a project named ViewPagerExample and set the information as stated in the image.

Build Target: Android 4.0
Application Name: ViewPagerExample
Package Name: com. example. ViewPagerExample
Activity Name: ViewPagerExample
Min SDK Version: 8

2.) Open ViewPagerExample.java file and write following code there:

package com.example.viewpagerexample;

import com.example.viewpagerexample.R;

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

public class ViewPagerExample extends FragmentActivity {
	private MyAdapter mAdapter;
	private ViewPager mPager;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mAdapter = new MyAdapter(getSupportFragmentManager());

		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(mAdapter);
	}

	public static class MyAdapter extends FragmentPagerAdapter {
		public MyAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				return new DetailFragment();
			case 1:
				return new ImageFragment(R.drawable.ic_launcher);
			case 2:
				return new ImageFragment(R.drawable.thumb);

			default:
				return null;
			}
		}
	}
}

3.) Compile and build the project.

Output

Did you enjoy this article?
Share
the
Love
Get Free Updates

30 Responses

  1. thomas says:

    Nice list of blogs to follow!

  2. abdullah ayyad says:

    wait , theirs two file of
    details.xml , on this example , how this work ??

  3. anonymous says:

    the 2nd xml file should be image_layout.xml

  4. christian says:

    the example is not completed , where is the complete source ?

  5. Niko says:

    Very useful! Thanks a lot!

  6. gabi says:

    do you know how can I make a button that I have added to xml on the 1st fragment work or open a new page

  7. gabi says:

    Hello, thank you very much for the tutorial to add the buttons on each fragment you may use:
    public class DetailFragment extends Fragment {

  8. gabi says:

    after that you can add the usual button code, however you have to be careful how the “intent” is defined

  9. Lesik Pidy says:

    THANK YOU!!!
    Your Tutorial is so great!
    I didn’t understand it for years of development!!!
    THANKS for sharing this simple tutorial with us!
    You are the best, love you!!

    Thank you, again! I am so happy now!

  10. Sean says:

    Great, Thanx

  11. Vishnu says:

    Yeah, this was i looking for….. Great tutorial……..

  12. John says:

    This is very good, however when I change the orientation of my phone the app crashes. Anyone have any ideas why? Here is the logcat:

    12-24 21:09:30.411: D/dalvikvm(18639): newInstance failed: no ()
    12-24 21:09:30.421: D/AndroidRuntime(18639): Shutting down VM
    12-24 21:09:30.421: W/dalvikvm(18639): threadid=1: thread exiting with uncaught exception (group=0x40028a00)
    12-24 21:09:30.451: E/AndroidRuntime(18639): FATAL EXCEPTION: main
    12-24 21:09:30.451: E/AndroidRuntime(18639): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.viewpagerexample/com.example.viewpagerexample.ViewPagerExample}: android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.jacoblever.view.pager.example.MenuFragment: make sure class name exists, is public, and has an empty constructor that is public

    Thanks

  13. ninjaboy says:

    why does the app stop working or crash when i tried it on the emulator

  14. Andy Res says:

    Very clean and nice example. thanks.

  15. Katrina says:

    Hi, very nice example, but how can I zoom and pan the images in this viewpager?
    Thanks in advance!

    Regards,
    Katrina

  16. Praveen Pandey says:

    great tutorial …. Thanks ….

  17. Raja Rajan says:

    Nice tutorial..It’s help me so much..thank u.

  18. Mihai says:

    Crash if change to landscape mode. Any solution, without disabling orientation?

  19. Mihai says:

    OK, I’ve fixed it, removing arguments from ImageFragment fix the issue.

  20. VeeJay says:

    Thank you so much. I have been struggling like anything for the past 5 days to try this kind of example.

    Great post.

  21. maddy says:

    Hi,
    If i create i listview in one of the fragment and I want to refresh the listView after the fragment is created. how do i can do this. Thanks in advance.

  22. anon says:

    i still got error ,

    uncaught exception (group=0x4001d800)

    can you help me?

  23. Hi guys,

    Thanks Sushant, for your sample.
    It didn’t work at first but I managed to get it working.
    I also included an image to replace that drawable.thumb I couldn’t find

    For anyone asking for the complete source, here follows:
    http://www.scottx.net/android_samples/ViewPagerExample.zip

    I have this sample which is almost everything I want to do but lacks zoom:
    http://developer.android.com/training/displaying-bitmaps/index.html

    And I also have this great sample which has pinch-zoom:
    https://github.com/sephiroth74/ImageViewZoom

    Now modified by me with a double tap listener zooming to image at 100%:
    http://www.scottx.net/android_samples/ImageViewTouch.zip
    offtopic: The girl in the photo included in this sample is my neighbour :)

    Now what I would like to do is either put the ImageViewTouch on a Pageviewer like the sample explained on this page so a user can swipe the image to see the next photo keeping the zooming capabilites, or use the first sample from Google but with zooming.

    Could anyone give a little help here?

    Thank you so much :)
    Ricardo Santos

  24. Nayeem says:

    Thanks, it worked for me! Had to change few things though.

  25. Kamlesh Bobde says:

    very good and useful example….Thanx a lot

  26. Ahsan says:

    Hey , thanks for this. I have 2 problem, hope you can help. I want the pager to go from left to right(not sure how to do that) and when the screen orientation changes it closes out the page. Can you please help me with these 2 issue. Thanks in advance

  27. phanan says:

    How can we make TextView of details.xml show something from database?

  28. phanan says:

    And can we build page4 with graphic?

  29. Ajay B says:

    Nice post. I like the example.
    In ImageFragment.java “imageResourceId” should not be defined as final.

  30. Csxman says:

    Thank Nice Exam !!

Leave a Reply


× five = 30

Proudly designed by Theme Junkie.