Android Image Slider Using ViewPager

Android Image Slider Using ViewPager

You have seen many Android apps with sliding images with circle page indicator at top. Today we are going to learn the same thing for our app.

Before proceeding we need a superb library called ViewPagerIndicator-Library that we can get from Github created by JakeWhartom. Just download it and import the library into your project.

We are going to use ViewPager for Sliding the images so if anyone of you are unaware of viewpager can go and check my tutorial about ViewPager.

Features of this app:

  • Slide images by swiping left and right.
  • Automatic image sliding at particular duration.

Video Demo

Let’s start with the Example:

1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.

2. First create an xml layout file naming activity_main.xml that contains viewpager and CirclePageIndicator that is provided by JakeWhartom library.

3. Now create a new xml layout naming slidingimages_layout.xml that contains an ImageView. It is custom view for our images placing.

4. For custom view we have to create a java file for connecting the custom view with the user interface. I named the class SlidingImage_Adapter.java extending PagerAdapter since we are dealing with ViewPager. This class just fetch the Images from Array and display over imageView and rest will be handled by viewpager.

5. Finally come to your MainActivity.java and add the following code. In this class at start we set the Timer that changes the images at particular interval of time and also when user swipes the viewpager will change the next image.

6. Now, you are all done, run your app and you will get the output as shown in video.

Thanks. :)

Download Source Code – >

 

Download this ViewPagerIndicator-Library compatible to Android Studio. This  is converted library in build.gradle format so you can download it and directly import into your project.

Thanks

 

COMMENTS (59)
Reply

Hello . ive tried your code. It works like a charm but when i open new activity and press back button it crashes because the viewpager notifychanged is not called and it found 0 instead of 10. How can i resolved it.

    Reply

    Hi,

    Try to use FragmentPagerAdapter instead of PagerAdapter.

Reply

Sir if I want to click the image and go to some url then how can i achieve that? Thank You.

    Reply

    Hi Rahul,

    Inside “instantiateItem” method do the following –

    imageview.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    //Here you can do your stuff
    }
    });

    Thanks

Reply

How can I get it done in AndroidStudio as ViewPagerIndicator library works for Eclipse Maven.

    Reply

    Hi Sakshi,

    Just download the viewpager library from above mentioned link and include library file in your project as you include other libraries. Try this.

    Thanks

Reply

I am not able to import the ViewPagerIndicator-Library so any one please help me? tell me how will i do this step by step in android STUDIO 1.0

    Reply

    HI Mutaza,

    Follow the below steps to use library in Android Studio –

    1. Download the ViewpagerIndicator-Library from above location.
    2. Extract the folder and copy the library folder from the extracted folder.
    3. Create a folder inside root directory of your project naming ‘libraries’ or any other name and paste the copied library in that created folder.
    4. Open ‘setting.gradle’ and add the below line and click on ‘sync now’ to build gradle.
    include ‘:app’,’:folder_path:library’
    5. Now come to build.gradle in app directory and under ‘dependencies’ add the below line and click on sync now:
    compile project(‘:folder_path:library’)
    6. Now you are all done to use the ViewPager Library.

    Note: Here folder_path is a path where you pasted the copied library from extracted file.

    Hope it helps.

    Thanks.

      it doesn’t work for me can u give me code without indicators ? my email is gmpanh@gmail.com

      i guess build.gurdle file is missing in library folder as when i sync it give me error Error:Configuration with name ‘default’ not found.
      I don’t know how to solve it 🙁

        I am getting the same error. Can you please elaborate on what changes did you make. Thanks in advance.

          I am also getting the same error. Have any solution anyone?

      Never mind i make this thing work. but it lags on large images do u have any idea to fix lags ?

        I am getting the same error. Can you please elaborate on what changes did you make. Thanks in advance.

Reply

Hi to all,

I saw most of the peoples are facing issue in Library. So i uploaded new library and link is given at below source code. So download it from there and use it in your app.

Thanks

Reply

I am not able to import library ViewPagerIndicator-Library
during gradle sync following error occurs:
failed to find target with hash string ‘android-15’ android studio

