Android Foundation Project for Beginners — RecyclerView & Adapter

What is RecyclerView and Adapter

In overview, RecyclerView is a container. LayoutManager decides how RecyclerView look like. Adapter is a bridge between RecyclerView and Data.

In earlier time, Android developers used ListView or GridView to implement a series data. But now we have RecyclerView to build it. Not only simpler, but also elegant. On one hand, we could choice LinearLayoutManager to create vertical or horizontal list. On the other hand, GridLayoutManager is able to create grid. Moreover, StaggeredGridLayoutManager let developers create random grid much easier.

GitHubUserAdapter

Four types of LayoutManager

First, we build the adapter to connect data and RecyclerView. I prefer to send context and data into the constructor, due to the fact that if we want to change the color or get string etc. But it is all right if send only data into it.

Let’s focus on some override functions and an inner class ViewHolder.
1. onCreateViewHolder 
2. onBindViewHolder
3. getItemCount
Those three functions are the most important things for RecyclerView Adapter.

Simply speaking, 
1. onCreateViewHolder decides the outline of every item in RecyclerView.
2. onBindViewHolder helps parse data and set them into every view. We also load image in this function via Picasso(Loading image library, a single line to load image from URL or local file.)
3. getItemCount tells how many item in the RecyclerView.

Finally, the inner class ViewHolder.
It is all right if make this class out of Adapter if this ViewHolder is reusable,
which means we could only create a ViewHolder if App has the same user interface for RecyclerView.

RecyclerViewActivity

We generate a random integer from MainActivity to fetch GitHub users data. Before we put data into Adapter, Android has to know which LayoutManager should we use for the RecyclerView. So we could use the utility that we have created last time(SetUpLayoutManager). After that, let’s put data into adapter and set adapter for the RecyclerView.

Click event for RecyclerView

RecyclerView doesn’t has default click event like ListView or GirdView, this may be a disadvantage of it. But the fact is that click event is easy to implement. Check the utility we have created last time(OnItemClickListener).

We declare OnItemClickListener in Adapter and do a simple Observe Pattern, which is also may be the highest usage rate pattern in Android.