Android - Adapter

Card Puncher Data Processing

Android - Adapter


An Adapter (widget) object acts as a bridge between:

  • an AdapterView (An AdapterView is a view whose children are determined by an Adapter. See subclasses of AdapterView such as listView, GridView … )
  • and the underlying data for that view.

The Adapter:

  • provides access to the data items.
  • is also responsible for making a View for each item in the data set.

An adapter pulls content from a source such as an array or database query and converts each item result into a view that's placed into the container.

Multiple Views


Every adapter Implements a BaseAdapter

// The static constant can never be greater than the number returned by the function getViewTypeCount
// That's why they start with 0.
private static final int VIEW_TYPE_ONE = 0;
private static final int VIEW_TYPE_TWO = 1;
public int getViewTypeCount() {
      return 2; // for two views

public int getItemViewType(in position) {
    return (position==0) ? VIEW_TYPE_ONE : VIEW_TYPE_TWO;

* Create the view during runTime
public View newView(Context context, Cursor cursor, ViewGroup parent) {
	// Choose the layout type
	int viewType = getItemViewType(cursor.getPosition());
	int layoutId;

	// Inflate the layout
	switch (viewType) {
			layoutId = R.layout.list_item_one;
			layoutId = R.layout.list_item_Two;

        View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
        // See viewHolder section below
        // The XML parse operations is hold in an object to avoid 
        // to do it twice by using the lookup function findViewById
        ViewHolder viewHolder = new ViewHolder(view);
        // We return the view
	return view;


The findViewById method of a view looks up for a child view. It's a costly function therefore it's a good practice to hold the result of this function in a ViewHolder.

A ViewHolder object stores each of the component views inside the tag field of the parent view.


  • Declaration
static class ViewHolder {
  ImageView iconView;
  TextView textView;
  TextView dateView;
  • Instantiation
ViewHolder holder = new ViewHolder();
holder.iconView = (ImageView) parentView.findViewById(;
holder.textView = (TextView) parentView.findViewById(;
holder.dateView = (TextView) parentView.findViewById(;
  • Use
ViewHolder viewHolder = (ViewHolder) view.getTag();


  • ViewHolder pattern documentation.
  • this example adapter of the sunshine app:
    • The inner static viewHolderClass (Declaration)
    • The function newView (Instantiation)
    • The function bindView (Usage)

Discover More
Card Puncher Data Processing
Android - ListView

ListView is a view group that shows items in a vertically scrolling list. The items come from the android/widget/ListAdapterListAdapter associated with this view. The list items are automatically inserted...

Share this page:
Follow us:
Task Runner