Search This Blog

Tuesday 9 October 2012

Viewpager Example in android

Viewpager  is  the best way to switching among view. It provide a way to swipe views from left to right and right to left. Viewpager provide strong way to swipe any views but here i have taken ImageView to swipe left and right.

Viewpager is strong widget as well as very simple. So here we go step wise solution  with explanation.

Add the support library while you are creating project because Viewpager does not support in lower android version 


Step 1) After creating a fresh project. change your main.xml to as follow so that it have one Viewpager widget in it.


<?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/myfivepanelpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


Step 2) Now our main concern is to bind data inside a Viewpager so that you can easily swipe. PagerAdapter bind the data to Viewpager and create view dynamically when needed. In PagerAdapter we remove the view as soon as its use is over so that we can avoid memory wastage . So create one new class and paste below code inside it.


package com.horizontalscrollviewwithpageindicator;

import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ViewPagerAdapter extends PagerAdapter {

 Activity activity;
 int imageArray[];

 public ViewPagerAdapter(Activity act, int[] imgArra) {
  imageArray = imgArra;
  activity = act;
 }

 public int getCount() {
  return imageArray.length;
 }

 public Object instantiateItem(View collection, int position) {
  ImageView view = new ImageView(activity);
  view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.FILL_PARENT));
  view.setScaleType(ScaleType.FIT_XY);
  view.setBackgroundResource(imageArray[position]);
  ((ViewPager) collection).addView(view, 0);
  return view;
 }

 @Override
 public void destroyItem(View arg0, int arg1, Object arg2) {
  ((ViewPager) arg0).removeView((View) arg2);
 }

 @Override
 public boolean isViewFromObject(View arg0, Object arg1) {
  return arg0 == ((View) arg1);
 }

 @Override
 public Parcelable saveState() {
  return null;
 }
}

Step 3) This is the final step and Viewpager complete. As in PagerAdapter , i have created one ImageView to display as child of Viewpager so we need one image array to show image. I have image in my drawable folder. I created one array like this


private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
   R.drawable.antartica3, R.drawable.antartica4,
   R.drawable.antartica5, R.drawable.antartica6,
   R.drawable.antartica7, R.drawable.antartica8 };

Now we just need to attach our PagerAdapter to android Viewpager . So we will change our main activity code to as following ---


package com.horizontalscrollviewwithpageindicator;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class PageIndicatorActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ViewPagerAdapter adapter = new ViewPagerAdapter(this, imageArra);
  ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
  myPager.setAdapter(adapter);
  myPager.setCurrentItem(0);
 }

 private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
   R.drawable.antartica3, R.drawable.antartica4,
   R.drawable.antartica5, R.drawable.antartica6,
   R.drawable.antartica7, R.drawable.antartica8 };

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

}

See the video to get perfect idea about what's the outcome will be. And if you are not able to follow the above procedure than no need to worry. Just download the source code and play with it


                                                         
                                                       

Download Source Code

13 comments:

  1. very nice tutorial , i need your help when i place my images which is high definition image with large size it gave me this exception :
    java.lang.OutOfMemoryError: bitmap size exceeds VM budget.
    any advice please how to fix it , im new to android development ,
    thanks

    yours :
    androidqq6

    ReplyDelete
    Replies
    1. Thank you..Use my Ahmad Image Downloader> to download big images. Or If you getting error while displaying image then see Scaling Image To avoid Memory Error

      Delete
  2. I looked on Scalling image to avoid Memory Error , but i cant implemented to your code coz im new to android please help me with some code .thanks

    ReplyDelete
  3. i tried to apply the method in (Scalling Image To avoid Memory Error) to above code , but i think my way not calling the method to scale the image for some reason , please help me by fixing that , really appreciated , thanks.
    my code attempt :

    public class ViewPagerAdapter extends PagerAdapter {

    Activity activity;
    int imageArray[];

    public ViewPagerAdapter(Activity act, int[] imgArra) {
    imageArray = imgArra;
    activity = act;
    }

    public int getCount() {
    return imageArray.length;
    }

    public Object instantiateItem(View collection, int position) {
    ImageView view = new ImageView(activity);
    view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
    LayoutParams.MATCH_PARENT));
    view.setScaleType(ScaleType.CENTER_CROP);
    view.setBackgroundResource(imageArray[position]);
    ((ViewPager) collection).addView(view, 0);
    return view;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
    ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
    return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
    return null;
    }
    public static Bitmap decodeSampledBitmapFromResource(String imageArra,
    int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(imageArra, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(imageArra, options);
    }


    public static int calculateInSampleSize(
    BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
    if (width > height) {
    inSampleSize = Math.round((float)height / (float)reqHeight);
    } else {
    inSampleSize = Math.round((float)width / (float)reqWidth);
    }
    }
    return inSampleSize;
    }
    }

    ReplyDelete
  4. Hi,
    In all examples until now, isViewFromObject is only implemented as "return arg0==arg1;". It works fine, of course, but it's interesting what else be done in this method? Can Views be reused, like with ListView?

    ReplyDelete
    Replies
    1. Hi Ilya,
      We can not reuse View in sider Viewpager like ListView. As it keeps maximum of Three view. And then reload if its goes from these three. If you does not remove the then, it will waste the memory

      Delete
    2. That is understood, i'm just looking at documentation that says that PagerAdapter is more general from ViewAdapters allowing and requiring me to manually add/remove views and also keeps track by Objects instead of views. But how can I use that power, except like in example?
      I can add more than one view to Pager in instantiateItem, I could do different compare in isViewFromObject, but I can't really think of any useful trick it can allow me.

      Delete
    3. First of all, i thank you for such worthy discussion.But AFAIK, it can not work like ListView. I request you to come on Tech Trainer FaceBook

      Delete
  5. Hi,
    Nice tutorial..Working great...!!
    But if now i want to add zoom functionality with View Pager. Actually I have searched for it and I get the solution in form of TouchImageView file.

    Now, zooming is done but the image cuts when it is zooed.

    Please help...Thanks in advance.







    ReplyDelete
    Replies
    1. Hi,
      Yes it will cut, Currently i am working on it to make pinch zoom gallery. As soon as i complete, will let you know. Keep visiting

      Delete
  6. Thanks for such a nice tutorial, here on different screens how do i save some data like a form or setting? i want to put this screens where user can enter data and instead of pressing next he or she just need to swipe the screen to go in next screen. How do i achieve this? is that possibble?

    Thanks

    ReplyDelete
    Replies
    1. Yes it can be done. In view pager you can change the pages on swipe or dynamically using code.

      Delete

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code