Android Image Slider Using ViewPager - Androhub

Image Slider

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.

And, before we start, If you are looking for Android developer jobs, you can find it on Jooble.

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 the video.

Thanks. :)

 

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

Thanks

 

102 Comments

Denise
Sunday, January 10th, 2016

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.

Droid
Sunday, January 10th, 2016

Hi,

Try to use FragmentPagerAdapter instead of PagerAdapter.

RAHUL
Tuesday, January 12th, 2016

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

Droid
Tuesday, January 12th, 2016

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

Sakshi
Wednesday, January 27th, 2016

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

Droid
Monday, February 22nd, 2016

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

Murtaza
Monday, February 29th, 2016

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

Droid
Monday, February 29th, 2016

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.

Murtaza
Monday, February 29th, 2016

it doesn’t work for me can u give me code without indicators ? my email is [email protected]

Murtaza
Tuesday, March 1st, 2016

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 🙁

Tushar
Sunday, March 6th, 2016

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

Lily
Tuesday, March 8th, 2016

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

Murtaza
Tuesday, March 1st, 2016

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

Tushar
Saturday, March 5th, 2016

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

Droid
Tuesday, March 8th, 2016

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

khushi
Saturday, April 16th, 2016

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 🙂

Dr. Droid
Saturday, April 16th, 2016

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

khushi
Monday, April 18th, 2016

okay !

Payal
Monday, April 25th, 2016

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

Payal
Monday, April 25th, 2016

cannot resolve symbol viewpagerindincator, circleindicator, setradius5, r

Dr. Droid
Monday, April 25th, 2016

Hi Payal,

Had you imported ViewPagerIndicator – Library in your Project?

Darsh
Monday, May 2nd, 2016

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

Dr. Droid
Monday, May 2nd, 2016

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.

armin
Monday, June 27th, 2016

hi
how add libraries to android studio??

droid
Tuesday, June 28th, 2016

Hi Armin,

Please check this youtube link to Add Libraries in Android Studio : https://www.youtube.com/watch?v=1MyBO9z7ojk

Thanks

karthikeyan
Monday, July 18th, 2016

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

Dr. Droid
Monday, July 18th, 2016

Hi Karthikeyan,

For loading url in image view you have to use some libraries like UniversalImageLoader-Library, Picasso,Glide, etc.

These libraries help in Image Caching also.

Thanks

Sankar
Thursday, July 21st, 2016

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

Dr. Droid
Thursday, July 21st, 2016

Hi Sankar,

Can you please let me know your actual issue means what kind of error is popping. You can contact me via [email protected].

Thanks

Sankar
Thursday, July 21st, 2016

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

Sankar
Thursday, July 21st, 2016

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 ([email protected]) is still in active, i tried to mail you, but failed.

madhav
Friday, August 5th, 2016

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 ?

Dr. Droid
Friday, August 5th, 2016

Hi Madhav,

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

Thanks

madhav
Saturday, August 6th, 2016

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

Dr. Droid
Saturday, August 6th, 2016

Hi Madhav ,

Check out this Github Library : https://github.com/chrisbanes/PhotoView.

Thanks

madhav
Sunday, August 7th, 2016

It work well but when i scroll fast image cannot be display means blank image is set

madhav
Friday, August 12th, 2016

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.

shivangi
Wednesday, August 24th, 2016

Same error First image is showing blank

Dr. Droid
Wednesday, August 24th, 2016

Hi Shivangi,

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

Thanks

Jagannathan
Friday, September 9th, 2016

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

Dr. Droid
Friday, September 9th, 2016

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.

duke
Tuesday, September 20th, 2016

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??

Dr. Droid
Tuesday, September 20th, 2016

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 ([email protected]). I will help you.

Thanks

vips
Tuesday, October 18th, 2016

how to load images from internet for this

Dr. Droid
Tuesday, October 18th, 2016

Hi VIPS,

Please follow the below link to Load Images from Internet:
http://square.github.io/picasso/

use this library in your project.

Thanks

vips
Wednesday, October 19th, 2016

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

Dr. Droid
Wednesday, October 19th, 2016

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

vips
Wednesday, October 19th, 2016

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

Dr. Droid
Wednesday, October 19th, 2016

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

vips
Wednesday, October 19th, 2016

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

vips
Wednesday, October 19th, 2016

i can not import library indicator

Dr. Droid
Wednesday, October 19th, 2016

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

vips
Thursday, October 20th, 2016

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: [email protected], thanks

