Create List Using ListView – Android

Home / Android / Create List Using ListView – Android

Talking about the scenario where there is a need to display a list. This may be the list of options from which a user has to choose, or like a list of contact numbers. The list could be for displaying purpose or for choosing options from it.

There are two ways to create list:

  1. Using ListView
  2. Using ListActivity

In this demo application, a list would be created using ListView. In this application following points are being covered.

  • Add ListView in XML
  • Add elements in the ListView (list is ready for display)
  • Handle click event on the list items




activity_main.xml

A ListView is added to the XML with three parameters, viz. id, layout_width, and layout_height.



    


MainActivity.java

In MainActivity.java, a String array is used to store the list items. In order to populate the ListView, lvName, with list items; it needs to be referenced with the ListView of activity_main.xml. Then, an ArrayAdapter of String type is set to the lvName. The ArrayAdapter<String> requires three types of arguments, viz. Context, int, String[]. For Context type argument MainActivity.this is passed. The integer type parameter is for the layout of list items. And, the String array is for the list of items which would be populated inside the ListView lvName.

The setOnItemClickListener() adds the the listener to the list items of the ListView. And, the function of this listener is to handle the click event on the list items. The listener takes one argument of type OnItemClickListener defined inside "android.widget.AdapterView". The OnItemClickListener interface has a method onItemClick, which must be overriden. And, the functionality for performing actions when an item is clicked, should be added here.

package com.pcsalt.listviewdemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	ListView lvName;
	String name[] = {"Android","iOS","BlackBerry","Windows Phone","Symbian","Bada"};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		lvName = (ListView) findViewById(R.id.lv_Name);
		lvName.setAdapter(new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1 , name));
		lvName.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView arg0, View arg1, int arg2,
					long arg3) {
				Toast.makeText(getBaseContext(), name[arg2], Toast.LENGTH_SHORT).show();
			}
		});
	}
}

Screenshots
ListViewDemo1ListViewDemo2

Download source: