Android Image Slider using ViewPager in Kotlin
Last Updated :
30 May, 2022
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:android="http://schemas.android.com/apk/res/android"
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
xmlns:android="http://schemas.android.com/apk/res/android"
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:
Similar Reads
Image Slider in Android using ViewPager
When talking about Android Apps, the first thing that comes to mind is variety. There are so many varieties of Android apps providing the user with beautiful dynamic UI. One such feature is to navigate in the Android Apps using the left and right swipes as opposed to clicking on Buttons. Not only do
4 min read
Android ViewPager in Kotlin
ViewPager adds a sleek, swipeable interface that lets users effortlessly navigate between pages, just like flipping through a book. This feature is common in social media apps; for instance, WhatsApp greets you with three intuitive tabs: chats, status, and calls. This makes the app look cool. You've
5 min read
Android Auto Image Slider with Kotlin
Most e-commerce application uses auto image sliders to display ads and offers within their application. Auto Image Slider is used to display data in the form of slides. In this article, we will take a look at the Implementation of Auto Image Slider in our Android application using Kotlin. A sample v
5 min read
Cube in Scaling Animation with ViewPager in Android
The Android ViewPager has become a very interesting concept among Android apps. It enables users to switch smoothly between fragments which have a common UI and itâs the best way to make your app extraordinary from others. ViewPagers provide visual continuity. They basically keep track of which page
4 min read
Android Slide Up/Down in Kotlin
In Android Animations are the visuals that are added to make the user interface more interactive, clear and good looking. In this article we will be discussing how to create a Slide Up/Down animation in Kotlin. XML Attributes Description android:duration It is used to specify the duration of animati
3 min read
Slide Animation in Android with Kotlin
Animations in Android allow UI elements to perform aesthetic moves across the screen. Animations can be implemented from a third party as well as developed from scratch. Despite the source, animations can be applied to any kind of view or UI element. Typically, we have demonstrated a slide animation
3 min read
Android View Shaker in Kotlin
View Shaker is an android animation in which the UI of the screen vibrates for a specific interval of time. We can implement this View shaker to the specific views of the application. View Shaker provides different animation effects which we can add to our views such as bounce, fade, float, and othe
4 min read
Android ListView in Kotlin
ListView in Android is a ViewGroup which is used to display a scrollable list of items arranged in multiple rows. It is attached to an adapter which dynamically inserts the items into the list. The main purpose of the adapter is to retrieve data from an array or a database and efficiently push every
3 min read
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this
8 min read
ViewPager Using Fragments in Android with Example
ViewPager is a layout manager that allows the user to flip left and right through pages of data. It is a depreciated concept we are using ViewPager2 now. It is mostly found in apps like Youtube, Snapchat where the user shifts right-left or top-bottom to switch to a screen. Instead of using activitie
6 min read