2

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 HEADER = Integer.MIN_VALUE;
public static final int FOOTER = Integer.MIN_VALUE + 1;
public static final int ADAPTER_OFFSET = 2;

@Override
    public int getItemViewType(int position) {
        if (position == 0 && useHeader()) {
            return HEADER;
        }

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

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

        if (basicItemType >= Integer.MAX_VALUE - ADAPTER_OFFSET) {
            new IllegalStateException(
                    "");
        }

        return basicItemType + ADAPTER_OFFSET;
    }

@Override
    public int getBasicItemType(int position) {
        return position;
    }
Android Killer
  • 18,174
  • 13
  • 67
  • 90

1 Answers1

4

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

Blackbelt
  • 156,034
  • 29
  • 297
  • 305