Home Contact Me Tutorials

A Simple Android ListView Example



This tutorial describes how to create a simple ListView and populate it with text data (the names of various planets). The following picture shows what the Android program looks like.

Basically we create a ListView class and use TextView objects for each row. Each planet name is rendered in a TextView.

Main Layout File

Our ListView is defined in the main layout file (res/layout/main.xml) within a LinearLayout.

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

The resource ID of the ListView is mainListView, which we will use to get a reference to the ListView in our Activity class.

// Find the ListView resource.   
mainListView = (ListView) findViewById( R.id.mainListView );  

Row Layout File

Each row in the ListView will be a TextView. The TextView is defined in another file (res/layout/simplerow.xml).

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:textSize="16sp" >


Our main activity (SimpleListViewActivity) creates an ArrayAdapter, which holds the objects to be displayed in the ListView. The ArrayAdapter constructor is passed the resource ID of the TextView layout file (R.layout.simplerow). The ArrayAdapter will use it to instantiate a TextView for each row.

We then set the ArrayAdapter as our ListView's adapter.

package com.windrealm.android;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SimpleListViewActivity extends Activity {
  private ListView mainListView ;
  private ArrayAdapter<String> listAdapter ;
  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    // Find the ListView resource. 
    mainListView = (ListView) findViewById( R.id.mainListView );

    // Create and populate a List of planet names.
    String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
                                      "Jupiter", "Saturn", "Uranus", "Neptune"};  
    ArrayList<String> planetList = new ArrayList<String>();
    planetList.addAll( Arrays.asList(planets) );
    // Create ArrayAdapter using the planet list.
    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList);
    // Add more planets. If you passed a String[] instead of a List<String> 
    // into the ArrayAdapter constructor, you must not add more items. 
    // Otherwise an exception will occur.
    listAdapter.add( "Ceres" );
    listAdapter.add( "Pluto" );
    listAdapter.add( "Haumea" );
    listAdapter.add( "Makemake" );
    listAdapter.add( "Eris" );
    // Set the ArrayAdapter as the ListView's adapter.
    mainListView.setAdapter( listAdapter );      


The source code and Eclipse project files for this tutorial can be downloaded here.