Open In App

Implement Android Pull-to-Refresh with ListVIew using Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Swipe to Refresh Layout is used in most social media applications such as Facebook or Instagram. In these applications, users can simply swipe down to refresh the posts or feeds within the applications to load the new ones. Swipe to refresh layout detects vertical swipe and displays a progress bar. After that, the listview will be updated with the new data from the database. In this article, we will take a look at How to implement Pull to Refresh ListView in Android using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement the similar feature within the android application using Java language. Check out the following article: Pull to refresh with listview in android using Java 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Adding dependencies to build.gradle

We are using SwipeRefreshLayout. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency you need to click on Sync Now.

implementation ‘androidx.swiperefreshlayout:swiperefreshlayout:1.1.0’ 

After adding this dependency simply sync your project to install the dependency. 

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating a swipe to refresh layout-->
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/idSwipeToRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--on below line we are creating a list view-->
    <ListView
        android:id="@+id/idListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
   
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>


Step 4: Create an XML layout file for each item of ListView

Create an XML file for each grid item to be displayed in ListView. Click on the app > res > layout > Right Click > Layout Resource file and then name the file as gridview_item. Below is the code for the gridview_item.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
       xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="0dp">
       
    <!--on below line we are creating a
         linear layout for grid view item-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <!--on below line we are creating a simple image view-->
        <ImageView
            android:id="@+id/idIVCourse"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:padding="5dp"
            android:src="@mipmap/ic_launcher" />
 
        <!--on below line we are creating a simple text view-->
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:padding="4dp"
            android:text="@string/app_name"
            android:textAlignment="textStart"
            android:textColor="@color/black"
            android:textStyle="bold"
            tools:ignore="RtlCompat" />
 
    </LinearLayout>
 
</androidx.cardview.widget.CardView>


Step 5: Create a Modal Class for storing Data

Modal Class is the JAVA Class that handles data to be added to each ListView item of ListView. For Creating Modal Class. Navigate to app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and specify the name as ListViewModal and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
// on below line we are creating a modal class.
data class ListViewModal(
    // we are creating a modal class with 2 member
    // one is course name as string
    // and other course img as int.
    val courseName: String,
    val courseImg: Int
)


Step 6: Creating the Adapter class

Adapter Class adds the data from Modal Class in each item of ListView which is to be displayed on the screen. For Creating Adapter Class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and specify the name as CourseLVAdapter and add below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
 
// on below line we are creating
// an adapter class for our grid view.
internal class CourseLVAdapter(
    // on below line we are creating two variables
    // for course list and context
    private val courseList: List<ListViewModal>,
    private val context: Context
) :
    BaseAdapter() {
     
    // in base adapter class we are creating variables for
    // layout inflater, course image view and course text view.
    private var layoutInflater: LayoutInflater? = null
    private lateinit var courseTV: TextView
    private lateinit var courseIV: ImageView
 
    // below method is use to return the count of course list
    override fun getCount(): Int {
        return courseList.size
    }
 
    // below function is use to return the item of grid view.
    override fun getItem(position: Int): Any? {
        return null
    }
     
    // below function is use to return item id of grid view.
    override fun getItemId(position: Int): Long {
        return 0
    }
 
    // in below function we are getting individual item of grid view.
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
        var convertView = convertView
        // on blow line we are checking if layout inflater
        // is null, if it is null we are initializing it.
        if (layoutInflater == null) {
            layoutInflater =
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        }
        // on below line we are checking if convert view is null.
        // If it is null we are initializing it.
        if (convertView == null) {
            // on below line we are passing the layout file
            // which we have to inflate for each item of grid view.
            convertView = layoutInflater!!.inflate(R.layout.gridview_item, null)
        }
        // on below line we are initializing our course image view
        // and course text view with their ids.
        courseIV = convertView!!.findViewById(R.id.idIVCourse)
        courseTV = convertView!!.findViewById(R.id.idTVCourse)
         
        // on below line we are setting image for our course image view.
        courseIV.setImageResource(courseList.get(position).courseImg)
         
        // on below line we are setting text in our course text view.
        courseTV.setText(courseList.get(position).courseName)
         
        // at last we are returning our convert view.
        return convertView
    }
}


Step 7: Adding images to drawable folder.

Copy your images. Navigate to app > res > drawable> Right-click on it and paste all the images which are copies within the drawable folder.

Step 8: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import java.util.*
import kotlin.collections.ArrayList
 
class MainActivity : AppCompatActivity() {
    // on below line we are creating variables for list view,
    // swipe to refresh layout and course list
    lateinit var courseLV: ListView
    lateinit var swipeToRefreshLV: SwipeRefreshLayout
    lateinit var courseList: List<ListViewModal>
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // initializing variables of list view and
        // swipe refresh view with their ids.
        courseLV = findViewById(R.id.idListView)
        swipeToRefreshLV = findViewById(R.id.idSwipeToRefresh)
        courseList = ArrayList<ListViewModal>()
         
        // on below line we are adding data to our
        // course list with image and course name.
        courseList = courseList + ListViewModal("C++", R.drawable.c)
        courseList = courseList + ListViewModal("Java", R.drawable.java)
        courseList = courseList + ListViewModal("Android", R.drawable.android)
        courseList = courseList + ListViewModal("Python", R.drawable.python)
        courseList = courseList + ListViewModal("Javascript", R.drawable.js)
 
        // on below line we are initializing our course adapter
        // and passing course list and context.
        val courseAdapter = CourseLVAdapter(courseList = courseList, this@MainActivity)
         
        // on below line we are setting adapter to our grid view.
        courseLV.adapter = courseAdapter
         
        // on below line we are adding on item click listener for our grid view.
        courseLV.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            // inside on click method we are simply displaying
            // a toast message with course name.
            Toast.makeText(
                applicationContext, courseList[position].courseName + " selected",
                Toast.LENGTH_SHORT
            ).show()
        }
 
        // on below line we are initializing our swipe to refresh
        // layout by calling set in refresh listener method
        swipeToRefreshLV.setOnRefreshListener {
             
            // on below line we are setting refreshing to false/
            swipeToRefreshLV.isRefreshing = false
             
            // on below line we are creating a variable
            // for our original list
            val originalList = courseList.toMutableList()
             
            // on below line we are shuffling our list.
            val shuffledList = originalList.shuffled()
             
            // on below line we are initializing our course adapter
            // and passing course list and context.
            val courseAdapter = CourseLVAdapter(courseList = shuffledList, this@MainActivity)
             
            // on below line we are setting adapter to our list view.
            courseLV.adapter = courseAdapter
        }
 
    }
}


Now run your application to see the output of it. 

Output: 



Last Updated : 17 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads