Open In App

How to Detect Long Press on ListView Items in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

ListView in Android is a ViewGroup that is used to display items in rows and has an adapter that inserts the desired elements into the list. Once the items are inserted into the ListView, they can be clicked and the desired action can be performed.

As multiple operations can be performed on a ListView, in this article, we will show you how you could handle a long press on the items in ListView.

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. Add a ListView in the layout.

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">
 
    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 
</RelativeLayout>


Step 3: 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




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // Create a list of items
        val mCity = arrayOf("Delhi", "Mumbai", "Hyderabad", "Pune", "Bengaluru", "Chennai", "Kolkata", "Jaipur", "Lucknow", "Bhopal")
 
        // Declare and initialize the ListView
        val mListView: ListView = findViewById(R.id.listView)
 
        // Create adapter for the list view
        val mAdapter: ArrayAdapter<*> = ArrayAdapter<Any?>(this, android.R.layout.simple_list_item_1, mCity)
        mListView.adapter = mAdapter
 
        // Handle long press on the ListView item
        mListView.onItemLongClickListener = AdapterView.OnItemLongClickListener { _, _, index, _ ->
            Toast.makeText(applicationContext, "Long clicked on ${mCity[index]}", Toast.LENGTH_SHORT).show()
            true
        }
    }
}


Java




import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // Call the superclass onCreate method
        super.onCreate(savedInstanceState);
 
        // Set the layout for the activity
        setContentView(R.layout.activity_main);
 
        // Create a list of items to be displayed
        String[] mCity
            = { "Delhi",   "Mumbai",    "Hyderabad",
                "Pune",    "Bengaluru", "Chennai",
                "Kolkata", "Jaipur",    "Lucknow",
                "Bhopal" };
 
        // Declare and initialize the ListView
        ListView mListView
            = (ListView)findViewById(R.id.listView);
 
        // Create an adapter for the list view
        ArrayAdapter mAdapter = new ArrayAdapter(
            this, android.R.layout.simple_list_item_1,
            mCity);
 
        // Set the adapter for the list view
        mListView.setAdapter(mAdapter);
 
        // Handle long press on an item in the ListView
        mListView.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(
                    AdapterView<?> parent, View view,
                    int index, long id)
                {
                    // Show a Toast message with the name of
                    // the city
                    Toast
                        .makeText(getApplicationContext(),
                                  "Long clicked on "
                                      + mCity[index],
                                  Toast.LENGTH_SHORT)
                        .show();
                    return true;
                }
            });
    }
}


Output:

You can see that upon long press on any element, a message about the items is displayed. You can customize the operation to perform any desired action.



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