Android Auto Image Slider with URL Example Kotlin
1/ Create A New Project .
>>> main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:background="@color/white"
>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
2/ Add dependencies
>>>build.gradle.kts(Module:app)implementation ("androidx.viewpager2:viewpager2:1.0.0")
implementation ("com.github.bumptech.glide:glide:4.15.1")
annotationProcessor ("com.github.bumptech.glide:compiler:4.15.1")
3/MainActivtiy.kt
package com.imagesilderkotlin.imagesilderkotlin
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
class MainActivity : AppCompatActivity() {
private lateinit var viewPager: ViewPager2
private val handler = Handler(Looper.getMainLooper())
private var currentPage = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager = findViewById(R.id.viewPager) // Remove duplicate declaration
// Example list of image URLs
val imageUrls = listOf(
"https://scontent.fjsr1-1.fna.fbcdn.net/v/t39.30808-6/391650514_851930526468651_2724053640235114867_n.jpg?stp=c119.0.1122.1122a_dst-jpg_s206x206_tt6&_nc_cat=111&ccb=1-7&_nc_sid=50ad20&_nc_eui2=AeHPF9bp5DMcE4AYfzr6LQA-y1u7SOp4zpTLW7tI6njOlD-z_JQ83am2gk_yx0eBPAiYHF6EH5D5AqZVWCKZqdWg&_nc_ohc=d-KX0c_naRgQ7kNvgGonH0N&_nc_zt=23&_nc_ht=scontent.fjsr1-1.fna&_nc_gid=AZeKxZ35nuVBmaYHmzSVO-R&oh=00_AYDK101iIhy1TpNFoU7LjEvBH-mXW0oeGPT8mqsCf4ZqEw&oe=675250C4",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ7rwiOlo8iMshMT0XJurrdBGPZYr3qi1gdMNI4oI2MK4F8Y_NPPnMYUj8OfkwN2r8mvzw&usqp=CAU",
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ8helKOWpKwMhipcCCqcRddnKHA9txH3Y20g&s",
"https://img.freepik.com/premium-photo/3d-cartoon-android-app-developer-white-background_893610-22853.jpg?w=740",
)
val adapter = SliderAdapter(imageUrls)
viewPager.adapter = adapter
// Call the auto-slide function
startAutoSlide(imageUrls.size)
}
private fun startAutoSlide(totalPages: Int) {
val runnable = object : Runnable {
override fun run() {
if (currentPage == totalPages) {
currentPage = 0
}
viewPager.currentItem = currentPage++
handler.postDelayed(this, 3000) // Slide every 3 seconds
}
}
handler.post(runnable)
// Stop sliding when user interacts
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
currentPage = position
handler.removeCallbacks(runnable)
handler.postDelayed(runnable, 3000)
}
})
}
override fun onDestroy() {
super.onDestroy()
handler.removeCallbacksAndMessages(null)
}
}
4/ Create A New layout
layout<new<Layout Resouece File<item_slider.xml<?xml version="1.0" encoding="utf-8"?>
<android.widget.FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:layout_gravity="center_horizontal"
/>
</android.widget.FrameLayout
5/ Create a new class
package com.imagesilderkotlin.imagesilderkotlin;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.List;
public class SliderAdapter extends RecyclerView.Adapter<SliderAdapter.SliderViewHolder> {
private final List<String> imageUrls;
public SliderAdapter(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
@NonNull
@Override
public SliderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_slider, parent, false);
return new SliderViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull SliderViewHolder holder, int position) {
String imageUrl = imageUrls.get(position);
// Load the image using Glide
Glide.with(holder.itemView.getContext())
.load(imageUrl)
.into(holder.imageView);
}
@Override
public int getItemCount() {
return imageUrls.size();
}
public static class SliderViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public SliderViewHolder(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView); // Match the ID in item_slider.xml
}
}
}
6/ Internet Permision in menifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/> <!-- Internet permission -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <!-- Internet permission -->
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ImageSilderKotlin"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>