Handling Android ListView onItemClick Event

Waqas Anwar
14 August 2011
274373 Views

Android ListView control is designed to display a list of items to the user and the most common action users perform with the ListView is the item selection by just tapping any particular item in the ListView. ListView allows developers to handle user tapping by attaching the OnItemClickListener and overriding the onItemClick event. In most cases, when user click any item in the ListView, a new android activity opens that shows the details related to the selected item. To implement such scenario the knowledge of Android Intents and activity to activity communication is required. I will show you that in my future tutorials. In this tutorial, I will demonstrate you how you can handle the click events in ListView.

Create a new Android project in Eclipse with MainActivity as your default Activity and main.xml as your default layout file. Declare a ListView control in your main.xml layout file as shown in the following code.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   
   <ListView
      android:id="@+id/listView1"
      android:layout_height="fill_parent"
      android:layout_width="fill_parent" />


</LinearLayout>

The above code is using simple LinearLayout with vertical orientation, and a ListView is declared to cover the entire width and height of the parent container using the fill_parent as the value of both android:layout_height and android:layout:width properties. ListView also has a unique id listView1 that will be used in the MainActivity to reference the ListView control.

Before I show you the MainActivity code, you need to create a java class whose objects you will bind with the ListView. Add a new class Product in your Android project and add the following code in it.


Product.java
public class Product {
    private int id;
    private String name;
    private double price;
   
    public Product(){
        super();
    }
   
    public Product(int id, String name, double price) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return this.id + ". " + this.name + " [$" + this.price + "]";
    }

}

Inside the MainActivity,  an array of Product objects is created and an ArrayAdapter is used to bind the array with the ListView. To handle the ListView item click events you need to use setOnItemClickListener method of ListView class. This method requires an object of the class that is implementing OnItemClickListener interface. In this particular case, I have decided to create implementation on the fly using java anonymous class. To implement OnItemClickListener interface, the method onItemClick must need to be defined as shown in the code below. This method will be fired everytime user will click any item in the ListView. By default, ListView uses the TextView objects to render every item in the List so the onItemClick implementation shown here simply cast the internal view to TextView and gets the string displayed on the TextView using the getText() method of the TextView class. Finally, the selected item text is displayed using the Android Toast class.


MainActivity.java
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        ListView listView1 = (ListView) findViewById(R.id.listView1);
       
        Product[] items = {
            new Product(1, "Milk", 21.50),
            new Product(2, "Butter", 15.99),
            new Product(3, "Yogurt", 14.90),
            new Product(4, "Toothpaste", 7.99),
            new Product(5, "Ice Cream", 10.00),
        };
       
       
ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this,
                    android.R.layout.simple_list_item_1, items);
       
        listView1.setAdapter(adapter);

        listView1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
               
                String item = ((TextView)view).getText().toString();
               
                Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
               
            }
        });


    }
}

Run your project and click any item in the ListView. You will be able to see the selected item text in a Toast message as shown in the screenshot below.

Android ListView onItemClick