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

Using ListView with ListActivity

Author: Ian Darwin
Published? true -- FormatLanguage: W

Problem:

You want to use a ListView in a ListActivity.

Solution:

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.

Discussion:

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. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

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:

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

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

        ArrayAdapter<String> adapter = ...
        setListAdapter(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.

Download:

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