Tuesday, August 26, 2014

Adapters

Adapters are bridging classes that bind data to Views.

An Adapter is responsible for creating the child Views used to represent each item within the parent View and providing access to underlying data.

Adapters are responsible both for supplying the data and for creating the Views that represent each item

Native Adapters

ArrayAdapter
  • Uses toString values of each item within an object array to populate a Text View which is specified in a layout
SimpleCursorAdapter
  • Binds specific columns contained within a Cursor to Views specified within a layout.

Custom Views and Adapters 

Views that support Adapter binding must extend the AdapterView abstract class.

Custom Adapter classes can be created to bind to these views.


Customizing Array Adapter

Define custom array adapter

public class MyArrayAdapter extends ArrayAdapter<MyClass> {

  int resource;

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

/*
   position: position of the item to be displayed
   View: view being updated
   ViewGroup: to which the view will be placed 

   return: newly created and populated/updated View
*/
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    // Create and inflate the View to display
    LinearLayout newView;

    if (convertView == null) {
      // Inflate a new view if this is not an update.
      newView = new LinearLayout(getContext());
      String inflater = Context.LAYOUT_INFLATER_SERVICE;
      LayoutInflater li;
      li = (LayoutInflater)getContext().getSystemService(inflater);
      li.inflate(resource, newView, true);
    } else {
      // Otherwise we'll update the existing View
      newView = (LinearLayout)convertView;
    }

    MyClass classInstance = getItem(position);

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

    // TODO Get references to the Views to populate from the layout.
    // TODO Populate the Views with object property values.

    return newView;
  }
}







No comments:

Post a Comment