How to make auto image slider with viewpager in android studio

In this tutorial, we will create an auto image slider in android studio using java language. we will slide not only images but also title and body text of that particular image. we also will create dot indicator for this auto image slider.

How to make auto image slider with viewpager in android studio

Overview

In this tutorial, we are going to use java programming language. i also will share you complete code of this tutorial. we didn't use any library for this auto image slider. we will create all the things from scratch. if you will follow this tutorial from start to end, you will be able to create any kind of auto slider for your android project, you can also make changes and can add some new features in this image slider so let's start building this auto image slider.

Auto Image Slider Video Tutorial.

in this video tutorial, we have briefly discussed all the code related to this project. 

For to make an auto image slider first of all we will create an activity and then we will write all code related to the auto image slider there. you can also use it in fragments but we are going to create this image slider in the activity.  

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
   >

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardCornerRadius="3dp"
        android:layout_margin="16dp"
        app:cardElevation="2dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:background="#cccccc"
                android:foreground="#1A000000" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                android:orientation="vertical"
                android:paddingLeft="15dp"
                android:paddingTop="15dp"
                android:paddingRight="15dp"
                android:paddingBottom="15dp">

                <TextView
                    android:id="@+id/title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:maxLines="1"
                    android:singleLine="true"
                    android:text="Suspendisse ornare est ac auctor pulvinar"
                    android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                    android:textColor="#263238" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:gravity="bottom"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:orientation="horizontal">

                        <ImageView
                            android:layout_width="15dp"
                            android:layout_height="15dp"
                            android:layout_marginEnd="10dp"
                            android:layout_marginRight="10dp"
                            app:srcCompat="@drawable/ic_baseline_ac_unit_24"
                            app:tint="#666666" />

                        <TextView
                            android:id="@+id/brief"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="The Backpacker"
                            android:textAppearance="@style/TextAppearance.AppCompat.Small"
                            android:textColor="#666666" />

                    </LinearLayout>

                    <View
                        android:layout_width="0dp"
                        android:layout_height="0dp"
                        android:layout_weight="1" />

                    <LinearLayout
                        android:id="@+id/layout_dots"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:orientation="horizontal" />

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

    </androidx.cardview.widget.CardView>


</androidx.constraintlayout.widget.ConstraintLayout>

activity_main.xml details.

In activity_main.xml file we used these android framework widgets cardview , viewpager, Linearlayout and two textview. view pager is for to slide images 2 textview for title and body and in above code, you can see also have used one empty linear layout. we basically will add image slider indicator in that linearlayout from java code. 

MainActivity.java Code.

package com.jainone.autobannerslider;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import android.graphics.PorterDuff;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    Runnable runnable;
    Handler handler;
    private int[] array_image_place = {
            R.drawable.firstbanner,
            R.drawable.secondbanner,
            R.drawable.thirdbanner,
            R.drawable.fourthbanner,
            R.drawable.shoes
    };

    private LinearLayout layout_dots;
    private ViewPager viewPager;
    private AdapterImageSlider adapterImageSlider;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startBannerSlider();
    }

    private void startBannerSlider() {
        handler = new Handler();
        String[] titleArr = this.getResources().getStringArray(R.array.titles);
        String[] bodyArr = this.getResources().getStringArray(R.array.body);

        layout_dots = (LinearLayout) findViewById(R.id.layout_dots);
        viewPager = (ViewPager) findViewById(R.id.pager);
        adapterImageSlider = new AdapterImageSlider(this, new ArrayList());

        final List items = new ArrayList<>();
        for (int i = 0; i < array_image_place.length; i++) {
            Image obj = new Image();
            obj.image = array_image_place[i];
            obj.imageDrw = getResources().getDrawable(obj.image);
            obj.title= titleArr[i];
            obj.body = bodyArr[i];
            items.add(obj);
        }

        adapterImageSlider.setItems(items);
        viewPager.setAdapter(adapterImageSlider);
        // displaying selected image first
        viewPager.setCurrentItem(0);

        addBottomDots(layout_dots, adapterImageSlider.getCount(), 0);

        ((TextView) findViewById(R.id.title)).setText(items.get(0).title);
        ((TextView) findViewById(R.id.brief)).setText(items.get(0).body);

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

            @Override
            public void onPageSelected(int pos) {
                ((TextView) findViewById(R.id.title)).setText(items.get(pos).title);
                ((TextView) findViewById(R.id.brief)).setText(items.get(pos).body);
                addBottomDots(layout_dots, adapterImageSlider.getCount(), pos);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        startAutoSlider(adapterImageSlider.getCount());

    }

    private void startAutoSlider(final int count) {
        runnable = new Runnable() {
              @Override
              public void run() {
                  int pos = viewPager.getCurrentItem();
                  pos = pos + 1;
                  if (pos >= count) pos = 0;
                  viewPager.setCurrentItem(pos);
                  handler.postDelayed(runnable, 3000);
              }
          };
        handler.postDelayed(runnable, 3000);

    }

    private void addBottomDots(LinearLayout layout_dots, int size, int current) {
        ImageView[] dots = new ImageView[size];

        layout_dots.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new ImageView(this);
            int width_height = 15;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(width_height, width_height));
            params.setMargins(10, 0, 10, 0);
            dots[i].setLayoutParams(params);
            dots[i].setImageResource(R.drawable.circle_outline);
            dots[i].setColorFilter(ContextCompat.getColor(this, R.color.grey40), PorterDuff.Mode.SRC_ATOP);
            layout_dots.addView(dots[i]);
        }

        if (dots.length > 0) {
            dots[current].setImageResource(R.drawable.circle_shape);
            dots[current].setColorFilter(ContextCompat.getColor(this, R.color.grey40), PorterDuff.Mode.SRC_ATOP);
        }
    }




}

