Using Array Adapter

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 shown above)

• 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 View getView(int position, View

convertView,

ViewGroup parent)

{

if (convertView==null) {

convertView=new TextView(this);

}

convertView.setText(buildStringFor(position));

return(convertView);

}

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 example shown above, the adapter still returns a Textview, but uses a different behavior for determining the string that goes in the view. The TourIt sample application demonstrates using a more complicated custom view for a list adapter.

Self Publishing

Self Publishing

Have you always wanted to write your own book and get it published? Discover How to Write, Print Sell Your Own Book! Have you always wanted to write your own book and get it published? If you have written a book or even if you have a yen to be a writer, you are probably already aware of the competition in the writing field.

Get My Free Ebook


Post a comment