Kindly revert me asap
thanks in advance 🙂

    Reply

    Hi Khushi,

    Actually you can directly search the error on Google and you will get some solutions over stackoverflow.com. Its basically due to some compileSdkVersion problem.

    Thanks

      okay !

Reply

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import com.viewpagerindicator.CirclePageIndicator;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
private static ViewPager mPager;
private static int currentPage = 0;
private static int NUM_PAGES = 0;
private static final Integer[] IMAGES= {R.drawable.img1,R.drwable.img2,R.drawble.img3};
private ArrayList ImagesArray = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
for(int i=0;i<IMAGES.length;i++)
ImagesArray.add(IMAGES[i]);

mPager = (ViewPager) findViewById(R.id.pager);

mPager.setAdapter(new SlidingImage_Adapter(MainActivity.this,ImagesArray));

CirclePageIndicator indicator = (CirclePageIndicator)
findViewById(R.id.indicator);

indicator.setViewPager(mPager);

final float density = getResources().getDisplayMetrics().density;

//Set circle indicator radius
indicator.setRadius(5 * density);

NUM_PAGES =IMAGES.length;

// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);

// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
currentPage = position;

}

@Override
public void onPageScrolled(int pos, float arg1, int arg2) {

}

@Override
public void onPageScrollStateChanged(int pos) {

}
});

}

}

m getting this error..
please some one help

    Reply

    cannot resolve symbol viewpagerindincator, circleindicator, setradius5, r

      Hi Payal,

      Had you imported ViewPagerIndicator – Library in your Project?

Reply

How to import ViewPagerIndicator libraryin android studio.I tried to add under dependency

    Reply

    Hi Darsh,

    1. Download the Library from Given Link.
    2. Copy the directory and paste in your project .
    3. Now open settigs.gradle and add the path of copied library like ‘:path_:library_name’ and sync the project.
    4. Now select app in project and press ‘command + below arrow’ is using mac else press ‘F4’ in windows and open dependency tab and click on ‘+’ button and select module dependency and select library and press ok.
    5. All Done.

    Thanks.

Reply

hi
how add libraries to android studio??

Reply

very nice tutorial thanks.
how to add url image instead of drawable mage

Reply

Hi, Nice Tutorial. I trying to implement this in fragment. I also changed the PagerAdapter to FragmentPagerAdapter. But still some errors are popping. Please guide me.

Thank you

    Hi Sankar,

    Can you please let me know your actual issue means what kind of error is popping. You can contact me via surender@androhub.com.

    Thanks

      I can able to get output using PagerAdapter itself. But now I got the error as,

      java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.Object android.content.Context.getSystemService(java.lang.String)’ on a null object reference

Reply

java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.Object android.content.Context.getSystemService(java.lang.String)’ on a null object reference at android.view.LayoutInflater.from(LayoutInflater.java:229)

Pls check the email id (surender@androhub.com) is still in active, i tried to mail you, but failed.

Reply

Thnxs for tutorial really great tutorial helps me a lot.
but can u tell me it is open source like can i used it in my project ?

    Hi Madhav,

    Yes you can use it in your project and its totally open source. 🙂

    Thanks

Reply

hello Dr. can u tell me how can i add pinch zoom +drag effect in image view in view pager

Reply

when i scroll fast in view pager image can’t be display like blank view is set.

can you please provide me solution for this.

Reply

Same error First image is showing blank

    Hi Shivangi,

    Please extend SlidingImage_Adapter class with FragmentStatePagerAdapter instead of PagerAdapter and try it.
    Good Luck!!

    Thanks

Reply

It works pretty awesome… Thanks a lot for both the source code and the Library and how to import the library… Thanks!

    Hi Jagannathan,

    Follow the below steps to import library in Android Studio –

    1. Download the ViewpagerIndicator-Library from above location.
    2. Extract the folder and copy the library folder from the extracted folder.
    3. Create a folder inside root directory of your project naming ‘libraries’ or any other name and paste the copied library in that created folder.
    4. Open ‘setting.gradle’ and add the below line and click on ‘sync now’ to build gradle.
    include ‘:app’,’:folder_path:library’
    5. Now come to build.gradle in app directory and under ‘dependencies’ add the below line and click on sync now:
    compile project(‘:folder_path:library’)
    6. Now you are all done to use the ViewPager Library.

    Note: Here folder_path is a path where you pasted the copied library from extracted file.

    Hope it helps.

    Thanks.

