Can somebody in plain words explain me the usage of getViewTypeCount()
and getItemViewType()
methods of ArrayAdapter
?
Watch Outttt!!!!
I had to face for a problem implementing a ListView
yesterday and it's two types of views for rows got jumbled just after I scroll it. Even though the top voted answer within this thread gives a good general explanation it hasn't highlighted the most important bit of information to stop the above UI bug which I have mentioned.
Here is my explanation:
Both getViewTypeCount()
and getItemViewType()
are being used by BaseAdapter
's getView
method to find out which type of a view should it be fetch, recycled and returned. (as explained in the top answer within the thread). But if you don't implement these two methods intuitively according to the Android API Doc, then you might get into the problem I mentioned about.
Summarized Guideline for the implementation:
To implement multiple types of Views
for ListView
's rows we have to essentially implement, getItemViewType()
and getViewTypeCount()
methods. And getItemViewType()
documentation gives us a Note as follows:
Note: Integers must be in the range
0
togetViewTypeCount() - 1
.IGNORE_ITEM_VIEW_TYPE
can also be returned.
So in your getItemViewType()
you should return values for the View Type, starting from 0, to the last type as (number of types - 1). For example, let's say you only have three types of views? So depending on the data object for the view, you could only return 0 or 1 or 2 from the getItemViewType()
method, like a zero-based array index. And as you have three types of views used,
your getViewTypeCount()
method must return 3.
In any case if you return any other integer values like 1, 2, 3 or 111, 222, 333 for this method you definitely might experience the above UI bug which you just placed by not obeying to the Android API Doc.
If you didn't get the clue or couldn't still resolve and need further information please read my detailed answer within this StackOverflow Q&A thread.
Read the Android Developer Doc for further information you might be find the clue directly.
Hope this answer might be helpful to someone out there to save a lots of hours!!!
Cheers!!!