This post is in continuation to ListView CustomAdapter example, as we shall learn
through differences between ListView/RecyclerView.
We could say is an efficient approach of ListView.
Recommended practices of ListView were made manadatory in an
efficient way in RecyclerView. Like, ViewHolder, Adapter.
ListView is part of native api.
RecyclerView is part of support Library
If you were to dynamically Add/Remove an Item in a ListView,
for Animating those changes it could get very complex.
In RecyclerView, Item Animations were added to address that.
In ListView, divider were simple. Adding custom divider is complex.
In RecyclerView, ItemDecoration were added to customise the
divider/seperators between Items.
In ListView, Scrolling is Vertical.
In RecyclerView, you can have Vertical/Horizontal Scrolling effect.
LayoutManager takes care of placing the items in the desired view.
Just like ListView, we additionally had GridView, Spinner.
In RecyclerView, we have LinearLayoutManager, GridLayoutManager,
StaggeredLayoutManager(for items of variying sizes).
Below is the example that we will be working on.
Add RecyclerView Support library in gradle.
layout with recyclerView widget.
For view Item, Define list_item.xml
Define a new Data Model (Data Source). (DataModel.java)
View Holder (as below)
In ListView, getView() function (see the recommended) is made manadatory as
ViewHolder in RecyclerView.
* class DataViewHolder extends RecyclerView.ViewHolder
1. Constructor method.
- findViewById of all the items in list_item.xml
2. method to set values to views
- onBindViewHolder calls this function.
Adapter (as below)
In List View, we extend CustomAdapter from ArrayAdapter or BaseAdapter.
* DataModelAdapter.java extends RecyclerView.Adapter<DataAdapter.DataViewHolder>
- inflate list item, and get view handle.
- instance of ViewHolder and pass View handle.
- setting the data to items. (usually call a method in ViewHolder)
- total number of items.
Create instance of Adapter and attach it to RecyclerView.
Aditionally, instead of ListView taking care of presenting the data,
in RecyclerView, LayoutManager will take care of presenting.
* Create instance of LayoutManager and attach it to RecyclerView.