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 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 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 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.

Other Key Adapters

Here are some other adapters in Android that you will likely use:

• CursorAdapter converts a Cursor, typically from a content provider, into something that can be displayed in a selection view

• SimpleAdapter converts data found in XML resources

• ActivityAdapter and ActivityIconAdapter provide you with the names or icons of activities that can be invoked upon a particular intent

0 0

Post a comment