Kotlin Create Slider With Page Indicator Using ViewPager Example

Last updated Jan 22, 2020

Kotlin Create Slider With Page Indicator Using ViewPager Example

Viewpager  we can do a lot of things, from the simplest navigation, to the page menu and so on. Then how to use it, similar to ListView, we also need an adapter, which is PagerAdapter

In this post we are going to see  page indicator on slider that are created using viewpager

Kotlin Create Slider With Page Indicator Using ViewPager Example

Step 1:Creat application in Android Stuido

Step 2: Create a model class which contains Slider item

import java.io.Serializable

class ViewItem : Serializable {
    var imageId: Int
    internal set
    var imageDrawable: Int
    internal set

            constructor(id: Int, drawable: Int) {
                this.imageId = id
                this.imageDrawable = drawable
            }
}

 

Step 3: Create Pager Adapter

class ViewPagerAdapter(internal var context: Context, internal var itemList: List<ViewItem>) : PagerAdapter() {

    internal var mLayoutInflater: LayoutInflater
    private var pos = 0

    init {
        mLayoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }

    override fun getCount(): Int {
        return Integer.MAX_VALUE
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val holder = ViewHolder()
        val itemView = mLayoutInflater.inflate(R.layout.layout_item_view_pager, container, false)
        holder.itemImage = itemView.findViewById(R.id.img_slider) as ImageView

        if (pos > this.itemList.size - 1)
            pos = 0

        holder.sliderItem = this.itemList[pos]
        holder.itemImage.setImageDrawable(context.getDrawable(holder.sliderItem.imageDrawable))

        (container as ViewPager).addView(itemView)

        holder.itemImage.scaleType = ImageView.ScaleType.FIT_XY

        pos++
        return itemView
    }

    internal class ViewHolder {
        lateinit var sliderItem: ViewItem
        lateinit var itemImage: ImageView
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as RelativeLayout)
    }

    override fun isViewFromObject(arg0: View, arg1: Any): Boolean {
        return arg0 === arg1 as View
    }

    override fun destroyItem(arg0: View, arg1: Int, arg2: Any) {
        (arg0 as ViewPager).removeView(arg2 as View)
    }
}

 

ViewPager adapter is PagerAdapter, which is the base class that provides the adapter to fill the page ViewPager's internals. You may want to use a more specific implementation, such as FragmentPagerAdapter or FragmentStatePagerAdapter. It needs to be explained here, in fact, ViewPager should be used with Fragment, at least Google officially thinks so, but under 3.0, we do not need to do so. Note that when you implement a PagerAdapter, you must at least override the following methods:

  • instantiateItem(ViewGroup, int)
  • destroyItem(ViewGroup, int, Object)
  • getCount()
  • isViewFromObject(View, Object)

Step 4:
Add Adapter view item layout_item_view_pager.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

    <ImageView
            android:id="@+id/img_slider"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY" />

</LinearLayout>

 

Step 5: 
 Update activity_main.xml with Viewpager and page indicator layout

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

    <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <androidx.viewpager.widget.ViewPager
                android:id="@+id/view_pager"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:focusable="true"
                android:focusableInTouchMode="true" />

        <LinearLayout
                android:id="@+id/lyt_page_indicator"
                android:layout_width="match_parent"
                android:layout_height="25dp"
                android:layout_alignParentBottom="true"
                android:gravity="center"
                android:orientation="horizontal"></LinearLayout>

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
 

 

Step 6:
 Addrequired Resourses to the application

Step 7:
 Add Adapter to Viewpager

fun initUI()
    {
        listViews=ArrayList<ViewItem>()
        listViews.add(ViewItem(1,R.drawable.t1))
        listViews.add(ViewItem(2,R.drawable.t2))
        listViews.add(ViewItem(3,R.drawable.t3))
        listViews.add(ViewItem(4,R.drawable.t4))
        listViews.add(ViewItem(5,R.drawable.t5))

        adapter= ViewPagerAdapter(applicationContext,listViews)
        view_pager.adapter=adapter
    }

 

Step 8: Add PageIndicators to page

fun addPageIndicators()
    {
        lyt_page_indicator.removeAllViews()
        for (i in listViews.indices) {
            val view = ImageView(applicationContext)
            view.setImageResource(R.drawable.inactive)

            lyt_page_indicator.addView(view)
        }
        updatePageIndicator(currentIndex)
    }

 

Step 9:
    Update PageIndicator on Page Selection

fun updatePageIndicator(position: Int) {
        var imageView: ImageView

        val lp =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(5, 0, 5, 0)
        for (i in 0 until lyt_page_indicator.getChildCount()) {
            imageView = lyt_page_indicator.getChildAt(i) as ImageView
            imageView.setLayoutParams(lp)
            if (position == i) {
                imageView.setImageResource(R.drawable.active)
            } else {
                imageView.setImageResource(R.drawable.inactive)
            }
        }
    }

 

Complete MainActivity code

package com.rrtutors.kotlinviewpager

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.LinearLayout
import android.widget.ImageView
import androidx.viewpager.widget.ViewPager


class MainActivity : AppCompatActivity() {

    lateinit var listViews:ArrayList<ViewItem>
    lateinit var adapter:ViewPagerAdapter
    var currentIndex:Int=0;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initUI()
    }

    fun initUI()
    {
        listViews=ArrayList<ViewItem>()
        listViews.add(ViewItem(1,R.drawable.t1))
        listViews.add(ViewItem(2,R.drawable.t2))
        listViews.add(ViewItem(3,R.drawable.t3))
        listViews.add(ViewItem(4,R.drawable.t4))
        listViews.add(ViewItem(5,R.drawable.t5))

        adapter= ViewPagerAdapter(applicationContext,listViews)
        view_pager.adapter=adapter
        addPageIndicators()
        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                updatePageIndicator(position)
            }
        })
    }

    fun addPageIndicators()
    {
        lyt_page_indicator.removeAllViews()
        for (i in listViews.indices) {
            val view = ImageView(applicationContext)
            view.setImageResource(R.drawable.inactive)

            lyt_page_indicator.addView(view)
        }
        updatePageIndicator(currentIndex)
    }
    fun updatePageIndicator(position: Int) {
        var imageView: ImageView

        val lp =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        lp.setMargins(5, 0, 5, 0)
        for (i in 0 until lyt_page_indicator.getChildCount()) {
            imageView = lyt_page_indicator.getChildAt(i) as ImageView
            imageView.setLayoutParams(lp)
            if (position == i) {
                imageView.setImageResource(R.drawable.active)
            } else {
                imageView.setImageResource(R.drawable.inactive)
            }
        }
    }
}

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

4222 Views