Brief Introduction to RecyclerView in Android Development.
Hello Everyone..
The concept of RecyclerView has been a huge struggle for me, to be honest. I promised myself that once I understand it, I will write an article to help others. This is the article.
What is RecyclerView?
Like ListViews, RecyclerView is what android developers use to create lists in Android development. Unlike ListViews, RecyclerView recycles via ViewHolders thereby ensuring that views that are not in use at a particular time are recycled, instead of generating new views for each new set of data that is to be displayed.
Major Features of a RecyclerView
- RecyclerView Layout and Item Layout
When creating a layout for RecyclerView, you are also expected to create another layout for the individual items that will be on the list. This second layout is connected to the first layout using the ‘listitem’ property.
2. LayoutManager
As the name suggests, this manages the way the items are displayed. This is one of the major differences between a ListView and a RecyclerView because in a ListView, the only type of view available is the vertical ListView, while a RecyclerView has many options, namely:
- LinearLayoutManager: This supports both vertical and horizontal lists
- GridLayoutManager: This displays the lists in the form of grids as seen in most android applications especially gallery apps.
- StaggeredLayoutManager: This lays out children in a staggered grid formation like the Pinterest application. It supports both vertical and horizontal layouts. Most people will be wondering what the difference is between Staggered and Grid. Well, Grid layout ensures that all the child views in it have the same height and views while the reverse is the case for Staggered.
3. Recycler Adapter.
The Recycler Adapter carries out two functions for the RecyclerView namely:
- Generate the view instances.
- Populate the needed data into the views.
It generates the view instances uses the concept of ViewHolder. In the onCreateViewHolder(Viewgroup parent, int position) method of the RecyclerAdapter class, the layout for the individual items is inflated using the LayoutInflater class. After this view is created, it is then attached to the view holder which holds a reference to each views.
The onBindViewHolder(ViewHolder holder, int position) method attaches the data that is to be displayed to each view in a view holder using the position of the data at a given point in time.
The getItemCount() method is used to get the size of the data being populated by the Recycler Adapter.
These three methods need to be overriden and implemented in order to make use of the RecyclerAdapter.
In order to learn more about the RecyclerView, kindly go through the docs: https://developer.android.com/reference/android/support/v7/widget/RecyclerView
In the coming days, I will work you through on how to implement a basic RecyclerView given a set of data.
Happy Coding!