Commonsware's answer on your previous question explained very well why do you need to care about those methods. Here is a small example:
You have a ListView
with 100 rows and 3 types of rows:
- a simple
TextView
- a custom view (very complex)
- an
AnalogClock
view
You ListView
starts like this:
- position 0: TextView <= first visible position
- position 1: custom view
- position 2: custom view
- position 3: TextView
- position 4: AnalogClock <= last visible position
- position 5: custom view <= first invisible position(here android will provide a recycled view)
- position 6: TextView
If you don't implement those methods then android will simply recycle the views not taking in consideration the type of rows. So in the example above, when the user scrolls the ListView
down the getView
method will be called for row 5
with a recycled view(the row 0 that isn't visible anymore), a TextView
(convertView
will not be null
for this position). As you see this isn't the view you would expect at that position. Because in the getView
method you have something like this:
//...
if (convertView == null) {
// inflate views
} else {
//just use it
//...
you'll end up setting data on a row that should be a custom view
(very complex) but instead get a simple TextView
. This will get worse as you further scroll the ListView
up and down.
If you do implement those methods then android will know that the getView
method will expect 3 types of rows. When row 5(from the previous example) needs to be shown android will call getItemViewType
to see what type of view the getView
method expects for that position(position 5). If a recycled view of that type is found(previously recycled) then the getView
method will be called with convertView
set to that recycled view, if not then the getView
will be called with convertView
set to null
. As you scroll the ListView
to show the position 5 the(only) recycled view will be the simple TextView
. The getView
method expects a custom view
(very complex) and as a recycled view isn't found with that type then the convertView
will be null
and you get the chance to inflate it.
If you scroll the ListView
to show position 6 the view from position 1(that isn't on the screen anymore) will be recycled so the ListView
has now two views of different types(TextView
and a custom view
(very complex)). Then the getItemViewType
will be called again and for this position the getView
method requires a TextView
. A recycled view of this type exists so the getView
method will be called with convertView
set to this recycled TextView
. If you further scroll the ListView
and the getView
requires a TextView
or a custom view
one of those recycled views(with the correct type) will be supplied. Also, eventually a view of type AnalogCLock
will be recycled so the ListView
will have recycled views of each list row type to reuse.