Reply

hi it works but when i slide with view pager and slide back the cirlce indicator adding automatically , example : before there is 3 page indicator , after slide there is 6 page indicator .., why??

    Hi Duke,

    There might be some issues in your code like:
    1. You are adding pages dynamically.
    2. You are calling adding pages again.

    So please check your code using LOGS and go through it again and try. If nothing is happening just contact me at my mail id (sonu.surendra0@gmail.com). I will help you.

    Thanks

Reply

how to load images from internet for this

      thanks man i got you but could you please tell me how to use that library in your code which you have written above, it would be quite helpful. thanks

    Hi VIPS again,

    Step by Step to use Picasso library in project:
    1. First of all add this compile ‘com.squareup.picasso:picasso:2.5.2’ library dependency in your app level gradle file and sync the gradle.
    2. After successful syncing change the below code:

    final ImageView imageView = (ImageView) imageLayout
    .findViewById(R.id.image);
    Picasso.with(context).load(image_url).into(imageView);

    That’t it. You good to go.

    Thanks

      as this is a viewpager so i would need more than one images so in that case where should i write all those urls .thanks

    Hi VIPS,

    As you saw my code i am using Integer ArrayList for displaying images from resources, so now in your case you have to take String ArrayList and add all the URL’s to arrayList.
    After adding you have to use below code:

    Picasso.with(context).load(IMAGES.get(position)).into(imageView);

    By using this you can display your URLs into imageview.

    Thanks

      thank you very much i would like to contact you further if there is any issue on this

      i can not import library indicator

      Hi VIPS,

      Please download the library from the link that i provided end of the article and make sure you FOLLOW the steps i mentioned in article.

      Thanks

      sir after a lot of mess i am not able to complete the project sir could you please send me the source code with the parts where i need to edit and i don’t want the viewpagerindicator as it is not compatible for unknown reasons so only send the code where i need to edit to get my work done.it would be a great help sir my email is: vipssingh53@outlook.com, thanks

      thank you very much sir you have been so kind to me it would help me a lot in completing my project in time

Reply

Hi there,

This is fantastic, thank you so much for you work!

I wanted to ask, in my project I have a bottom navbar that loads a fragment into a fragment container as each item is clicked and for this reason I need to put this code into something that will work in a fragment. Might you be able to provide the code for this and I was also wondering if the adapter would need to be a fragment as well or can that stay as it is ?

Kind regards,

Daveak

Reply

Hi Dr Droid,

So I don’t use a Navigation Drawer in my project, I use a bottom bar like the one here: https://material.google.com/components/bottom-navigation.html#bottom-navigation-usage

Basically when the app loads it loads a fragment container in the main activity and when a user clicks on a button in the navigation menu it fills that container with a new fragment for that button. What I wanted to do for the first button was load an image slider like the one you have created, however the code you have above is for implementing this directly into the main activity, ideally I wanted this code to run in the new fragment that is loaded.

Not to worry if this is too much work, thought it might be worth asking in case it’s only a few lines that need to change, but don’t worry if it’s a lot of work. Thanks very much for getting back to me either way, please do keep up the great work with your tutorials!

Kind regards,

Daveak

Reply

Hi Dr Droid,

I finally got it working thanks to your amended code to suit a fragment!!!!

Honestly can’t believe you had re-written the code to support this challenge and truly appreciate your support. I will likely need some development assistance in the future on projects and will certainly be requesting your assistance for some contract work.

Thank you so much again for your help, please do keep up the good work!

Kind regards,

Daveak

Reply

As many people got stuck in adding library in android studio just follow this step :

Add it in your build.gradle at the end of repositories:
Step 1
allprojects {
repositories {

maven { url “http://dl.bintray.com/populov/maven” }
mavenCentral()
jcenter()

}
}
Step 2. Add the dependency in the form

dependencies {
compile ‘com.viewpagerindicator:library:2.4.1@aar’
}

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Name (required)
Email (required)