Android Killer Android Killer - 3 months ago 24x
Android Question

Viewholder of recyclerview getting called for each item

I have Recyclerview in my project which is having one ViewHolder. For this RecyclerView, i have many items to populate, but for the simplicity sake, i have added 100 items. But for these 100 items onCreateViewHolder is being called 100 items i.e. for each item it is being called, hence for each item view is getting infalted. If i will use all items(may be 1000 or 2000), i am getting OOM. SO how can i avoid this call of onCreateViewHolder for each item. Really need help!!

public static final int TYPE_HEADER = Integer.MIN_VALUE;
public static final int TYPE_FOOTER = Integer.MIN_VALUE + 1;
public static final int TYPE_ADAPTEE_OFFSET = 2;

public int getItemViewType(int position) {
if (position == 0 && useHeader()) {

if (useHeader() && position > getBasicItemCount() && useFooter())
else if (!useHeader() && position >= getBasicItemCount() && useFooter())

int basicItemType = getBasicItemType(position - (useHeader() ? 1 : 0));

//This is not needed, the above condition satisfies that. If we will use this then when we will use both header and footer, then there will be problem of holder cast
/*if (position >= getBasicItemCount() && useFooter()) {

if (basicItemType >= Integer.MAX_VALUE - TYPE_ADAPTEE_OFFSET) {
new IllegalStateException(
"HeaderRecyclerViewAdapter offsets your BasicItemType by " + TYPE_ADAPTEE_OFFSET + ".");

return basicItemType + TYPE_ADAPTEE_OFFSET;

public int getBasicItemType(int position) {
return position;


getItemViewType changes the number of times onCreateViewHolder is called. The documentation states that it

Return the view type of the item at position for the purposes of view recycling.

it means that every time getItemViewType return a different value, Android thinks that you are dealing with a new different type, and you want a different view for it. Your implementation, is returning position. It means getItemCountdifferent views