Read about Kotlin Image Slider From URL with Indicator, ViewPager in Android example.
We will create dynamic and automatic image slider which fetch images from URL using Kotlin language.
You can use this android image slider with swipe and indicator example for an app introduction.
User will be able to swipe right or left in this image slider.
System will load the image from the remote server using it’s URL.
At the bottom of the slider there is one circular indicator which shows user which number of slider is currently displayed.
For more reference, go through the below video.
Now follow all the following steps to make an image slider from URL in kotlin.
Step 1. Permission and Gradle Writing
First of all, make a new project in the android studio.
Now open the file AndroidManifest.xml
Inside this AndroidManifest.xml file, add the following line
<uses-permission android:name="android.permission.INTERNET"/>
Above line is giving our app a permission to use the internet of the android device.
If you do not add the above line in the manifest file, then our app will not be able to use the internet and hence it will not be able to fetch or load the images from the URL.
Final code lines for AndroidManifest.xml file, should look like the below
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.imagesliderurlkotlin"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
Now open your build.gradle(Module:app) file and write the following lines inside it
implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1' implementation 'com.github.bumptech.glide:glide:4.7.1' implementation 'com.android.support:design:27.1.1'
First line is for integrating the Jake Wharton library into our project.
This Jake Wharton library will allow us to create the image slider with indicator.
Now see the second line which is giving us the access to the library of Glide.
Glide library will help us to fetch the Images from URL in the easiest possible way.
After adding all these libraries, final code for our build.gradle(Module:app) file should be like this :
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 27 defaultConfig { applicationId "com.example.imagesliderurlkotlin" minSdkVersion 19 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1' implementation 'com.github.bumptech.glide:glide:4.7.1' implementation 'com.android.support:design:27.1.1' }
Step 2. Specific Layout File and Adapter
Now we have to make one XML layout file which will help us to define layout structure of each slide.
We want only image slides so we need to put ImageView inside this layout file.
So navigate to app->res->layout folder and create a new XML file with name slidingimages_layout.xml
Now in this slidingimages_layout.xml file, add the below source snippet
<?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>
You can see that above file includes only one UI widget which is ImageView.
Every slide will inherit the view structure of the above file. If you want other widgets like text view then you can add as per your requirements.
Now it is time to make adapter class which will put data inside our slider.
Make a new Kotlin class and set it’s name as SlidingImage_Adapter.kt
Write down the following coding lines inside this SlidingImage_Adapter.kt file.
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 com.bumptech.glide.Glide /** * Created by Parsania Hardik on 23/04/2016. */ class SlidingImage_Adapter(private val context: Context, private val urls: Array<String>) : 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 urls.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 Glide.with(context) .load(urls[position]) .into(imageView) 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 } }
Now let us understand the most important lines from the above code.
First of all, see the following lines of instantiateItem() method.
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 Glide.with(context) .load(urls[position]) .into(imageView) view.addView(imageLayout, 0) return imageLayout }
First line of this method will inflate the XML file slidingimages_layout.xml
Then it will find the imageview which we added in slidingimages_layout.xml file.
After this, compiler will use the Glide library. Using Glide library, it will load the image from the URL into the image view.
Step 3. Final Work
There are two files which system have created automatically in your new android studio project. These two files are : activity_main.xml and MainActivity.kt
In your activity_main.xml file, you need to set the following code lines
<?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"> <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>
You can find view pager in the above coding lines.
View pager is the base of the image slider. It will allow us to create sliders which we will show inside the boundaries of the view pager.
After this, there is CirclePageIndicator which is the indicator of the image slider.
Here, you change the size, placement and color of the indicator as per your choice.
Now in your MainActivity.kt file, below code is required,
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.Timer import java.util.TimerTask class MainActivity : AppCompatActivity() { private val urls = arrayOf( "https://demonuts.com/Demonuts/SampleImages/W-03.JPG", "https://demonuts.com/Demonuts/SampleImages/W-08.JPG", "https://demonuts.com/Demonuts/SampleImages/W-10.JPG", "https://demonuts.com/Demonuts/SampleImages/W-13.JPG", "https://demonuts.com/Demonuts/SampleImages/W-17.JPG", "https://demonuts.com/Demonuts/SampleImages/W-21.JPG" ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) init() } private fun init() { mPager = findViewById(R.id.pager) as ViewPager mPager!!.adapter = SlidingImage_Adapter(this@MainActivity, urls) val indicator = findViewById(R.id.indicator) as CirclePageIndicator indicator.setViewPager(mPager) val density = resources.displayMetrics.density //Set circle indicator radius indicator.radius = 5 * density NUM_PAGES = urls.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 } }
Deep in Main Activity
First of all, see the below lines of code
private val urls = arrayOf( "https://demonuts.com/Demonuts/SampleImages/W-03.JPG", "https://demonuts.com/Demonuts/SampleImages/W-08.JPG", "https://demonuts.com/Demonuts/SampleImages/W-10.JPG", "https://demonuts.com/Demonuts/SampleImages/W-13.JPG", "https://demonuts.com/Demonuts/SampleImages/W-17.JPG", "https://demonuts.com/Demonuts/SampleImages/W-21.JPG" )
Compiler will make a string array named “urls”. As per name suggests, this string array holds the value of six urls from which we will fetch the images.
Now see the method init() . Let us see it’s lines one by one. See the following first
mPager!!.adapter = SlidingImage_Adapter(this@MainActivity, urls) val indicator = findViewById(R.id.indicator) as CirclePageIndicator indicator.setViewPager(mPager)
First line will bind the adapter to the view pager.
Second one will find the indicator from it’s id. Last line will set the indicator to the view pager.
Now see the below
indicator.radius = 5 * density NUM_PAGES = urls.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)
First line is setting the radius of the circular indicator. You can change it as per you choice.
Then NUM_PAGES holds the number of sliders.
Then after, compiler will start the slider automatically using thread and handler. By default it will slide every 3 seconds. You can change this by changing value from 3000 to your desired value.
JAVA version of this tutorial : https://demonuts.com/android-image-slider-from-url/
Download Code For Kotlin Image Slider From URL From Github
https://github.com/demonuts/Kotlin-Image-Slider-From-URL-Indicator-ViewPager-Android