RecyclerView library dynamically creates the elements, and recycles those individual elements. When an item scrolls off the screen, RecyclerView doesn't destroy its view. Instead, RecyclerView reuses the view for new items that have scrolled onscreen.
Key classes
RecyclerViewis theViewGroupthat contains the views corresponding to your data.- Each individual element in the list is defined by a view holder object. You define the view holder by extending
RecyclerView.ViewHolder. - The
RecyclerViewrequests those views, and binds the views to their data, by calling methods in the adapter. You define the adapter by extendingRecyclerView.Adapter. - Layout managers are all based on the library's
LayoutManagerabstract class.
Steps for implementing your RecyclerView
- Decide what the list or grid is going to look like.
- Design how each element in the list is going to look and behave. Based on this design, extend the
ViewHolderclass. - Define the Adapter that associates your data with the ViewHolder views.
Plan your layout The RecyclerView library provides three layout managers:
LinearLayoutManagerarranges the items in a one-dimensional list.GridLayoutManagerarranges all items in a two-dimensional grid, vertically and horizontally.StaggeredGridLayoutManagerarranges all items in a row or column can end up offset from each other.
Implementing your adapter and view holder
Adapter and ViewHolder work together to define how your data is displayed.
When you define your adapter, you need to override three key methods:
onCreateViewHolder():RecyclerViewcalls this method whenever it needs to create a newViewHolder.onBindViewHolder():RecyclerViewcalls this method to associate aViewHolderwith data.getItemCount():RecyclerViewcalls this method to get the size of the data set.