Wednesday, September 18, 2013

Android: List/GridView Adapter with different row layouts

Creating  and displaying lists on Android is quite simple: just display a ListView and set some Adapter and everything works. There are already some predefined Adapter classes you can use, but there's also the possibility to create your own adapter if the layout is a bit more comlpex than just text.
Such custom Adapter classes are usually implemented by inheriting from ArrayAdapter<?> or CursorAdapter, depending on your datasource. Usually this only requires you to override the method getView and newView and bindView, respectively.
I recently had a case where the data I had to display had different types, which also required different ways of representing. This is what I want to focus on in this blog post.

CursorAdapter with multiple item types

Let's assume we already have subclass of CursorAdapter. The only thing we have to do is to override the methods getViewTypeCount and getItemViewType to reflect the number of different views used and return the type number for the views, respectively.
The getViewTypeCount will return the number of different view types and
getItemViewType the correct type number for each position, which of course has to be smaller than the count ;).

In the newView method you can now just inflate a different view based on this type and in bindView set the correct view properties (text, images, ...). Of course, using the ViewHolder pattern is never wrong with this approach either!

(Half-)Full Example 

public class MyCustomAdapter extends CursorAdapter {
    @Override
    public int getViewTypeCount() {
        return NR_VIEW_TYPES;
    }

    @Override
    public int getItemViewType(int _position) {
        Cursor cursor = (Cursor) getItem(_position);
        return getItemViewType(cursor);
    }

    private int getItemViewType(Cursor _cursor) {
        itn typeIdx = _
cursor.getColumnIndex(COLUMN_NAME_TYPE);
        int type =
_cursor.getInt(typeIdx);
        return
type == 0 ? 0 : 1;
    }

    // Don't forget about newView and bindView
    // [...]

}

I'd like to credit this answer (and of couree question) on StackOverflow for pointing me in the right direction when I was also reseaching this topic.

Labels: , , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home