: Beginning Android

Using ArrayAdapter

Using ArrayAdapter

The easiest adapter to use is ArrayAdapter all you need to do is wrap one of these around a Java array or java.util.List instance, and you have a fully-functioning adapter:

String[] items={this, is, a,
really, silly, list};
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);

The ArrayAdapter constructor takes three parameters:

The Context to use (typically this will be your activity instance)

The resource ID of a view to use (such as a built-in system resource ID, as previously shown)

The actual array or list of items to show

By default, the ArrayAdapter will invoke toString() on the objects in the list and wrap each of those strings in the view designated by the supplied resource. android.R.layout.simple_list_item_1 simply turns those strings into TextView objects. Those TextView widgets, in turn, will be shown the list or spinner or whatever widget uses this ArrayAdapter.

You can subclass ArrayAdapter and override getView() to roll your own views:

public ViewgetView(int position, View convertView,
ViewGroup parent) {
if (convertView==null) {
convertView =newTextView(this);

Here, getView() receives three parameters:

The index of the item in the array to show in the view

An existing view to update with the data for this position (if one already existed, such as from scrolling if null, you need to instantiate your own)

The widget that will contain this view, if needed for instantiating the view

In the previous example, the adapter still returns a TextView, but uses a different behavior for determining the string that goes in the view. Chapter 9 will cover fancier ListViews.

: 1.072. /Cache: 3 / 1