Saturday, 4 August 2012

Android - A list view with different views for items

A list view is one of the most useful views to represent a set of common items. Sometimes, there could be different items to be shown in the same list. For example, for an Agenda, there could be a lot of names. It is a good idea to have a separator for each one of the character of the alphabet.

For this purpose, the following action should be done:
1. Override the method getViewTypeCount() - This method returns the number of the different view layouts.
2. Override the method getItemViewType(int position) - This method return the view type depending on the position.
3. Creates the correct View which is returned by the method getView.

For the last step, the method setTag(Object tag) is utilized to optimise the view update. Here is a good explanation:

"In the case of lists and the view holder pattern it's a simple object which contains references to views of the tagged view (group). So you don't have to call findViewById every time when you're updating the content of the view. It's just an performance optimisation." - Knickedi - StackOverFlow.

The complete source code could be found in my GitHub account:

Android tales - HowTo: ListView, Adapter, getView and different list item's layouts in one ListView