vips
Thursday, October 20th, 2016

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

Daveak
Thursday, October 20th, 2016

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

Dr. Droid
Friday, October 21st, 2016

Hi Daveak,

I think you are looking for Navigation Drawer/View with fragments?
Here are some links just look into it, if it helps 🙂
1. Navigation View: https://www.androhub.com/navigation-view-material-design-support-library-tutorial/
2. Navigation Drawer: https://www.androhub.com/android-navigationdrawer/

In above links there is logic of implementing fragments with adapter.

Thanks

Daveak
Sunday, October 23rd, 2016

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

Daveak
Wednesday, October 26th, 2016

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

Saurabh
Friday, November 4th, 2016

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’
}

kinsley kajiva
Wednesday, January 18th, 2017

Hi thanx for the tutorial it has really helped me a lot but i faced a change that the First image was only showing but was not showing others even tho the thread was being called.

i resolved the problem i noticed that you declared private static ViewPager mPager; whis is not the good way of declaring view according to google we should reduce memory leaks in android . This sort of declaration causes memory leaks avoid declaring views static will cause run-time memory leaks ,hence it also hindered the scroll of images so i declared like this private ViewPager mPager; with out the static statement

Thanx for the lesson tho.

Tejas Gawali
Thursday, March 2nd, 2017

Awesome tutorial I was trying this since last 3 days but your tutorial made it very easy.

thanks

Neo
Monday, May 15th, 2017

How can we change this into slide the images automatically. I’ve image slider perfectly working, but i need to make it slide automatically in a particular time period(say 1000ms)

Dr. Droid
Monday, May 15th, 2017

Hi Neo,

If you have check my code. In MainActivity.java class line number 49 you will find below code:

// 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);

This code is responsible for Automatic Image Sliding after 3sec. You can change 3000 into 1000 or any other time duration.
Hope this will help you.

Thanks.

jiten
Saturday, July 22nd, 2017

I want to fetch images from server using retrofit-gson-glide ,then display them in view pager with zoom and pan ability.how can I do it?

Dr. Droid
Saturday, July 22nd, 2017

Hi Jiten,

To fetch images from server using Retrofit – GSON follow this link : http://square.github.io/retrofit/
and for displaying fetched image url using Glide follow this link : https://github.com/bumptech/glide
Finally you want to implement zoom and pan ability to your imageView for this follow this link : https://github.com/sephiroth74/ImageViewZoom

Actually i have not done any article on those so i am referring you those links.

Thanks

Prathyusha
Monday, February 12th, 2018

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ab.hdgodwallpapers.utils.HeavyLifter;
import com.ab.hdgodwallpapers.viewpagertransformers.AccordionTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.BackgroundToForegroundTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.CubeOutTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.DepthPageTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.FlipHorizontalTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.ForegroundToBackgroundTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.TabletTransformer;
import com.ab.hdgodwallpapers.viewpagertransformers.ZoomOutSlideTransformer;
/*import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest.Builder;
import com.google.android.gms.ads.InterstitialAd;*/
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ImagesActivity extends FragmentActivity {

private static final List backgrounds = new ArrayList();
private static final int TOTAL_IMAGES = (backgrounds.size() – 1);
static final int NUM_ITEMS = TOTAL_IMAGES;
private Handler chuckFinishedHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0 /* 0 */:
Toast.makeText(ImagesActivity.this, “Image Set as Wallpaper”, 0)
.show();
return;
case HeavyLifter.FAIL /* 1 */:
Toast.makeText(ImagesActivity.this,
“Opps !, can’t do that right now”, 0).show();
return;
default:
super.handleMessage(msg);
return;
}
}
};
private HeavyLifter chuckNorris;
private int currentPosition = 0;
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
/* private InterstitialAd interstitial; */
ViewPager viewPager;

public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}

public int getCount() {
return ImagesActivity.NUM_ITEMS;
}

public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}

public static class SwipeFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment,
container, false);
((ImageView) swipeView.findViewById(R.id.imageView))
.setImageResource(((Integer) ImagesActivity.backgrounds
.get(getArguments().getInt(“position”))).intValue());
return swipeView;
}

static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt(“position”, position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}

