DEV Community

Adeyemo Adekunle Ayobami
Adeyemo Adekunle Ayobami

Posted on

Auto Image Slider in Android | Kotlin: A Step-by-Step Guide

Auto Image Slider in Android | Kotlin: A Step-by-Step Guide

Recently, I added an automatic image slider to my Kotlin app.

In this post, I'll guide you through the step-by-step process of implementing this feature.

An image slider is a view that showcases multiple images one at a time. Users can control the slider manually by swiping or using dedicated action buttons to navigate to the next or previous image.

Let's dive into how you can bring this dynamic image experience to your Kotlin app!

Add the needed dependencies

Add autoimageslider and glide to your build.gradle (Module) level file in the dependencies section and sync the project with gradle files.



implementation 'com.github.smarteist:autoimageslider:1.4.0'
implementation “com.github.bumptech.glide:glide:4.11.0”


Enter fullscreen mode Exit fullscreen mode

The autoimageslider library will be used for the image slider and the glide library will be used to display remote images.

Add the SliderView to your main xml file

Open your Activity or Fragment xml file and add the SliderView as shown below.



<androidx.cardview.widget.CardView
    app:cardCornerRadius="6dp"
    android:layout_margin="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.smarteist.autoimageslider.SliderView
        android:id="@+id/imageSlider"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:sliderAnimationDuration="600"
        app:sliderAutoCycleDirection="back_and_forth"
        app:sliderAutoCycleEnabled="true"
        app:sliderIndicatorAnimationDuration="600"
        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"
        app:sliderStartAutoCycle="true" />
</androidx.cardview.widget.CardView>


Enter fullscreen mode Exit fullscreen mode

The SliderView is wrapped inside a CardView to give the images a rounded corner and make them look better.

Likely error message

After adding the SliderView above to your xml file, You could come across any of the following errors:

  • Class referenced in the layout file, com.smarteist.autoimageslider.SliderView, was not found in the project or the libraries

  • Cannot resolve class com.smarteist.autoimageslider.SliderView

Solution to the error message

Add the code below to your settings.gradle file



dependencyResolutionManagement {
 repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
     repositories {
         //...
         jcenter()
         maven { url 'https://jitpack.io' }
     }
 }


Enter fullscreen mode Exit fullscreen mode

Sync the project with gradle files and the error message will disappear.

Create a data class
Create a data class named BannerSliderItem

This data class will have a field named imageUrl that will hold each slider image url.



class BannerSliderItem (val imageUrl: String)


Enter fullscreen mode Exit fullscreen mode

Create an xml file for each slider item

Right-click on your res/layout folder, and click New -> Layout Resource File. Name the file banner_slider_item.xml



<?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="200dp">
    <ImageView
        android:id="@+id/banner_slider_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:scaleType="fitXY"
        />

</RelativeLayout>


Enter fullscreen mode Exit fullscreen mode

Paste the code above inside the xml file.

Create a SliderViewAdapter similar to a RecyclerViewAdapter



class BannerSliderAdapter(sliders: ArrayList<BannerSliderItem>) :
    SliderViewAdapter<BannerSliderAdapter.SliderViewHolder>() {

    var sliderList: ArrayList<BannerSliderItem> = sliders

    override fun getCount(): Int {
        return sliderList.size
    }
    override fun onCreateViewHolder(parent: ViewGroup?): BannerSliderAdapter.SliderViewHolder {
        val inflate: View =
            LayoutInflater.from(parent!!.context).inflate(R.layout.banner_slider_item, null)
        return SliderViewHolder(inflate)
    }

    override fun onBindViewHolder(viewHolder: BannerSliderAdapter.SliderViewHolder?, position: Int) {
        if (viewHolder != null) {
            Glide.with(viewHolder.itemView).load(sliderList.get(position).imageUrl,).fitCenter()
                .into(viewHolder.imageView)
        }
    }

    class SliderViewHolder(itemView: View?) : SliderViewAdapter.ViewHolder(itemView) {
        var imageView: ImageView = itemView!!.findViewById(R.id.banner_slider_view)
    }
}


Enter fullscreen mode Exit fullscreen mode

Declare variables

Declare a variable for the BannerSliderAdapter



private lateinit var bannerSliderAdapter: BannerSliderAdapter


Enter fullscreen mode Exit fullscreen mode

Declare an array list to store the BannerSliderItem items



private lateinit var sliderList: ArrayList<BannerSliderItem>


Enter fullscreen mode Exit fullscreen mode

Initialize declared variables

Initialize the bannerSliderAdapter and sliderList inside the onCreateView method if you are using a Fragment or onCreate method if you're using an Activity



// Banner Slider Adapter
sliderList = arrayListOf(
    BannerSliderItem("https://images.pexels.com/photos/1639562/pexels-photo-1639562.jpeg"),
    BannerSliderItem("https://images.pexels.com/photos/2983101/pexels-photo-2983101.jpeg"),
    BannerSliderItem("https://images.pexels.com/photos/2271107/pexels-photo-2271107.jpeg")
);


Enter fullscreen mode Exit fullscreen mode

Create an Instance of the BannerSliderAdapter, pass the slider list to the constructor, and assign it to bannerSliderAdapter



bannerSliderAdapter = BannerSliderAdapter(sliderList)


Enter fullscreen mode Exit fullscreen mode

Find the reference to the SliderView inside the main layout using its ID and assign it to bannerSliderView. This reference can be found in two ways.

  • Using findViewById


val bannerSliderView: SliderView = findViewById(R.id.bannerSlider);


Enter fullscreen mode Exit fullscreen mode
  • Using Data Binding


val bannerSliderView: SliderView = binding.bannerSlider


Enter fullscreen mode Exit fullscreen mode

Attach the bannerSliderAdapter instance to the SliderView



bannerSliderView.setSliderAdapter(bannerSliderAdapter);


Enter fullscreen mode Exit fullscreen mode

Style the slider



//IndicatorAnimationType. :WORM or THIN_WORM or COLOR or DROP //or FILL or NONE or SCALE or SCALE_DOWN or SLIDE and SWAP.
bannerSliderView.setIndicatorAnimation(IndicatorAnimationType.WORM);

//Set the SliderTransformAnimation
bannerSliderView.setSliderTransformAnimation(SliderAnimations. WORM);

//Set the autoCycleDirection
bannerSliderView.autoCycleDirection = SliderView.AUTO_CYCLE_DIRECTION_RIGHT;

//Set the indicator selected and unselected color
bannerSliderView.indicatorSelectedColor = Color.WHITE;
bannerSliderView.indicatorUnselectedColor = Color.GRAY;

//Set the slider scroll delay in seconds
bannerSliderView.scrollTimeInSec = 4; 

//Start the auto-cycle
bannerSliderView.startAutoCycle();


Enter fullscreen mode Exit fullscreen mode

Outcome

.

Conclusion

In conclusion, implementing an automatic image slider in your Kotlin app can greatly enhance the visual experience for users. By following the step-by-step guide outlined in this post, you can easily integrate this feature using libraries like autoimageslider and glide. The dynamic nature of the image slider adds a touch of interactivity and engagement to your app. Don't hesitate to experiment with different styles and functionalities to create a unique and captivating image slider for your app users to enjoy!

Thank you for reading.

Top comments (0)