Android Basics – Adding a ViewHolder to the RecyclerViewAdapter

When you create a RecyclerView Adapter then you need to create a view holder by extending the RecyclerView.ViewHolder class.

Like the name suggests a ViewHolder is used to hold and display the View. Recycler view maintains a set of these views.

The number of these holders depends on the size of the view.

When the Recycler view is first constructed it builds this set by calling the onCreateViewHolder() method.

public static class ViewHolder extends RecyclerView.ViewHolder{
    CardView mCardView;
    public ViewHolder(View itemView) {
        super(itemView);
        mCardView = (CardView) itemView;
    }
}

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

    CardView cardView = (CardView) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.card_view_sample,parent,false);

    return new ViewHolder(cardView);
}

Source Code is available here