static {
backgrounds.add(Integer.valueOf(R.drawable.image_intro));
backgrounds.add(Integer.valueOf(R.drawable.image_01));
backgrounds.add(Integer.valueOf(R.drawable.image_02));
backgrounds.add(Integer.valueOf(R.drawable.image_03));
backgrounds.add(Integer.valueOf(R.drawable.image_04));
backgrounds.add(Integer.valueOf(R.drawable.image_05));
backgrounds.add(Integer.valueOf(R.drawable.image_06));
backgrounds.add(Integer.valueOf(R.drawable.image_07));
backgrounds.add(Integer.valueOf(R.drawable.image_08));
backgrounds.add(Integer.valueOf(R.drawable.image_09));
backgrounds.add(Integer.valueOf(R.drawable.image_10));
backgrounds.add(Integer.valueOf(R.drawable.image_11));
backgrounds.add(Integer.valueOf(R.drawable.image_12));
backgrounds.add(Integer.valueOf(R.drawable.image_13));
backgrounds.add(Integer.valueOf(R.drawable.image_14));
backgrounds.add(Integer.valueOf(R.drawable.image_15));
backgrounds.add(Integer.valueOf(R.drawable.image_16));
backgrounds.add(Integer.valueOf(R.drawable.image_17));
backgrounds.add(Integer.valueOf(R.drawable.image_18));
backgrounds.add(Integer.valueOf(R.drawable.image_19));
backgrounds.add(Integer.valueOf(R.drawable.image_20));
backgrounds.add(Integer.valueOf(R.drawable.image_21));
backgrounds.add(Integer.valueOf(R.drawable.image_22));
backgrounds.add(Integer.valueOf(R.drawable.image_23));
backgrounds.add(Integer.valueOf(R.drawable.image_24));
backgrounds.add(Integer.valueOf(R.drawable.image_25));
backgrounds.add(Integer.valueOf(R.drawable.image_26));
backgrounds.add(Integer.valueOf(R.drawable.image_27));
backgrounds.add(Integer.valueOf(R.drawable.image_28));
backgrounds.add(Integer.valueOf(R.drawable.image_29));
backgrounds.add(Integer.valueOf(R.drawable.image_30));
backgrounds.add(Integer.valueOf(R.drawable.image_31));
backgrounds.add(Integer.valueOf(R.drawable.image_32));
backgrounds.add(Integer.valueOf(R.drawable.image_33));
backgrounds.add(Integer.valueOf(R.drawable.image_34));
backgrounds.add(Integer.valueOf(R.drawable.image_35));
backgrounds.add(Integer.valueOf(R.drawable.image_36));
backgrounds.add(Integer.valueOf(R.drawable.image_37));
backgrounds.add(Integer.valueOf(R.drawable.image_38));
backgrounds.add(Integer.valueOf(R.drawable.image_39));
backgrounds.add(Integer.valueOf(R.drawable.image_40));
backgrounds.add(Integer.valueOf(R.drawable.image_41));
backgrounds.add(Integer.valueOf(R.drawable.image_42));
backgrounds.add(Integer.valueOf(R.drawable.image_43));
backgrounds.add(Integer.valueOf(R.drawable.image_44));
backgrounds.add(Integer.valueOf(R.drawable.image_45));
backgrounds.add(Integer.valueOf(R.drawable.image_46));
backgrounds.add(Integer.valueOf(R.drawable.image_47));
backgrounds.add(Integer.valueOf(R.drawable.image_48));
backgrounds.add(Integer.valueOf(R.drawable.image_49));
backgrounds.add(Integer.valueOf(R.drawable.image_50));
backgrounds.add(Integer.valueOf(R.drawable.image_51));
backgrounds.add(Integer.valueOf(R.drawable.image_52));
backgrounds.add(Integer.valueOf(R.drawable.image_53));
backgrounds.add(Integer.valueOf(R.drawable.image_thanks));
}

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_image);
/*
* this.interstitial = new InterstitialAd(this); this.interstitial
* .setAdUnitId(getString(R.string.interstitial_ad_unit_id));
* this.interstitial.loadAd(new Builder().build());
* this.interstitial.setAdListener(new AdListener() { public void
* onAdLoaded() { } });
*/
this.imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(
getSupportFragmentManager());
this.viewPager = (ViewPager) findViewById(R.id.pager);
this.viewPager.setAdapter(this.imageFragmentPagerAdapter);
this.viewPager.setPageTransformer(true, new ZoomOutSlideTransformer());
try {
Field mScroller = ViewPager.class.getDeclaredField(“mScroller”);
mScroller.setAccessible(true);
mScroller.set(this.viewPager,
new FixedSpeedScroller(this.viewPager.getContext()));
} catch (NoSuchFieldException e) {
} catch (IllegalArgumentException e2) {
} catch (IllegalAccessException e3) {
}
int primaryColor = Color.parseColor(“#FFFFFF”);
Drawable startBackground = getResources().getDrawable(
R.drawable.ic_back);
startBackground.setColorFilter(primaryColor, Mode.SRC_IN);
ImageView btnBack = (ImageView) findViewById(R.id.back);
Drawable previousBackground = getResources().getDrawable(
R.drawable.ic_left);
previousBackground.setColorFilter(primaryColor, Mode.SRC_IN);
((ImageView) findViewById(R.id.previous))
.setImageDrawable(previousBackground);
Drawable nextBackground = getResources().getDrawable(
R.drawable.ic_right);
nextBackground.setColorFilter(primaryColor, Mode.SRC_IN);
((ImageView) findViewById(R.id.next)).setImageDrawable(nextBackground);
btnBack.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ImagesActivity.this.onBackPressed();
}
});
btnBack.setImageDrawable(startBackground);
this.viewPager.setOnPageChangeListener(new OnPageChangeListener() {
public void onPageSelected(int arg0) {
int randomNumber = new Random().nextInt(8) + 1;
if (randomNumber == 1) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new ZoomOutSlideTransformer());
} else if (randomNumber == 2) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new BackgroundToForegroundTransformer());
} else if (randomNumber == 3) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new ForegroundToBackgroundTransformer());
} else if (randomNumber == 4) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new AccordionTransformer());
} else if (randomNumber == 5) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new CubeOutTransformer());
} else if (randomNumber == 6) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new DepthPageTransformer());
} else if (randomNumber == 7) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new FlipHorizontalTransformer());
} else if (randomNumber == 8) {
ImagesActivity.this.viewPager.setPageTransformer(true,
new TabletTransformer());
}
}

