Android Kotlin Image Slider tutorial with example is the main task of our right now.
We will use circular dot navigation indicator to tell user which slide number is currently going on.
This tutorial also includes the automatic slide show with custom time line between each slide.
We need to use the Viewpager to develop this tutorial programmatically.
If you want to develop this example with Java language, then visit automatic image slider android tutorial.
Output
Step 1. Add dependency
We will use One github library in this tutorial.
Add following lines into your build.gradle(Module:app) file
compile ('com.github.JakeWharton:ViewPagerIndicator:2.4.1') { exclude group: 'com.android.support' exclude module: 'appcompat-v7' exclude module: 'support-v4' }
Step 2. Add Images
Add some images to show into the slider.
Download images by clicking the below link.
[sociallocker]Download images to add into slider[/sociallocker]
You need to add this images into the drawable folder of android studio project.
You can see the drawable directory path in below image.
Step 3. Model Class
Now, we require model class in this example.
Create a new kotlin class named ImageModel.kt and then add below source code in it.
/** * Created by Parsania Hardik on 03-Jan-17. */ class ImageModel { private var image_drawable: Int = 0 fun getImage_drawables(): Int { return image_drawable } fun setImage_drawables(image_drawable: Int) { this.image_drawable = image_drawable } }
Step 4. Single slide layout
Make one new layout resource file named slidingimages_layout.xml and add following code
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="1dip" > <ImageView android:id="@+id/image" android:layout_width="fill_parent" android:layout_height="fill_parent" android:adjustViewBounds="true" android:layout_gravity="center" android:src="@mipmap/ic_launcher" android:scaleType="centerCrop" /> </FrameLayout>
Step 5. Adapter Class
Adapter class will provide data to the viewpager.
Prepare a new class named SlidingImage_Adapter.kt
Copy and paste following source code into it
import android.content.Context import android.os.Parcelable import android.support.v4.view.PagerAdapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import java.util.ArrayList /** * Created by Parsania Hardik on 23/04/2016. */ class SlidingImage_Adapter(private val context: Context, private val imageModelArrayList: ArrayList<ImageModel>) : PagerAdapter() { private val inflater: LayoutInflater init { inflater = LayoutInflater.from(context) } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun getCount(): Int { return imageModelArrayList.size } override fun instantiateItem(view: ViewGroup, position: Int): Any { val imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false)!! val imageView = imageLayout .findViewById(R.id.image) as ImageView imageView.setImageResource(imageModelArrayList[position].getImage_drawables()) view.addView(imageLayout, 0) return imageLayout } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } override fun restoreState(state: Parcelable?, loader: ClassLoader?) {} override fun saveState(): Parcelable? { return null } }
Step 6. Update Main Activity
Replace your existing code of activity_main.xml with below one
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="16dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="16dp" tools:context="com.example.parsaniahardik.kotlin_image_slider.MainActivity"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" > <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentTop="true" /> <com.viewpagerindicator.CirclePageIndicator android:id="@+id/indicator" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:gravity="bottom" android:padding="10dip" app:centered="true" app:fillColor="#df0623" app:pageColor="#fff" app:snap="false" /> </RelativeLayout> </RelativeLayout>
Now whole code for MainActivity.kt is something like below
import android.os.Handler import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.os.Bundle import com.viewpagerindicator.CirclePageIndicator import java.util.ArrayList import java.util.Timer import java.util.TimerTask class MainActivity : AppCompatActivity() { private var imageModelArrayList: ArrayList<ImageModel>? = null private val myImageList = intArrayOf(R.drawable.harley2, R.drawable.benz2, R.drawable.vecto, R.drawable.webshots, R.drawable.bikess, R.drawable.img1) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) imageModelArrayList = ArrayList() imageModelArrayList = populateList() init() } private fun populateList(): ArrayList<ImageModel> { val list = ArrayList<ImageModel>() for (i in 0..5) { val imageModel = ImageModel() imageModel.setImage_drawables(myImageList[i]) list.add(imageModel) } return list } private fun init() { mPager = findViewById(R.id.pager) as ViewPager mPager!!.adapter = SlidingImage_Adapter(this@MainActivity, this.imageModelArrayList!!) val indicator = findViewById(R.id.indicator) as CirclePageIndicator indicator.setViewPager(mPager) val density = resources.displayMetrics.density //Set circle indicator radius indicator.setRadius(5 * density) NUM_PAGES = imageModelArrayList!!.size // Auto start of viewpager val handler = Handler() val Update = Runnable { if (currentPage == NUM_PAGES) { currentPage = 0 } mPager!!.setCurrentItem(currentPage++, true) } val swipeTimer = Timer() swipeTimer.schedule(object : TimerTask() { override fun run() { handler.post(Update) } }, 3000, 3000) // Pager listener over indicator indicator.setOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageSelected(position: Int) { currentPage = position } override fun onPageScrolled(pos: Int, arg1: Float, arg2: Int) { } override fun onPageScrollStateChanged(pos: Int) { } }) } companion object { private var mPager: ViewPager? = null private var currentPage = 0 private var NUM_PAGES = 0 } }
Step 7. Stop Auto Slide
Sometimes you may have to stop the auto sliding feature.
For this purpose, consider following code
// Auto start of viewpager val handler = Handler() val Update = Runnable { if (currentPage == NUM_PAGES) { currentPage = 0 } mPager!!.setCurrentItem(currentPage++, true) } val swipeTimer = Timer() swipeTimer.schedule(object : TimerTask() { override fun run() { handler.post(Update) } }, 3000, 3000)
If you want stop auto slide then comment out the above code.
We have used Timer class to specify a time interval for each auto sliding.
You can also swipe manually when auto sliding is enabled.
Here sliding interval time is set as 3 seconds. You can change it by updating below
val swipeTimer = Timer() swipeTimer.schedule(object : TimerTask() { override fun run() { handler.post(Update) } }, 3000, 3000)
when you updated the values 3000,3000, as a result time interval will be changed.
Download the source code for kotlin image slider
[sociallocker]Download Kotlin Android Image Slider Code[/sociallocker]
The end for kotlin image slider android tutorial.
Keep sharing our tutorial and keep coding!