artem
artem

Reputation: 16777

RecyclerView and custom item types

I have a RecyclerView, filled with items from collection with fixed size.

I want to add views with ads, for example, for every 3th item:

@Override
public int getItemViewType(int position) {
     return position % 3 == 0 ? TYPE_ADS : TYPE_ITEM;
}



@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;

        switch (viewType) {
            case ItemTypes.TYPE_ITEM:
                view = layoutInflater.inflate(R.layout.view_news_entries_item, parent, false);
                break;

            case ItemTypes.TYPE_ADS:
                view = layoutInflater.inflate(R.layout.view_ads_item, parent, false);
                break;

            default:
                throw new IllegalArgumentException("Invalid item type: " + viewType);
        }

        return new ViewHolder(view);
    }

But using such method, how should I implement the getItemCount() and onBindViewHolder()? I mean that item count will be different then count of real items in collection, and positions will not be the same, so how to calculate them?

Upvotes: 2

Views: 454

Answers (1)

Nate
Nate

Reputation: 106

For the OnBindViewHolder:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    if (holder.getItemViewType() == TYPE_ADS) {
        // DO AD THINGS
    } else {
        // DO NORMAL ITEM THINGS
    }
}

I believe that the getItemCount() is used to keep count of actual views inside of the RecyclerView (so all items that are displayed including ads.) You may want to write a new method get the the count of items that are not ads:

public int getRealItemCount() {
    int ads = getItemCount() / 3;
    return getItemCount() - ads;
}

Upvotes: 3

Related Questions