Looking For Anything Specific?

Viewpager2 Android Kotlin Example With Sample Code

 Hello there,

In this tutorial, you will be learning about the new Android ViewPager2 API and how to use it, first of all, what is this android viewpager2, so if you're familiar with web development you might have come across the concept of the carousel, which is nothing but a view to show a list of images or videos in a horizontal list manner. And view pager does the same in android as it helps you to show a list of items in a horizontal listview with swipeable action, which makes it like swiping between pages, so if you want to know how to make a swipeable horizontal list view this is for you,

And if for any reason you can not find the view pager in your android studio or it shows an error when typing ViewPager2 make sure you have added the Gradle dependency check here: ViewPager2 

Learn How to Store Data In Android With Shared Preference In Kotlin

Still not understand what ViewPager2 can do below is the sample output of the code that we are going to type, which will give an insight into android ViewPager2.



You may wonder why what is with number two at the end of the view, is there a previous version to it, Yes there was ViewPager but we skipped them because android developer docs recommend us to migrate to ViewPager2, so let us start with Android ViewPager2, if you followed my previous tutorials on RecyclerView listed below, then I would say this is going to be a piece of cake for you, if not I suggest you learn more about the android RecyclerView below

Complete Guide On Android RecyclerView With Kotlin

Okay, Let's Jump to the code, As you can see that this view, ViewPager2 is used to display the list of items in a page style with swipeable action, so we need to create a page item layout which is where are going to show our content from the list, And for this example, we are using a list of images that I have collected from unsplash.com the images at this website is cool and they are free to use so do check it out.

How to Create Customized Buttons In Android With Rounded Corners

Now we will start by creating a new layout which is how our page will look like, and I have named it viewpage_item.xml

  
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/image_000"
        android:scaleType="centerCrop"/>

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/pageNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        android:background="@color/white"
        android:padding="16dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:text="Image Name" />

</androidx.constraintlayout.widget.ConstraintLayout>
  

This is just a simple view with ImageView and TextView to display some images along with their position.

how to create viewpager in android


Once created the view layout file now we move on to our MainActivity layout where we add new viewpager2



<?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"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>


This simple layout has only one view which the viewpager2, to display the data in this android viewpager2 we need to have an adapter, as surprising it may sound, we are going to we a recycler view adapter

Learn How to Add Circle Indicators to android viewpager

You can learn about the android recycler view here:

Now create a simple recycler view adapter and name it as you like, for example, ImageViewPagerAdapter.kt



package com.madtutorials.viewpager2example.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.madtutorials.viewpager2example.R

class ImageViewPagerAdapter : RecyclerView.Adapter<ImageViewPagerAdapter.ViewHolder>() {

    private val imagesList = arrayListOf(
        R.drawable.image_000, R.drawable.image_0600, R.drawable.image_0900,
        R.drawable.image_1400, R.drawable.image_1600
    )

    class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater
        .from(parent.context)
        .inflate(R.layout.viewpager_item,parent,false))
    }

    override fun getItemCount(): Int = imagesList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.view.findViewById<AppCompatImageView>(R.id.imageView).let {
            it.setImageDrawable(ContextCompat.getDrawable(it.context,imagesList[position]))
        }
        holder.view.findViewById<AppCompatTextView>(R.id.pageNumber).text = "$position"
    }
}

The above code is a simple recycler view adapter with a RecyclerView view holder, where we have a list of images as an array list to display in our viewpager2 and to display the position of the page where we are at.

Learn About Android Fragments Here

With this all we have to do is connect the adapter with the viewpager2, which is also simple as it is,For that, all you have to do is just find the view pager with findViewById the set the adapter with ImageViewPagerAdapter()


package com.madtutorials.viewpager2example

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.viewpager2.widget.ViewPager2
import com.madtutorials.viewpager2example.adapter.ImageViewPagerAdapter

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<ViewPager2>(R.id.viewPager).adapter = ImageViewPagerAdapter()

    }
}


That's all now you have swiping image view, Thanks for reading.

Download Full Code: Github Link

keywords:

android viewpager2 tutorial

android viewpager2 guide

viewpager2 with recyclerview adapter

viewpager2 kotlin 

viewpager2 android kotlin example

Post a Comment

0 Comments