Adding Click functionality in List View – onItemClickListener()

This entry is part 34 of 50 in the series Android Development Primer

In the previous posts we saw how we can, in a number of ways populate out List Views. However, most of the times just populating and displaying List Views aren’t enough. You must have seen that in most of the applications, we can click the items of the List View and that brings up an array of options that the programmer has programmed. We are going to learn how to add the click functionality to our List View.

Remember that the functionality described here will work in exactly in the same manner irrespective of whether it is a long click or a regular click. I will show you how to add the Long Click functionality in the list item in a separate post.
So start up an activity and follow along. Complete Source Code is at the bottom.

  • We are going to be working with ArrayAdapters just as we have been doing in the previous posts. The process of adding the click functionality remain the same even if you choose to use a different kind of adapter.
  • In the XML file of the activity, add the list view and switch to the MainActivity.java file. The source code at the bottom extends the MainActivity from ListActivity, but you can extend Activity just as I had shown you in the first post on List Views.
  • Set up the ArrayAdapter and assign it to the ListView.
  • Just after that, add the following code:
    lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
    String item = ((TextView)view).getText().toString();
    Toast.makeText(getApplicationContext(), "Clicked: "+item, Toast.LENGTH_LONG).show();
    }
    });
    
  • Save your work and execute it on an emulator or a device.

Click1    Click2

Understanding the Code

  • A careful examination of code shows that it itself is comprehensive enough.
  • AdapterView<?> parent is the parent Adapter view i.e. it refers to the complete section where the Adapter is used.
  • View view is the specific view which we are clicking at the moment, in this case the element we are clicking.
  • int position gives the position of the view under consideration, in this case the element clicked.
  • long id gives the id of the clicked element.
  • Here, I’ve shown you a very basic example of how to handle clicks by using Toast. You can create dialogs, alert boxes or switch to entire new activities if you want to. Refer to my previous posts and apply the concept discussed here.

COMPLETE SOURCE CODE

activity_main.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" >

    <ListView
        android:id="@+id/android:list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

MainActivity.java

package com.nero.myfirstapp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String values[]=new String[]{"Vergil", "Dante", "Sparda", "Nero", "Arkham", "Agni", "Rudra", "Beowulf", "Nevan"};
        ListView lv = getListView();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1,values);
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        		String item = ((TextView)view).getText().toString();
        		Toast.makeText(getApplicationContext(), "Clicked: "+item, Toast.LENGTH_LONG).show();
        	}
          });
    }
}
Series Navigation<< List View using Array Adapters – Part III : Using Custom Row LayoutsAdding Long Click functionality in List View – Context Menus >>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy This Password *

* Type Or Paste Password Here *

43,702 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>