Friday, 7 August 2015

Image Slide Show Using View Pager

Hello Guys,

In my previous post we have seen the example of Gallery Widget. Today I show you how to use View Pager for display images and scroll like our mobile phone.

Here only widget is different but the purpose is same.

With the help of View Pager you can display any components like Images, Buttons, Text and son on.

View Pager is working like slider.

Sample Code:

File: activity_view_pager.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/bg">

    <android.support.v4.view.ViewPager
        android:id="@+id/mypanelpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"/>
    
</LinearLayout>

File: ViewPagerActivity.java

package com.sneha.viewpagerdemo;

import android.app.Activity;
import android.os.Bundle;
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 ViewPagerActivity extends Activity
{
private int myImages[] = {R.drawable.gallery_photo_1, R.drawable.gallery_photo_2,
  R.drawable.gallery_photo_3, R.drawable.gallery_photo_4,
  R.drawable.gallery_photo_5, R.drawable.gallery_photo_6};

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

ViewPagerAdapter adapter = new ViewPagerAdapter(this, myImages);
ViewPager myPager = (ViewPager) findViewById(R.id.mypanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}

public class ViewPagerAdapter extends PagerAdapter
{
Activity activity;

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

public int getCount() 
{
return myImages.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_CENTER);
view.setImageResource(myImages[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);
}
}
}

Output:














































Download Full Source Code: ViewPagerExample

Enjoy Coding...!!!

No comments:

Post a Comment