public void onPageScrolled(int arg0, float arg1, int arg2) {
}

public void onPageScrollStateChanged(int arg0) {
}
});
this.chuckNorris = new HeavyLifter(this, this.chuckFinishedHandler);
((TextView) findViewById(R.id.tvShare))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(ImagesActivity.this,
ShareActivity.class);
intent.putExtra(“key_image”,
(Serializable) ImagesActivity.backgrounds
.get(ImagesActivity.this.viewPager
.getCurrentItem()));
ImagesActivity.this.startActivity(intent);
}
});
((TextView) findViewById(R.id.tvWallpaper))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ImagesActivity.this.chuckNorris
.setResourceAsWallpaper(((Integer) ImagesActivity.backgrounds
.get(ImagesActivity.this.viewPager
.getCurrentItem())).intValue());
}
});
}

public void gotoPreviousImage(View v) {
if (this.viewPager.getCurrentItem() != 0) {
this.viewPager.setCurrentItem(this.viewPager.getCurrentItem() – 1);
}
}

public void gotoNextImage(View v) {
if (this.viewPager.getCurrentItem() != backgrounds.size() – 1) {
this.viewPager.setCurrentItem(this.viewPager.getCurrentItem() + 1);
}
}
}

This is my class and below is the error.please help me in fixing this error.

