The design of the ListActivity in Android follows the MVC design pattern.
The main parts of a ListActiviy and their relationship is as shown in the following picture:
Now, we will apply a simplest ListActivity, the class diagram is as the following picture:
Since the ListActiviy follows the MVC design pattern. And the ListActivity object has a ListView to display data, and a ListAdapter to provide data to the ListView. So, what we need is the data. In the following example, I will define the data in a XML file.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="keypoints">
<item>Activity</item>
<item>Service</item>
<item>BroadcastReceiver</item>
<item>ContentProvider</item>
<item>Intent</item>
</string-array>
</resources>
Now, we have had the data to display, what should we do in next step is to define our own ListActivity. In the ListActivity, we just do two simply things:
1. get data from XML file;
2. set adapter to this ListActivity.
package org.vhow.android;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class AndroidDemoActivity extends ListActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// 1. Get data to be displayed
String[] keypoints = getResources().getStringArray(R.array.keypoints);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, keypoints);
// 2. Set adapter, provides data to the ListView that this ListActiviy contains
setListAdapter(arrayAdapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Object object = getListAdapter().getItem(position);
Toast.makeText(this, object.toString(), Toast.LENGTH_SHORT).show();
}
}
Ok, we have created the simpliest ListActivity. Run this program, it will looks like: