The flow of recycler view function call is:
getItemCount() -> getItemViewType() -> onCreateViewHolder() -> onBindViewHolder()
The size of array list is 15 and the number of visible views on screen is 0 to 6. This is the log once the adapter is set.
getItemCount() is called thrice even before a view is created. Why?
Once 7 views are populated the log is:
At a single time only 7 views are visible on screen. So onCreateViewHolder() is called 7 times in total.
After we scroll for one more single view, the log is:
On total onCreateViewHolder() is called 9-10 times. onBindViewHolder(): 10 times, getItemCount(): 56 times, getItemViewType(): 54 times.
Lets say we created 10 views and keep recycling them. Shouldn't onBindViewHolder() is also called atleast 15 times(size of list) since it is setting the data for each row?
And also why getItemCount() and getItemViewType() is called 54, 56 times for the size of 15 items?
CodePudding user response:
getItemCount
should be a trivial method that gets a list size. We don't need to worry about why it's called multiple times. For example, as the adapter is laying things out, maybe it uses a for loop to check something on all of them (one call), and it might elsewhere cache it to a local variable (second call), and maybe does a second pass loop (third call). You can find out for yourself by setting a breakpoint on this function and debugging so you can check the stack trace for each call.
Likewise for getItemViewType
, it could be doing multiple for-loop passes through the data and so it calls it multiple times for each view.
Since onBindViewHolder()
is a heavy method, they would have been careful to call it a minimal amount of times--only once for each time a view reappears on screen.