Android – Recyclerview show different view types

androidandroid-recyclerview

I'm using the recycleview to show a list. I was wondering how do we show different types of views? As in, different ViewHolders int the same adapter

In the simple listview we used getItemViewType(), anything different in the recycleview?

Best Solution

To create RecyclerView with multiple view type just implement getItemViewType(), two different ViewHolders and take care of the viewType parameter in onCreateViewHolder() and bindViewHolder().

Short example:

public class MultipleViewTypesAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int VIEW_TYPE_FIRST  = 0;
    private static final int VIEW_TYPE_SECOND = 1;

    class ViewHolderFirst extends RecyclerView.ViewHolder {
        ...
    }

    class ViewHolderSecond extends RecyclerView.ViewHolder {
        ...
    }

    @Override
    int getItemViewType(int position) {
        return position % 2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_FIRST: return new ViewHolderFirst(...);
            case VIEW_TYPE_SECOND: return new ViewHolderSecond(...);
            ...
        }
    }

    @Override
    public void bindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case VIEW_TYPE_FIRST:
                ViewHolderFirst viewHolderFirst = (ViewHolderFirst)holder;
                ...
                break;
            case VIEW_TYPE_SECOND:
                ViewHolderSecond viewHolderSecond = (ViewHolderSecond)holder;
                ...
                break;
            ...
        }
    }
}