Sunday, March 6, 2011

ListView, ListAdapter, ListActivity in Android

ListView is derived from View class, so it can be used by Activity in the similar way as EditText or Button View. ListView is also derived from ViewGroup, so it has the ability to contain a list of view for the list item.
In order to show the list view, the only method that needs to be called is
setAdapter( ListAdapter adapter). The ListAdatper parameter provides the views for showing each list item.

ListAdapter class mentoned in setAdapter method is responsible to render list item. Its first responsibility is holding the data of list item, which is passed as paramter to its constructor. The second responsibility is returning a view for each item when asked by ListView classm, the layout resource of the item view is passed to it as another paramter in its constructor.

Now let us take a look at ListActivity, basically, it is a activity that has a listView in it. In order to show a list items, the only method needs to be called is setListAdapter(adapter) in the overrided onCreate method. The following is the simple code to show a string array in listActivity, it does not even require to define any layout resources.

public class MyListActivity extends ListActivity {
@Override
public void onCreate(Bundle data) {
super.onCreate(data);
ArrayList myString = new ArrayList();
myString.add("string1");
myString.add("string2");
myString.add("string3");
myString.add("string4");
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, myString);
setListAdapter(adapter);
}
}

Jonathan

No comments:

Post a Comment