Hi 🙂 !

Well, this blog is just going to be a regular blog just like every other one. It might just be simplified to some extent.

There are times we would wish to display different kinds of data periodically (or rather at frequent intervals), like for example:
– You may wish to display three rows of data and then an ad
– Or, you may wish to display data as even and odd rows having different colors
– Or may be even one audio file and then another row representing a video file and so on

That is why we use the getItemViewType() method and getViewTypeCount() method. These methods are part of the adapter class that we extend, and even if not implemented in your custom adapter, Android automatically makes a call to them.

How then does the adapter work, and when do these methods come into play?

I will try my best to explain the flow in simple words, though, if in case i miss out on any point, please feel free to comment so that i could add the point here. 🙂

A little description about these methods just before we jump into the sequence.

getItemViewType() returns the type of the view that needs to be displayed and it would be determined by getViewTypeCount() which returns the number of views to display. By default it has a value of 1, since we inflate the same rows.

The whole process:

  1. We first bind our data to the AdapterView using an Adapter
  2. We override the getViewTypeCount() and getItemViewType() methods
  3. getViewTypeCount() should return the size of items in the adapter based on the views you wish to implement, like: if you wish to implement even and odd views, you would return the size = adapter’s item size, if you wish to implement just the load more or a different header then the method should return adapter’s item count + 1
  4. getItemViewType() will return the view that has to be loaded based on the position, so you can modify this to define the views you should return. For example: In the case of odd and even views, you can define a method that determines if the position is odd or even and return that view type. By default 0 is returned, so you might as well start numbering the view types from 0.
  5. In the onCreateViewHolder(), we determine the viewType returned by getItemViewType() and we create the viewHolder instance
  6. Lastly, in the onBindViewHolder we determine the viewType returned by getItemViewType() and bind the view with data using the viewHolder instances

Some good references that you might want to look at:

1. GetViewTypeCount, GetItemViewType methods of array adapter

2.ListView getViewType and getViewTypeCount in action

Advertisements