Android ListActivity onListItemClick Example

0

In this example, we will see how to perform an action when an item in the list is selected. We will be improving our example on Customized List View.

Our custom list contains couple of cartoon characters. Each item will display a cartoon character and some details about the character. On selecting the item, we need to show the illustrator’s picture and name in a dialog box.

Steps to set up the ListView item listener

    1. Create your own custom ListView. Your activity should extend ListActivity.
    2. Override onListItemClick.
    3. In onListItemClick implementation, create a dialog box, set its content view and then show the dialog.
    4. The dialog box should contain the illustrator’s name and picture.

ListView Layout

If you are new to creating list view, read my article on building customized ListView.
Below XML is the layout of ListView.

cartoon_list_view.xml:

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

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

ListView Item Layout

List Item will show the cartoon character, some description about the character and the character’s name. Below XML describes its layout.

cartoon_list_item_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/cartoon_pic"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_marginRight="6dip" 
            android:layout_weight="0"/>

        <TextView
            android:id="@+id/about_cartoon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:layout_weight="1"/>

    </LinearLayout>

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

</LinearLayout>

Here is our ListActivity class. In our activity class, we set the content view to ListView’s layout and then attach the model.

CartoonListActivity:

package com.javarticles.android;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class CartoonListActivity extends ListActivity {
	private CartoonListAdapter cartoonListAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cartoon_list_view);
		List cartoonList = new ArrayList();
		cartoonList
				.add(new Cartoon(
						"Tintin",
						R.drawable.tintin_thumb,
						"Tintin is a fictional character in The Adventures of Tintin, the comics series by Belgian cartoonist Hergé.",
						"Herge", R.drawable.herge));
		cartoonList
				.add(new Cartoon(
						"Asterix",
						R.drawable.asterix_thumb,
						"Asterix is a fictional character, the titular hero of the French comic book series The Adventures of Asterix. The series portrays him as a diminutive but fearless Gaulish warrior living in the time of Julius Caesar's Gallic Wars",
						"Abbert Underzo", R.drawable.albbert_uderzo));
		cartoonListAdapter = new CartoonListAdapter(this,
				R.layout.cartoon_list_item_view, cartoonList);
		setListAdapter(cartoonListAdapter);
	}
}

Our Model contains simple beans of Cartoon class.

CartoonListAdapter:

package com.javarticles.android;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CartoonListAdapter extends ArrayAdapter{
	private List cartoonItems;
	private Context context;

	
	public CartoonListAdapter(Context context, int textViewResourceId, List cartoonItems) {
		super(context, textViewResourceId, cartoonItems);
		this.context = context;
		this.cartoonItems = cartoonItems;
	}
    
	@Override
    public View getView(int position, View convertView, ViewGroup parent) {
  
        View view = convertView;
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.cartoon_list_item_view, null);
        }
        
        Cartoon cartoon = cartoonItems.get(position);
        
        if (cartoon != null) {            
            // name
            TextView nameTextView = (TextView) view.findViewById(R.id.name);
            nameTextView.setText(cartoon.getName());                       
            
            // thumb image
            ImageView imageView = (ImageView) view.findViewById(R.id.cartoon_pic);
            imageView.setImageResource(cartoon.getCartoonPicRes());  
            
            TextView aboutTextView = (TextView) view.findViewById(R.id.about_cartoon);
            aboutTextView.setText(cartoon.getAbout());    
        }
        
        return view;        
    }
}

When we run the application, the list would look like below:

Cartoon List

Cartoon List

Dialog Box Content

Now comes the part, we are most interested in, that is, to display the illustrator details on selecting the item.
Our dialog will contain a text field and a ‘close’ dialog button. We will set the illustrator’s name and picture dynamically in the onListItemClick() as soon as the list item is selected.
author_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/author_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/illustrator"/>

    <Button
        android:id="@+id/close_author_dialog_button"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/close" />

</LinearLayout>

Implement onListItemClick

In onListItemClick, based on the list item selected, we will first get the Cartoon bean the row represents. Next step would be to create a customized dialog. We will create a Dialog Object and set its title. The title would be manufactured based on the cartoon character’s name.

Once we create the dialog object, we need to set its content view to author_dialog layout.

Next step would be to populate the dialog fields. We need to find the illustrator’s text widget from the dialog’s view and set the illustrator’s name. We also need to set the picture of the illustrator on the same text field, using textView.setCompoundDrawablesWithIntrinsicBounds.

The dialog box has a ‘Close’ button to close the dialog. We will set a listener to the ‘Close’ button to close the dialog using dialog.dismiss(). The final step would be to show the dialog using dialog.show().

CartoonListActivity:

package com.javarticles.android;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class CartoonListActivity extends ListActivity {
	private CartoonListAdapter cartoonListAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cartoon_list_view);
		List cartoonList = new ArrayList();
		cartoonList
				.add(new Cartoon(
						"Tintin",
						R.drawable.tintin_thumb,
						"Tintin is a fictional character in The Adventures of Tintin, the comics series by Belgian cartoonist Hergé.",
						"Herge", R.drawable.herge));
		cartoonList
				.add(new Cartoon(
						"Asterix",
						R.drawable.asterix_thumb,
						"Asterix is a fictional character, the titular hero of the French comic book series The Adventures of Asterix. The series portrays him as a diminutive but fearless Gaulish warrior living in the time of Julius Caesar's Gallic Wars",
						"Abbert Underzo", R.drawable.albbert_uderzo));
		cartoonListAdapter = new CartoonListAdapter(this,
				R.layout.cartoon_list_item_view, cartoonList);
		setListAdapter(cartoonListAdapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Cartoon cartoon = cartoonListAdapter.getItem((int) position);
		displayIllustratorInDialog(cartoon);
	}

	private void displayIllustratorInDialog(Cartoon cartoon) {
		final Dialog dialog = new Dialog(this);
		dialog.setTitle(cartoon.getName() + "'s "
				+ getString(R.string.illustrator));
		dialog.setContentView(R.layout.author_dialog);
		TextView author = (TextView) dialog.findViewById(R.id.author_name);
		author.setCompoundDrawablesWithIntrinsicBounds(0,
				cartoon.getAuthorPicRes(), 0, 0);
		author.setText(cartoon.getAuthorName());
		final Button closeButton = (Button) dialog
				.findViewById(R.id.close_author_dialog_button);

		closeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();
	}

}

Run the application and select the list Item

On selecting the list item, illustrator’s details would show up in the dialog popup.

List Item Dialog

List Item Dialog

Download Source Code

In this article, I have shown you an example of ListActivity’s onListItemClick. You can download the source code here: customListListener.zip

Share.

Comments are closed.