How to Make Android AUTOMATED Image Slider using View Pager


You might have noticed that a lot of android applications introduced AUTOMATED Image Slider to showcase their services while the application is loading something else. Under this article, we are going to learn how to create advanced Automated Image Slider in android using View Pager.

The sliding images must be capable of sliding themselves without user intervention and slider should be infinite for any number of images, hence Automated Image Slider in android.

Download CODE | Download APK



DEMO VIDEO

How to create android Automated Image Slider in Android Using View Pager

We are going to use Android ViewPager with Fragments to achieve this. Fragments will be used as a container for the sliding images, while view pager will enable us to swipe through each fragment efficiently, but in our case, we need to automate the swiping process.

First, we MUST create a real-time checker, that will keep checking for the current page occupied in our View Pager, or basically something that will automate the whole process. To achieve this, we will use Handler class. Handler class will run infinitely updating our slider. Please go through the code below and Make Sure you read all the comments in the code carefully. Am going to explain everything after we create the whole project.

Creating new Project – Android Image Slider

Create a new project in the android studio from File => New Project, by filling in all the necessary details. When it prompts you to select activity, select Basic Activiy and finish. Please note, you can also use empty activity if you like. I prefer basic activity as it contains all development tools that we need.



Download Images and add them to your project’s drawable folder, under res => drawable. These images can also be found in the project files.

Open content_main.xml and add the following code. Make sure you change ConstraintLayout to RelativeLayout.

content_main.xml
content_main.xml contains only one child view (ViewPager).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager_slider"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="10dp" />

</RelativeLayout>

Create three fragments layouts namely: fragment_slider_one_layout.xml, fragment_slider_two_layout.xml and fragment_slider_three_layout.xml. These are just normal layouts created from res > layout > new > Layout resource file. We will then create three java classes that will instantiate our fragments. These layouts will contain our images, each layout conntaining one image. Let’s start with fragment_slider_one_layout.xml.

fragment_slider_one_layout.xml
This is fragment layout that will contain our first image.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_slider_one" />

</RelativeLayout>

fragment_slider_two_layout.xml
This fragment layout contains our second image

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_slider_two" />

</RelativeLayout>

fragment_slider_three_layout
Third image will be contained by this fragment.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_slider_3" />

</RelativeLayout>

Next, let’s create three classes that will represent our three fragment layouts. These classes together with above three layouts are what will make complete fragments. So at the end of the day, we should have 3 fragments. We are going to create three fragment classes namely: FragmentSliderOne.java, FragmentSliderTwo.java and FragmentSliderThree.java. Let us start with FragmentSliderOne.java.

FragmentSliderOne.java.

package com.hacksmile.androidimageslider;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentSliderOne extends Fragment {
    // make sure you import android.support.v4.app.Fragment


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_slider_one_layout, container, false);


        return view;

    }
}

FragmentSliderTwo.java

package com.hacksmile.androidimageslider;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentSliderTwo extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_slider_two_layout, container, false);


        return view;

    }
}

FragmentSliderThree.java

package com.hacksmile.androidimageslider;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FragmentSliderThree extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_slider_three_layout, container, false);


        return view;

    }
}

We have completed fragments creation. Next, we need to create a view pager adapter that will make our three fragments to swipe efficiently in the viewPager. Go ahead and create view pager adapter and name it CustomViewPagerAdapter.java.

CustomViewPagerAdapter.java.

package com.hacksmile.androidimageslider;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class CustomViewPagerAdapter extends FragmentStatePagerAdapter {

    public CustomViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment;

        if (position == 0) {
            fragment = new FragmentSliderOne();
        } else if (position == 1) {
            fragment = new FragmentSliderTwo();
        } else {
            fragment = new FragmentSliderThree();
        }

        return fragment;
    }

    @Override
    public int getCount() {
        // return the number of your fragments,
        // we have 3 fragments
        return 3;
    }
}

Let’s now dive into our main business of creating Automated Image Slider in android. At this juncture, open MainActivity.java or your launcher activity and add the following code.



package com.hacksmile.androidimageslider;

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

public class MainActivity extends AppCompatActivity {

    private static final long SLIDER_TIMER = 2000; // change slider interval
    private int currentPage = 0; // this will tell us the current page available on the view pager
    // please see ViewPager Listener on the onPageSelected method to see how we are updating
    // currentPage variable

    private boolean isCountDownTimerActive = false; // let the timer start if and only if it has completed previous task


    private Handler handler;
    private ViewPager viewPager;

    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (!isCountDownTimerActive) {
                automateSlider();
            }

            handler.postDelayed(runnable, 1000);
            // our runnable should keep running for every 1000 milliseconds (1 seconds)
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        handler = new Handler();

        handler.postDelayed(runnable, 1000);
        runnable.run();

        viewPager = findViewById(R.id.view_pager_slider);

        CustomViewPagerAdapter viewPagerAdapter = new CustomViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(viewPagerAdapter);

        // now it's time to think about our sliders


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    currentPage = 0;
                } else if (position == 1) {
                    currentPage = 1;
                } else {
                    currentPage = 2;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void automateSlider() {
        isCountDownTimerActive = true;
        new CountDownTimer(SLIDER_TIMER, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {

                int nextSlider = currentPage + 1;

               

                if (nextSlider == 3) {
                    nextSlider = 0; // if it's last Image, let it go to the first image
                }

                viewPager.setCurrentItem(nextSlider);
                isCountDownTimerActive = false;
            }
        }.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Kill this background task once the activity has been killed
        handler.removeCallbacks(runnable);
    }
}

Android Image Slider Explanation

We are only going to explain what’s happening in the MainActivity.java. Please make sure you understand everything to do with ViewPager and viewPager listeners. From our MainActivity.java, we have several global variables. SLIDER_TIMER constants, keeps the time interval between each slide. currentPage variable, stores the current page selected by view pager, please have a look at the viewPager listener to understand how this variable is updated. We also have another important variable, isCountDownTimerActive. This is boolean that regulates CountDownTimer. It tells the system, “Please do not start next slide until the current slide is finished”, in short, this boolean regulates the slider. Please make sure you read comments inside the code and also ask me questions in the commenting system below, in case you got stranded.