Android - Listview Click Event


In this tutorial we will add event handling to our previously created Listview Example. We will make view-items of our list clickable. So, if you do not know about how to implement a basic listview then please go back and read our First Article.

Adding click listener to listview

After setting adapter add the following line of code in your onCreate()

listview.setOnItemClickListener(new ListClickHandler());

Now let us implement ListClickHandler class.

To make our view-items clickable we need to implement an interface called OnItemClickListener. So create an inner-class ListClickHandler in your MainActivity.

public class ListClickHandler implements OnItemClickListener{

}

The OnItemClickListener interface has a method named onItemClicked() which is called whenever view-item of listview is clicked. So we need to implement that method.

public class ListClickHandler implements OnItemClickListener{

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
		// TODO Auto-generated method stub
		TextView listText = (TextView) view.findViewById(R.id.listText);
		String text = listText.getText().toString();
		
                // create intent to start another activity
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
		// add the selected text item to our intent.
                intent.putExtra("selected-item", text);
		startActivity(intent);	
		
	}
	
}

Explanation of above code to handle click event in listview

  1. onItemClick() gives us the reference of the view-item which is clicked by the user. Note : See argument "View view".
  2. Now we know that the view which was clicked is a TextView. Get its reference so that we can fetch the text from the clicked view using the below line of code.
    TextView listText = (TextView) view.findViewById(R.id.listText);
    String text = listText.getText().toString();
  3. Now create an Intent so that we can pass the clicked item to another activity.
  4. Load intent with the string item to pass in a key-value pair using
    intent.putExtra("selected-item", text);

ScreenShot of event handling in listview

 

Complete code of our clickable listview

MainActivity.java

package com.example.listview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	ListView listview;
	String[] foody;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		listview = (ListView)findViewById(R.id.listView);

	String[] foody = {"pizza", "burger", "chocolate", "ice-cream", "banana", "apple"}; 

	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_view_row, R.id.listText, foody);
	listview.setAdapter(adapter);
	listview.setOnItemClickListener(new ListClickHandler());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

public class ListClickHandler implements OnItemClickListener{

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
		// TODO Auto-generated method stub
		TextView listText = (TextView) view.findViewById(R.id.listText);
		String text = listText.getText().toString();
		Intent intent = new Intent(MainActivity.this, SecondActivity.class);
		intent.putExtra("selected-item", text);
		startActivity(intent);	
		
	}
	
}

}

Note: for layout files of this tutorial kindly see the first part of listview tutorial Listview in Android.

Now let us implement SecondActivity to display the information.

SecondActivity.java

We have already covered the basic explanation about activity in android. So if you are unfamiliar with the below code. Kindly refer to our tutorial Basics of Activity in Android.

package com.example.listview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TextView;

public class SecondActivity extends Activity {
	TextView textView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		textView = (TextView) findViewById(R.id.textView);
		// get the intent from which this activity is called.
                Intent intent = getIntent();
  
                // fetch value from key-value pair and make it visible on TextView.
		String item = intent.getStringExtra("selected-item")
                textView.setText("you selected "+item);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.second, menu);
		return true;
	}

}

 

Below is the layout file for our second activity which is a simple xml file with a TextView.

activity_second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".SecondActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:text="" />

</RelativeLayout>

So, in this tutorial we learned about adding events in listview. In the next tutorial we will add checkbox in our listview so that user can select multiple items.