MainActivity.java Code Details.

in MainActivity.java oncreate method we used startBannerSlider();  method we will create this private method in same activity. 

startBannerSlider code

 private void startBannerSlider() {
        handler = new Handler();
        String[] titleArr = this.getResources().getStringArray(R.array.titles);
        String[] bodyArr = this.getResources().getStringArray(R.array.body);

        layout_dots = (LinearLayout) findViewById(R.id.layout_dots);
        viewPager = (ViewPager) findViewById(R.id.pager);
        adapterImageSlider = new AdapterImageSlider(this, new ArrayList<Image>());

        final List<Image> items = new ArrayList<>();
        for (int i = 0; i < array_image_place.length; i++) {
            Image obj = new Image();
            obj.image = array_image_place[i];
            obj.imageDrw = getResources().getDrawable(obj.image);
            obj.title= titleArr[i];
            obj.body = bodyArr[i];
            items.add(obj);
        }

        adapterImageSlider.setItems(items);
        viewPager.setAdapter(adapterImageSlider);
        // displaying selected image first
        viewPager.setCurrentItem(0);

        addBottomDots(layout_dots, adapterImageSlider.getCount(), 0);

        ((TextView) findViewById(R.id.title)).setText(items.get(0).title);
        ((TextView) findViewById(R.id.brief)).setText(items.get(0).body);

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

            @Override
            public void onPageSelected(int pos) {
                ((TextView) findViewById(R.id.title)).setText(items.get(pos).title);
                ((TextView) findViewById(R.id.brief)).setText(items.get(pos).body);
                addBottomDots(layout_dots, adapterImageSlider.getCount(), pos);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        startAutoSlider(adapterImageSlider.getCount());

    }

startBannerSlider method code explain

in this method first of all we initialized all android widgets, views like view pager, linearlayout for dots indicator etc. we have two arrays at this  app/res/values/string.xml location one is for the title and the second for body text. we basically have stored these arrays in string.xml file. you can either store it in an XML file if you have fixed content but if you want to update your image banner slider content time to time then you should fetch data from the server and then store that in an array.

next, we have initialized adapter for view pager we have created a custom adapter for this image banner slider we will discuss about it later in this tutorial. 

we will store banner slider all data in another arraylist of type Image view model we have created image view model in which we have to write below code.

Image.java Class 

public class Image {
    public int image;
    public Drawable imageDrw;
    public String title;
    public String body;
    public Integer counter = null;

}

in the above Image View model class, we have one image variable of int type,imageDra Drawable type for to store Drawable, title, body, and counter Integer type. 

we will set these values in the next step of startbanner slider method

startimageslider method arraylist value set code.

final List<Image> items = new ArrayList<>();
        for (int i = 0; i < array_image_place.length; i++) {
            Image obj = new Image();
            obj.image = array_image_place[i];
            obj.imageDrw = getResources().getDrawable(obj.image);
            obj.title= titleArr[i];
            obj.body = bodyArr[i];
            items.add(obj);
        }

in above code you can see we are setting value to items arraylist of type Image. we basically have three different arrays and one arraylist one array is for title , second is for body text and third is for to store slider images ids. so in the above code we are setting all that value to one list called items. so next we will pass this list to viewpager adapter and then finally we will set that adapter to view pager.

we also set addOnPageChangeListener on viewpager  . then we implemented three methods of onpagechangelistener  in this scenario we just need onPageSelected method In this method we will set title text, body text and dots indicator code method. we also have one addbottomdots method in startbannerslider method we will write code related to image slider dots indicator. 

addbottomdots Method Code

private void addBottomDots(LinearLayout layout_dots, int size, int current) {
        ImageView[] dots = new ImageView[size];

        layout_dots.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new ImageView(this);
            int width_height = 15;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(width_height, width_height));
            params.setMargins(10, 0, 10, 0);
            dots[i].setLayoutParams(params);
            dots[i].setImageResource(R.drawable.circle_outline);
            dots[i].setColorFilter(ContextCompat.getColor(this, R.color.grey40), PorterDuff.Mode.SRC_ATOP);
            layout_dots.addView(dots[i]);
        }

        if (dots.length > 0) {
            dots[current].setImageResource(R.drawable.circle_shape);
            dots[current].setColorFilter(ContextCompat.getColor(this, R.color.grey40), PorterDuff.Mode.SRC_ATOP);
        }
    }

