Image Slider Android

To slide one entire screen to another screen, the image slider is used in Android which is created by the ViewPager. The support library provides the ViewPager. The ViewPager class must be inherited to implement an image slider. It extends the PagerAdapter.

Example of Image Slider:


The ViewPager is wrapped inside the RelativeLayout, in the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
       android:layout_height="fill_parent" />

Activity class:(File:

package com.example.radioapp;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   protected void onCreate(Bundle savedInstanceState) {
       ViewPager mViewPager = (ViewPager) findViewById(;
       ImageAdapter adapterView = new ImageAdapter(this);

ImageAdapter class:(File:

To extend the PagerAdapter for an android image slider, we will create the ImageAdapter class. While the images to be slid are placed in the drawable folder.

package com.example.radioapp;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter{
   Context mContext;
   ImageAdapter(Context context) {
       this.mContext = context;
   public boolean isViewFromObject(View view, Object object) {
       return view == ((ImageView) object);
   private int[] sliderImageId = new int[]{
 , R.drawable.php
   public Object instantiateItem(ViewGroup container, int position) {
       ImageView imageView = new ImageView(mContext);
       ((ViewPager) container).addView(imageView, 0);
       return imageView;
   public void destroyItem(ViewGroup container, int position, Object object) {
       ((ViewPager) container).removeView((ImageView) object);
   public int getCount() {
       return sliderImageId.length;

The PagerAdapter class has certain methods that need to be overridden. We are describing these methods below:

isViewFromObject(View, Object) method:

Use: The isViewFromObject(View, Object) method is used to check the View i.e, to determine whether the View is associated with a key and is returned by instantiateItem().

instantiateItem(ViewGroup, int) method:

Use: The instantiateItem(ViewGroup, int) method is used to create the page position passed as an argument.

destroyItem(ViewGroup, int, Object) method:

Use: The destroyItem(ViewGroup, int, Object) method is used to eliminate the page from its current position from the container. However, in the above example, we used the removeView() method to remove the object.

getCount() method:

Use: The getCount() method is used to get the number of available views in the ViewPager.

Output 1:

Output 2:


Please follow and like us:
Content Protection by