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

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: