Handling Android ListView onItemClick Event

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.

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.

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.