I am trying to make a slideshow of a few images while making an android app. I am using this code below
final int[] array = {R.drawable.cow_1, R.drawable.cow_2, R.drawable.cow_3, R.drawable.cow_4};
for (int i = 0; i < 4; i++){
final int finalI = i;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
animal_image.setImageResource(array[finalI]);
}
}, 4000);
}
The problem I am facing is that I am not getting the slideshow of images one-by-one instead the code is showing the last image after the first one directly. There's some problem with the code, please help me fix it.
What you code is doing is that it is creating a Handler
for each of the image and setting the delay to 4 seconds. The for
loop will run instantly for each iteration and all the Handlers that have been created will run after 4 seconds. This causes the last image to show up because the last Handler will have run a few milliseconds after the rest. In order to fix this, you need to have an incremental timer for each Handler.
final int[] array = {R.drawable.cow_1, R.drawable.cow_2, R.drawable.cow_3, R.drawable.cow_4};
for (int i = 0; i < 4; i++){
final int finalI = i;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
animal_image.setImageResource(array[finalI]);
}
}, 4000 * finalI);
}
Using the above given code, the first image will be displayed, and all the other images will be displayed after a multiple of 4 seconds based on the image number (image 2 will be shown after 4 seconds, image 3 will be shown after 8 seconds, image 4 will be shown after 12 seconds and so on).