Open In App

Android Image Slider using ViewPager in Kotlin

Last Updated : 30 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Image slider is seen in most e-commerce applications that display advertisements on the home screen. This slider displays the advertisement banners which users can slide to view the others. In this article, we will take a look at Implementing the image slider using ViewPager in Android using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you want to build Image Slider in Android using Java. Check out the following article: Image Slider in Android using View Pager

Step by Step Implementation

Step 1: Create a New Project in Android Studio

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

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

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"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!--on below line we are adding view pager -->
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/idViewPager"
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:layout_margin="10dp" />
  
</RelativeLayout>


Step 3: Creating a layout file for ImageView in View Pager

Navigate to the app > res > layout > Right-click on it > New > Layout Resource file and specify the name as image_slider_item. Add the below code to it. Comments are added in the code to get to know in detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <!--on below line we are creating an image view-->
    <ImageView
        android:id="@+id/idIVImage"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerInParent="true" />
  
</RelativeLayout>


Step 4: Creating a new java class for the adapter of our ViewPager

Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and name it as ViewPagerAdapter and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
  
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.viewpager.widget.PagerAdapter
import java.util.*
  
class ViewPagerAdapter(val context: Context, val imageList: List<Int>) : PagerAdapter() {
    // on below line we are creating a method 
    // as get count to return the size of the list.
    override fun getCount(): Int {
        return imageList.size
    }
  
    // on below line we are returning the object
    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object` as RelativeLayout
    }
  
    // on below line we are initializing 
    // our item and inflating our layout file
    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        // on below line we are initializing 
        // our layout inflater.
        val mLayoutInflater =
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
          
        // on below line we are inflating our custom 
        // layout file which we have created.
        val itemView: View = mLayoutInflater.inflate(R.layout.image_slider_item, container, false)
          
        // on below line we are initializing 
        // our image view with the id.
        val imageView: ImageView = itemView.findViewById<View>(R.id.idIVImage) as ImageView
          
        // on below line we are setting 
        // image resource for image view.
        imageView.setImageResource(imageList.get(position))
          
        // on the below line we are adding this
        // item view to the container.
        Objects.requireNonNull(container).addView(itemView)
          
        // on below line we are simply 
        // returning our item view.
        return itemView
    }
  
    // on below line we are creating a destroy item method.
    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        // on below line we are removing view
        container.removeView(`object` as RelativeLayout)
    }
}


Step 5: Adding images to the drawable folder

Select the images which you want to add copy them Navigate to app > res > drawable and right-click on it. Simply paste it and add all the images to the drawable folder. 

Step 6: Working with the MainActivity.kt file

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

Kotlin




package com.gtappdevelopers.kotlingfgproject
  
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
  
class MainActivity : AppCompatActivity() {
  
    // on below line we are creating variable for view pager, 
    // viewpager adapter and the image list.
    lateinit var viewPager: ViewPager
    lateinit var viewPagerAdapter: ViewPagerAdapter
    lateinit var imageList: List<Int>
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
          
        // initializing variables 
        // of below line with their id.
        viewPager = findViewById(R.id.idViewPager)
          
        // on below line we are initializing 
        // our image list and adding data to it.
        imageList = ArrayList<Int>()
        imageList = imageList + R.drawable.android
        imageList = imageList + R.drawable.c
        imageList = imageList + R.drawable.java
        imageList = imageList + R.drawable.js
        imageList = imageList + R.drawable.python
          
        // on below line we are initializing our view 
        // pager adapter and adding image list to it.
        viewPagerAdapter = ViewPagerAdapter(this@MainActivity, imageList)
          
        // on below line we are setting 
        // adapter to our view pager.
        viewPager.adapter = viewPagerAdapter
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads