Customizing the Array Adapter

By default the Array Adapter will use the toString value of the object array it is binding to populate the Text View available within the specified layout.

In most cases you will need to customize the layout used to represent each View. To do that, you will need to extend ArrayAdapter with a type-specific variation, overriding the getView method to assign object properties to layout Views as shown in Listing 5-23.

The getView method is used to construct, inflate, and populate the View that will be displayed within the parent Adapter View class (e.g., List View) which is being bound to the underlying array using this Adapter.

The getView method receives parameters that describe the position of the item to be displayed, the View being updated (or null), and the View Group into which this new View will be placed. A call to getItem will return the value stored at the specified index in the underlying array.

Return the new populated View instance as a result from this method.

LISTING 5-23: Customizing the Array Adapter Available for download on public class MyArrayAdapter extends ArrayAdapter<MyClass> { int resource;

public MyArrayAdapter(Context context, int _resource, List<MyClass> items) { super(context, _resource, items); resource = _resource;

@Override public View getView(int position, View convertView, ViewGroup parent) { LinearLayout newView;

MyClass classInstance = getItem(position);

// TODO Retrieve values to display from the // classInstance variable.

// Inflate a new view if this is not an update. if (convertView == null) {

newView = new LinearLayout(getContext());

String inflater = Context.LAYOUT_INFLATER_SERVICE;

LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater); vi.inflate(resource, newView, true); } else {

newView = (LinearLayout)convertView;

// TODO Retrieve the Views to populate

// TODO Populate the Views with object property values.

return newView;

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment