Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using ListView with ListActivity

Published? true
FormatLanguage: WikiFormat


You want to use a ListView in a ListActivity.


While the previous recipe 397 gave details on ListView in a plain Activity, the official documentation at Android.com generally recommends using a ListActivity. This recipe shows some specifics of the ListActivity.


Many ListView activities are organized by inheriting from ListActivity, which is the recommended way to write such things.

public class Main extends ListActivity {

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

Set the activity's contentView in the usual way. There is one requirement on your XML layout: the ListView must have the pre-defined name that the ListActivity expects, which is represented in your Layout by @android:id/list:


As with any ListView, you need to provide an Adapter. The inherited setListAdapter() method makes this easy:

        ArrayAdapter<String> adapter = ...

Although it's not strictly necessary, you will usually want to refer to the ListView object, for example, to add a Listener to it. The inherited getListView() method should be used in preference to findViewById():

        final ListView myList = getListView();
        myList.setOnItemClickListener(new OnItemClickListener() {
                // handle the click...

Once you have a reference to the ListView you can tailor it in all the ways suggested in the previous recipe 397.


The source code for this project is in the Android Cookbook repository, http://github.com/IanDarwin/Android-Cookbook-Examples/,in the subdirectory ListViewDemos.