Skip to content
Related Articles

Related Articles

Auto Image Slider in Android with Example
  • Last Updated : 21 Dec, 2020

Auto Image Slider is one of the most seen UI components in Android. This type of slider is mostly seen inside the apps of big E-commerce sites such as Flipkart, Amazon, and many more. Auto Image Slider is used to represent data in the form of slides that changes after a specific interval of time. In this article, we will take a look at How to Create Auto Image Slider on Android. We will use the SliderView library to add this type of UI component in our app.  

Note: You may also refer to Image Slider in Android using ViewPager.

Now we will see the Implementation of this SliderView in Android. 

Example

A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Auto Image Slider in Android



Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency of Slider View in build.gradle file

Navigate to the Gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.

// dependancy sor slider view

implementation ‘com.github.smarteist:autoimageslider:1.3.9’

// dependancy for loading image from url

implementation “com.github.bumptech.glide:glide:4.11.0”



Step 3: Add internet permission in the AndroidManifest.xml file

Navigate to the app > Manifest to open the Manifest file and add below two lines.

<!–Permission for internet–>

<uses-permission android:name=”android.permission.INTERNET” />

<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />

Step 4: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--
    slideranimation duration is to set duration for transition between two slides
    sliderautocycledirection is to set animationbetween transition of your slides
    sliderindicator enables is used to display the indicators for slider
    slider indicator gravity is to set gravity for indicator gravity
    slider indicator margin is to set margin for indicator
    slider indicator orientation is used to add orientation for slider
    slider indicator padding is use to add padding to indicator
    slider indicator selected color is use to specify selected color
    and slider indicator unselected color is use to specify the color when the slider is unselected
    slider scroll time in sec is used to specify scrolling time in seconds
    -->
    <com.smarteist.autoimageslider.SliderView
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_centerInParent="true"
        app:sliderAnimationDuration="600"
        app:sliderAutoCycleDirection="back_and_forth"
        app:sliderIndicatorAnimationDuration="600"
        app:sliderIndicatorEnabled="true"
        app:sliderIndicatorGravity="center_horizontal|bottom"
        app:sliderIndicatorMargin="15dp"
        app:sliderIndicatorOrientation="horizontal"
        app:sliderIndicatorPadding="3dp"
        app:sliderIndicatorRadius="2dp"
        app:sliderIndicatorSelectedColor="#5A5A5A"
        app:sliderIndicatorUnselectedColor="#FFF"
        app:sliderScrollTimeInSec="1" />
  
</RelativeLayout>

Step 5: Create a new Modal class for storing data

Navigate to app > java > your app’s package name and then right-click on it and New > Java class and name your Model class as SliderData and below code inside that Java class. Below is the code for the SliderData.java file. Comments are added inside the code to understand the code in more detail.

Java




public class SliderData {
  
    // image url is used to 
    // store the url of image
    private String imgUrl;
  
    // Constructor method.
    public SliderData(String imgUrl) {
        this.imgUrl = imgUrl;
    }
  
    // Getter method
    public String getImgUrl() {
        return imgUrl;
    }
  
    // Setter method
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}

Step 6: Create an XML file for the items of SliderView 

Navigate to the app > res > layout > Right-click on it and select New > Layout Resource File and then name your XML file as slider_layout.xml. After creating this file add the below code to it.  

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <!--Image we will display is our slider view-->
    <ImageView
        android:id="@+id/myimage"
        android:layout_width="400dp"
        android:layout_height="300dp"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/app_name" />
  
</RelativeLayout>

Step 7: Create Adapter Class for setting data to each item of our SliderView

Navigate to app > java > your app’s package name and then right-click on it and New > Java class and name your class as SliderAdapter and below code inside that Java class. Below is the code for the SliderAdapter.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
  
import com.bumptech.glide.Glide;
import com.smarteist.autoimageslider.SliderViewAdapter;
  
import java.util.ArrayList;
import java.util.List;
  
public class SliderAdapter extends SliderViewAdapter<SliderAdapter.SliderAdapterViewHolder> {
      
    // list for storing urls of images.
    private final List<SliderData> mSliderItems;
      
    // Constructor
    public SliderAdapter(Context context, ArrayList<SliderData> sliderDataArrayList) {
        this.mSliderItems = sliderDataArrayList;
    }
  
    // We are inflating the slider_layout 
    // inside on Create View Holder method.
    @Override
    public SliderAdapterViewHolder onCreateViewHolder(ViewGroup parent) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.slider_layout, null);
        return new SliderAdapterViewHolder(inflate);
    }
  
    // Inside on bind view holder we will
    // set data to item of Slider View.
    @Override
    public void onBindViewHolder(SliderAdapterViewHolder viewHolder, final int position) {
  
        final SliderData sliderItem = mSliderItems.get(position);
  
        // Glide is use to load image
        // from url in your imageview.
        Glide.with(viewHolder.itemView)
                .load(sliderItem.getImgUrl())
                .fitCenter()
                .into(viewHolder.imageViewBackground);
    }
  
    // this method will return
    // the count of our list.
    @Override
    public int getCount() {
        return mSliderItems.size();
    }
  
    static class SliderAdapterViewHolder extends SliderViewAdapter.ViewHolder {
        // Adapter class for initializing 
        // the views of our slider view.
        View itemView;
        ImageView imageViewBackground;
  
        public SliderAdapterViewHolder(View itemView) {
            super(itemView);
            imageViewBackground = itemView.findViewById(R.id.myimage);
            this.itemView = itemView;
        }
    }
}

Step 8: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
    // Urls of our images.
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // we are creating array list for storing our image urls.
        ArrayList<SliderData> sliderDataArrayList = new ArrayList<>();
          
        // initializing the slider view.
        SliderView sliderView = findViewById(R.id.slider);
          
        // adding the urls inside array list
        sliderDataArrayList.add(new SliderData(url1));
        sliderDataArrayList.add(new SliderData(url2));
        sliderDataArrayList.add(new SliderData(url3));
          
        // passing this array list inside our adapter class.
        SliderAdapter adapter = new SliderAdapter(this, sliderDataArrayList);
          
        // below method is used to set auto cycle direction in left to 
        // right direction you can change according to requirement.
        sliderView.setAutoCycleDirection(SliderView.LAYOUT_DIRECTION_LTR);
          
        // below method is used to 
        // setadapter to sliderview.
        sliderView.setSliderAdapter(adapter);
          
        // below method is use to set 
        // scroll time in seconds.
        sliderView.setScrollTimeInSec(3);
          
        // to set it scrollable automatically
        // we use below method.
        sliderView.setAutoCycle(true);
          
        // to start autocycle below method is used.
        sliderView.startAutoCycle();
    }
}

Output: 

Check out the project on this link: https://github.com/ChaitanyaMunje/GFGImageSlider

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :