Android – Creating Simple ListView

android-listview-listactivityTo display a list of items create an activity extending ListActivity which has a built-in ListView and bind a data source such as an array to the ListView using an Adapter. ListActivity has a default layout that consists of a single, full-screen list in the center of the screen.

 

 

 

Objectives:

  • How to create simple ListView using standard row layout resources provided by Android?
  • How to bind the ListActivity’s ListView object to data “String[]” using ArrayAdapter?

Environment & Tools:

  • Android Developer Tools (ADT) (or Eclipse + ADT plugin)
  • AVD Nexus S Android 4.3 “emulator” or,
  • Min SDK 8

( 1 ) Create Android Application

  • File >> New >> Android Application
  • Enter App name: android-simple-listview
  • Pakcage: com.hmkcode.android
  • Keep other defualt selections, go Next  till you reach Finish

( 2 ) Extend ListActivity

  • The only file we will work with is MainActivity.java “the generated blank activity”
  • src/com/hmkcode/android/MainActivity.java
  1. Define array of String “listItemArray” to hold label of each list item
  2. Create ArrayAdapter to bind data “String array” to the view “android.R.layout.simple_list_item_1
  3. Call setListAdapter(ArrayAdapter) pass the created adapter.
package com.hmkcode.android;

import android.os.Bundle;
import android.app.ListActivity;

import android.widget.ArrayAdapter;

public class MainActivity extends ListActivity {

	// 1. define list of item 
	String listItemArray[] = {"A","B","C"};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// 2. create array adapter
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, 
        android.R.layout.simple_list_item_1, // standard row layout provided by android
        listItemArray);

                // 3. Call setListAdapter
		setListAdapter(adapter);

	}
}

android-listview-listactivity