02-12 13:15:37.467: D/ImageLoader(456): Initialize ImageLoader with configuration
02-12 13:15:37.597: I/Adreno-EGL(456): : EGL 1.4 QUALCOMM build: ()
02-12 13:15:37.597: I/Adreno-EGL(456): OpenGL ES Shader Compiler Version: E031.24.00.08
02-12 13:15:37.597: I/Adreno-EGL(456): Build Date: 07/15/14 Tue
02-12 13:15:37.597: I/Adreno-EGL(456): Local Branch: AU200-20140715-all-patches-au200-839308
02-12 13:15:37.597: I/Adreno-EGL(456): Remote Branch:
02-12 13:15:37.597: I/Adreno-EGL(456): Local Patches:
02-12 13:15:37.597: I/Adreno-EGL(456): Reconstruct Branch:
02-12 13:15:37.647: D/OpenGLRenderer(456): Enabling debug mode 0
02-12 13:15:51.397: D/AbsListView(456): Get MotionRecognitionManager
02-12 13:15:53.217: D/dalvikvm(456): GC_EXPLICIT freed 221K, 34% free 11783K/17600K, paused 3ms+4ms, total 32ms
02-12 13:15:54.277: D/dalvikvm(456): GC_EXPLICIT freed 573K, 37% free 11240K/17600K, paused 2ms+4ms, total 27ms
02-12 13:15:54.447: V/RenderScript(456): 0x7948e068 Launching thread(s), CPUs 4
02-12 13:15:56.057: E/InputEventReceiver(456): Exception dispatching input event.
02-12 13:15:56.057: D/AndroidRuntime(456): Shutting down VM
02-12 13:15:56.057: W/dalvikvm(456): threadid=1: thread exiting with uncaught exception (group=0x41878da0)
02-12 13:15:56.077: E/AndroidRuntime(456): FATAL EXCEPTION: main
02-12 13:15:56.077: E/AndroidRuntime(456): Process: com.ab.hdgodwallpapers, PID: 456
02-12 13:15:56.077: E/AndroidRuntime(456): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
02-12 13:15:56.077: E/AndroidRuntime(456): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
02-12 13:15:56.077: E/AndroidRuntime(456): at java.util.ArrayList.get(ArrayList.java:308)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.support.v4.view.ViewPager.performDrag(ViewPager.java:2078)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.support.v4.view.ViewPager.onTouchEvent(ViewPager.java:2001)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.View.dispatchTouchEvent(View.java:8164)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2428)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2151)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2434)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2166)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2434)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2166)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2434)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2166)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2434)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2166)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2434)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2166)
02-12 13:15:56.077: E/AndroidRuntime(456): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2330)
02-12 13:15:56.077: E/AndroidRuntime(456): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1614)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.app.Activity.dispatchTouchEvent(Activity.java:2658)
02-12 13:15:56.077: E/AndroidRuntime(456): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2278)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.View.dispatchPointerEvent(View.java:8359)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4711)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4572)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4130)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4184)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4153)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4264)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4161)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4321)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4130)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4184)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4153)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4161)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4130)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6453)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6366)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6337)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6302)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6533)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:176)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl.doConsumeBatchedInput(ViewRootImpl.java:6506)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.ViewRootImpl$ConsumeBatchedInputRunnable.run(ViewRootImpl.java:6552)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.Choreographer.doCallbacks(Choreographer.java:613)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.Choreographer.doFrame(Choreographer.java:581)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:799)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.os.Handler.handleCallback(Handler.java:733)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.os.Handler.dispatchMessage(Handler.java:95)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.os.Looper.loop(Looper.java:146)
02-12 13:15:56.077: E/AndroidRuntime(456): at android.app.ActivityThread.main(ActivityThread.java:567

Dr. Droid
Monday, February 12th, 2018

Hi Prathyusha,

You forgot to initialise the ImageLoader.
Please check this link : https://www.androhub.com/select-and-share-multiple-images/

Thanks

Haritha
Tuesday, February 20th, 2018

Hii sir, can u plz give me the code to insert texts to each of these images in the slider??

Dr. Droid
Tuesday, February 20th, 2018

Hi Haritha,

Use the below xml layout for showing Text with Images and find the ID of TextView in PagerAdapter class and change its text label there.

< ?xml version="1.0" encoding="utf-8"?>


Thanks

Taras
Wednesday, February 21st, 2018

Hi, how can i do if i want to upload images from phone gallery?
private static final Integer[] IMAGES= {R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.five};
How can i pass images from gallery in that array?
Thanks

Dr. Droid
Thursday, February 22nd, 2018

Hi Taras,

Check this below link to pick multiple images from gallery. After picking you will get image path , that path you have to store in List and pass that List to adapter to show Images.

https://www.androhub.com/select-and-share-multiple-images/

Thanks

Anish Sahu
Saturday, March 3rd, 2018

getting following error java.lang.IllegalStateException: The application’s PagerAdapter changed the adapter’s contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item

while adding two slider on in one activity

Dr. Droid
Wednesday, March 7th, 2018

Hi Anish,

Can you show me your code so that I can check how you are implementing two sliders.

Thanks

Syed
Tuesday, April 10th, 2018

How to add different text below different images and the background color should also change when the image changes?

Dr. Droid
Tuesday, April 10th, 2018

Hi Syed,

I haven’t posted yet anything like this at my blog. And it will take time to explain you here.

I found one link which can help you:

https://android.jlelse.eu/creating-an-intro-screen-for-your-app-using-viewpager-pagetransformer-9950517ea04f

Thanks

Peter
Thursday, June 21st, 2018

Hi Dr. Droid,

Am using Fragment not Activity, how do I modify the code to make it work for me.

Thanks for the support.

Dr. Droid
Sunday, June 24th, 2018

Hi Peter,

To implement the same in Fragment the only thing you need to take care is that instead of *this* and *MainActivity.this* you should be using *getActivity()* which is basically a Context.

Thanks

as
Monday, June 25th, 2018

how to make this dynamic using Image from JSON? make tutorial about this, please

danni
Monday, July 2nd, 2018

how to swipe an image in viewpager to left or right direction?

Dr. Droid
Tuesday, July 3rd, 2018

Hi Danni,

You mean programatically right?

If yes, then you can use below code:

viewPager.setCurrentItem(position); //here position will be your items in viewpager

Thanks

Anonymous
Saturday, August 11th, 2018

Where is cirlcepageindicator class ?

Dr. Droid
Saturday, August 11th, 2018

Hi Anonymous,

If you see the code i have added some external library for it. So the same you have to do.

Thanks

tom
Wednesday, October 3rd, 2018

hi dear developer , do you exist other way for slideshow?
that of course without library…
please navigate me …

Dr. Droid
Monday, October 8th, 2018

Hi Tom,

If you want to add the DOTs at the bottom or at any place then you have to use some library and if you want to do this without using DOTs then you can exclude library.

Thanks

ubaid
Wednesday, October 31st, 2018

hye i just want make an app for ecommerce store like http://www.alubaidiya.pk any one here for help https://www.alubaidiya.pk/

Dr. Droid
Wednesday, October 31st, 2018

Hi Ubaid,

Can you mail me your full requirement so that we can discuss further?

Thanks

ubaid
Monday, November 26th, 2018

yes sir please email at [email protected] before email us please go through our website http://www.alubaidiya.pk

sagar
Wednesday, March 27th, 2019

hi sir i’m using it in a fragment but at
mPager.setAdapter(new SlidingImage_Adapter(getContext(), ImagesArray));
it is giving the null pointer exception and the app crashes

Dr. Droid
Wednesday, March 27th, 2019

Hi Sagar,

Null pointer exception occurs when something is not initialised in your code.
So cross check you code and still if you can’t find error then mail me your exception.

Thanks

Kumar
Saturday, April 6th, 2019

Not Working Error

Dr. Droid
Tuesday, April 9th, 2019

Hi Kumar,

What actual exception you are getting? Can you share?

Thanks

Atishay jain
Saturday, April 13th, 2019

In an activity, when i moved to different activity the circle/bubbles on an image get doubled.How it can be solved??

Dr. Droid
Monday, April 15th, 2019

Hi Atishay,

You need to clear your list before adding items to it again.

Thanks

Khanzada
Saturday, April 27th, 2019

Hi, the code is working fine for me except its swipes the slides very quickly. At first it swipes smoothly but soon starts to swipe rapidly and keep on accelerating. i want it go smoothly. please help.

Dr. Droid
Sunday, April 28th, 2019

Hi Khanzada,

You can put your own time in Timer to reduce the swipe time.

Thanks

Aarzu
Wednesday, June 26th, 2019

Hi Dr.Droid Sir,
Please help me to add “next and prev” buttons in image slider by viewPager and Picasso or suggest me to add in you code? Here is the question I asked and given code:https://stackoverflow.com/questions/56749244/add-next-prev-buttons-in-slider-image-made-by-picasso-and-viewpager

I want to mage img slider of many images(+1000s) from drawable, which will be the best method above method or “Viewpager and picasso”.

I have done by “vp and picasso” and its working now please help me to add next, prev buttons. please sir please

Hardik
Friday, July 26th, 2019

Hi,If i am going to some one fragment and press back and goto slider fragment ,image sliding speed is increase.

Dr. Droid
Friday, July 26th, 2019

Hi Hardik,

When you leave the fragment you have to remove handler callbacks and once you again come back register callbacks again.

Thanks

charbel
Saturday, August 17th, 2019

how to make the circlepageindicator start from the begining when it’s reached the maximum

Dr. Droid
Monday, August 26th, 2019

Hi Charbel,

You have to implement onPageChangeListener and once you reached the last item you have to manually change it to the first item.

Thanks

Wehape
Sunday, November 24th, 2019

How to do that sir?
Please give me some example code

Dr. Droid
Monday, November 25th, 2019

Hi Wehape,

What you want to do and what example you need?

Thanks

Post comment

Your email address will not be published. Required fields are marked *