ViewPagers have built-in swipe gestures to transition through pages, and they display screen slide animations by default.
ViewPagers use PagerAdapters
as a supply for new pages to display. I simply put the images to drawable folder and display on it ViewPager
Swipe Image Gallery By ViewPager:


First you need to create the PagerAdapter.
ImageAdapter.java
import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class ImageAdapter extends PagerAdapter { Context context; private int[] GalImages = new int[] { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e, }; ImageAdapter(Context context){ this.context=context; } @Override public int getCount() { return GalImages.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((ImageView) object); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); //int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium); //imageView.setPadding(padding, padding, padding, padding); //imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setImageResource(GalImages[position]); ((ViewPager) container).addView(imageView, 0); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((ImageView) object); } }
Then create the xml file and add the ViewPager in layout.
<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"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Then create main Activity and create the instance of ViewPager
import android.app.Activity; import android.os.Bundle; import android.support.v4.view.ViewPager; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); ImageAdapter adapter = new ImageAdapter(this); viewPager.setAdapter(adapter); }
}
Stay Tune for next session happy coding :)
No comments:
Post a Comment