addBottmDots method explains.

above method is used to add dots in linear layout and this method will also change the design of selected dot. so let me explain each and everything of this method. 

we basically called this method in startbannerslider method and onpageselected method of addonpagechangelistner . we called it time because on first launched on page selected will not call and we just run this method one time outside of on page selected method and we have passed dots linear layout, current position zero because on first launch image banner position will be zero then we also have passed total banner count. 

and in onpageselected method we also used it there. in onpageselected method we are getting current position of view pager so we will use that position and then we will change the selected dot design according to that position. this is the logic that we have used. i hope now you understand.

in addbottomdots method, we have first created an image array and the size would be same as items arraylist size. and then we run for loop and set values of Imageview and then we have added that image view to dots linear layout at the end of this method we are setting selected or current display image dot drawable. we set fill drawable for selected dot and outline drawable for all other dots.

circle_shape.xml drawable for selected dot code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@android:color/white" />

</shape>

 

circle_outline.xml drawable file for non selected banners dot

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@android:color/transparent" />
    <stroke
        android:width="1dp"
        android:color="@android:color/white" />

</shape>

startAutoSlider(int count); method

you can see we have used this method at the end of the startbannerslider method. this method is reponsible to make this view pager to auto view pager.
let me share with you code of this method and then i will explain you how basically this method work.

startAutoSlider(int count) code:

    private void startAutoSlider(final int count) {
        runnable = new Runnable() {
            @Override
            public void run() {
                int pos = viewPager.getCurrentItem();
                pos = pos + 1;
                if (pos >= count) pos = 0;
                viewPager.setCurrentItem(pos);
                handler.postDelayed(runnable, 3000);
            }
        };
        handler.postDelayed(runnable, 3000);
    }
in above method we used handler and runnable, handler basically used to run code on different thread its not block our main thread if we will write this code
without handler and runnable our app will crash right after launch. so for long term tasks we used handler and runnable.
in above method we have used postDelayed factory method of handler Class postDelayed is used to run code after specific time so as you can see we have passed 3000
aas a second parameter in postDelayed factory method of handler, 3000 mean 3000 miliseconds and in seconds we can say its 3 seconds you can increase this value
if you want to increase one banner dispaly time.

AdapterImageSlider

so now its time to talk about our custom view pager adapter.


AdapterImageSlider code
package com.jainone.websitetutorialproject;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.cardview.widget.CardView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.List;
 public class AdapterImageSlider extends PagerAdapter {

    private Activity act;
    private List<Image> items;

    private AdapterImageSlider.OnItemClickListener onItemClickListener;

    private interface OnItemClickListener {
        void onItemClick(View view, Image obj);
    }

    public void setOnItemClickListener(AdapterImageSlider.OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    // constructor
    public AdapterImageSlider(Activity activity, List<Image> items) {
        this.act = activity;
        this.items = items;
    }

    @Override
    public int getCount() {
        return this.items.size();
    }

    public Image getItem(int pos) {
        return items.get(pos);
    }

    public void setItems(List<Image> items) {
        this.items = items;
        notifyDataSetChanged();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        final Image o = items.get(position);
        LayoutInflater inflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.item_slider_layout, container, false);

        ImageView image = (ImageView) v.findViewById(R.id.image);
        CardView lyt_parent = (CardView) v.findViewById(R.id.lyt_parent);
        Utils.displayImageOriginal(act, image, o.image);
        lyt_parent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(v, o);
                }
            }
        });

        ((ViewPager) container).addView(v);

        return v;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        ((ViewPager) container).removeView((RelativeLayout) object);

    }

}


if you know how to create Adapter of type pagerAdapter you can easily understand above code. there nothing special in above adapter code if you dont know how pagerAdapter
work then i will recommend you to first learn about pagerAdapter.

Pager Adapter item layout xml file code.

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

    <androidx.cardview.widget.CardView
        android:id="@+id/lyt_parent"

        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#263238"
            android:scaleType="centerCrop" />

    </androidx.cardview.widget.CardView>

</RelativeLayout>

All Done i hope you understand all above steps. if you still have any doubt please write down comment below we will be happy to help you . you can also watch our
video tutorial, we have discussed deeply about this auto banner slider .














What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0