Open In App

How to Detect Scroll Up and Down Gestures in a ListView in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

A ListView in Android is a scrollable list used to display items. Data, which is a list or array of items fetched from a source or hardcoded in the application can be displayed row-wise using a ListView. If the items are less, then the list may not even reach the bottom of the screen. However, if the items are large in number, then they may go beyond the bottom of the screen, where a scroll function takes entry and lets users scroll up and down to discover the covered items. 

In this article, we will show you how you could detect scrolls up and down in a ListView. Follow the below steps once the IDE is ready.

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. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: 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. We implemented a TextView that shall display the scrolling status and a ListView that shall display items.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Scroll Status"
        android:textSize="20sp"
        android:gravity="center"/>
 
    <ListView
        android:id="@+id/list_view"
        android:layout_below="@id/text_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 
</RelativeLayout>


Step 3: Working with the MainActivity.kt file

In the main code, we declared an array list of elements (numbers from 1 to 30). Using an adapter this array is displayed into the ListView. A scroll listener is called on the ListView to get information on the first visible item, total visible items, and total item count. A buffer index variable is initially set to 0. Now, according to our algorithm, if the first visible element index is greater than the buffer variable, then we are basically scrolling down. Else we are scrolling up. Now refer to the below code.

Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        val mList = arrayOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
            "11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
            "21", "22", "23", "24", "25", "26", "27", "28", "29", "30",)
 
        val mListView = findViewById<ListView>(R.id.list_view)
        val mTextView = findViewById<TextView>(R.id.text_view)
        val mAdapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, mList)
 
        mListView.adapter = mAdapter
 
        mListView.setOnScrollListener(object : AbsListView.OnScrollListener{
            override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) {
                // Do nothing
            }
 
            private var lastFirstVisibleItem = 0
 
            override fun onScroll(view: AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
                if (lastFirstVisibleItem < firstVisibleItem) {
                    // Down
                    mTextView.text = "Scrolling down"
                }
                if (lastFirstVisibleItem > firstVisibleItem) {
                    // Up
                    mTextView.text = "Scrolling Up"
                }
                lastFirstVisibleItem = firstVisibleItem
            }
        })
 
    }
}


Java




import android.app.Activity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
 
// MainActivity extends the built-in Activity class
public class MainActivity extends Activity {
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // Call the parent's onCreate method
    super.onCreate(savedInstanceState);
 
    // Set the content view to the activity_main layout
    setContentView(R.layout.activity_main);
 
    // Create a list of strings
    String[] mList = new String[] {
      "1""2""3""4""5""6""7""8",
      "9""10", "11", "12", "13", "14", "15", "16",
      "17", "18", "19", "20", "21", "22", "23", "24",
      "25", "26", "27", "28", "29", "30"
    };
 
    // Get the ListView and TextView from the layout
    ListView mListView = findViewById(R.id.list_view);
    TextView mTextView = findViewById(R.id.text_view);
 
    // Create an ArrayAdapter with the list of strings
    ArrayAdapter<String> mAdapter = new ArrayAdapter<>(
      this,
      R.layout.support_simple_spinner_dropdown_item,
      mList
    );
 
    // Set the adapter for the ListView
    mListView.setAdapter(mAdapter);
 
    // Set an OnScrollListener for the ListView
    mListView.setOnScrollListener(
      new AbsListView.OnScrollListener() {
        // Store the first visible item from the previous scroll event
        private int lastFirstVisibleItem = 0;
 
        // Called when the scroll state changes
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
          // Do nothing
        }
 
        // Called when the ListView is scrolled
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
          // Check if the ListView is scrolling down
          if (lastFirstVisibleItem < firstVisibleItem) {
            mTextView.setText("Scrolling down");
          }
          // Check if the ListView is scrolling up
          if (lastFirstVisibleItem > firstVisibleItem) {
            mTextView.setText("Scrolling up");
          }
          // Update the first visible item
          lastFirstVisibleItem = firstVisibleItem;
        }
      }
    );
  }
}


Output:

We can see that when we scroll down, the TextView displays “Scrolling Down”. When we scroll up, it displays “Scrolling Up”.



Last Updated : 26 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads