RecyclerView made easy
This article will explain what is RecyclerView and how to use it with an example : a simple News App.
First of all, what is RecyclerView?
RecyclerView is the appropriate view to use when you have a lot data to display in items and it’s very likely that your user’s device cannot present all of those items at once.
For instance, let’s take our Contacts App, each contact is an item.
When the user scrolls, visible items which became out of view will be recycled and reused when a new item comes into view.
We use RecyclerView for a simple reason: your phone have a limited amount of memory. Consequently, if you create for each contact an item, you will use a lot of memory.
Elements of RecyclerView:
Adapter
- Used to provide the RecyclerView with new views when needed.
- Bind data from DataSource.
- Send View to ViewHolder thanks to this object.
ViewHolder
- Holds all sub views that depend on the current item’s data → caches of your View objects.
LayoutManager
- Tells the RecyclerView how to layout all those views (vertically, horizontally…).
How to create a RecyclerView?
STEP 1: Add RecyclerView dependency in Build.app
dependencies { ... compile 'com.android.support:recyclerview-v7:25.1.1'}
STEP 2: Create a RecyclerView that match_parent in your activity.xml and assign an id
<android.support.v7.widget.RecyclerView android:id="@+id/rv_news" android:layout_width="match_parent" android:layout_height="match_parent" />
STEP 3: Create a Layout (item.xml)
This layout will be used to hold each item.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Au PS, la fronde s'organise contre Hamon"
android:textColor="#000000"/>
</FrameLayout>
STEP 4: Create our LayoutManager
Determines how the collection of items is displayed.
3 implements:
- Linear
- Grid Layout
- Staggered Grid Layout Manager
@Overrideprotected void onCreate(Bundle savedInstanceState) { ...// Create fake News
ArrayList<News> data = new ArrayList<>();
data.add(new News("13 reasons why Rotterdam may be Europe's new capital of cool"));
data.add(new News("Protests after Netherlands bars Turkish official's plane from landing"));
data.add(new News("Abuja airport shutdown 'hugely embarrassing'"));
data.add(new News("Somalia: 'People are dying of hunger'"));
data.add(new News("Concern over yellow fever outbreak"));
data.add(new News("Detained DREAMer files petition to go free"));
data.add(new News("Mexico opens immigrant defense centers"));
data.add(new News(" Canada: 'Point to prove' after funds cut"));
data.add(new News("Mark Zuckerberg, Priscilla Chan expecting second baby girl"));
data.add(new News("Tinder's Sean Rad: App has made 250,000 transgender matches"));
data.add(new News("California officially embraces the self-driving car"));
data.add(new News("Cory Booker: We need to love each other"));
data.add(new News("H-4 visa holder: Working 'changed my life'"));
data.add(new News("Testing earbuds that translate in real-time"));
data.add(new News("Experts: 'Vault 7' leak describes common hacks"));
data.add(new News("Musk offers to fix Australia's energy crisis in 100 days"));// Get a reference of our RecyclerView from xml
// It allows us the do things like set the Adapter of the RecyclerView and toggle the
// visibility
RecyclerView mNewsList = (RecyclerView) findViewById(R.id.rv_news);
// GridLayoutManager is responsible for measuring and positioning item views within a RecyclerView
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mNewsList.setLayoutManager(layoutManager);
// Don't change the size of the content
mNewsList.setHasFixedSize(true);NewsAdapter adapter = new NewsAdapter(getApplicationContext(), NUM_ITEMS, data);
mNewsList.setAdapter(adapter);
}
Step 5: Create our custom class
We have to define our data model that stands at the base of our UI (i.e. what information we want to show). For this purpose, we can define a simple class:
In News.class:
public class News { //Our class News will have // @mNewsTitle : Titleprivate String mNewsTitle; public News(String title){ mNewsTitle = title; } public String getNewsTitle(){ return mNewsTitle; } }
STEP 6: Create a ViewHolder
public class NewsAdapter extends RecyclerView.Adapter< NewsAdapter.NewsViewHolder> {
List<News> mNews;
// ViewHolders cache the references to the views that will be modified in the adapter.
// We create a class called NewsViewHolder that extends Recycler.ViewHolder
public class NewsViewHolder extends RecyclerView.ViewHolder {
// Create a TextView variable called listItemNumberView
TextView listItemNumberView = (TextView) itemView.findViewById(R.id.tv_title);
// Create a constructor for NewsViewHolder that accepts a View called itemView as a parameter
public NewsViewHolder(View itemView) {
super(itemView);
listItemNumberView = (TextView) itemView.findViewById(R.id.tv_title);
}
}
STEP 7: Create our Adapter
An Adapter connect RecyclerView to a data source.
- The Adapter is called to create new items (in the form of ViewHolders).
- He populates the items with data.
- He returns information about data (how many items…).
The data could come from an ArrayList, the JSON result of a network request, or any data source.
The Adapter requires us to override 3 functions:
- onCreateViewHolder: called when the RecyclerView instantiates a new ViewHolder instance (inflates the items view from xml → creates them in code → return a new ViewHolder object).
- onBindViewHolder: called when RecyclerView wants to populate the view with data from our model so that the user can see it.
- getItemCount: returns the number of items in our data source.
/*
ADAPTER
*/
// Specify how many views adapter hold
private int mNumberItems;
private Context context;
// Store a member variable for the titles
// Populate that var in the constructor
public NewsAdapter(Context context, int numberOfItems, ArrayList<News> news) {
mNumberItems = numberOfItems;
mNews = news;
this.context = context;
}
// Override our 3 functions
// onCreateViewHolder()
@Override
public NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Log.v("onCreateViewHolder", "onCreateViewHolder is called !");
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.item;
// Inflate our new item view using a LayoutInflater. It takes the ID of layout in xml.
// Then --> inflates or converts this collection of view groups and views.
LayoutInflater inflater = LayoutInflater.from(context);
// Set to false, so that the inflated layout will not be
// immediately attached to its parent viewgroup.
View view = inflater.inflate(layoutIdForListItem, viewGroup, false);
NewsViewHolder viewHolder = new NewsViewHolder(view);
return viewHolder;
}
//onBindViewHolder()
@Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
// Get the data model based on position
News news = mNews.get(position);
// Set item views based on your views and data model
TextView textView = holder.listItemNumberView;
textView.setText(news.getNewsTitle());
}
//getItemCount() : returns the mNumberItems var
@Override
public int getItemCount() {
mNumberItems = mNews.size();
return mNumberItems;
}
}
How it works?
- When the RecyclerView is being laid out and drawn → it will ask the Adapter for the numbers of items that will be displayed.
2. Then, the RecyclerView will ask the Adapter to create ViewHolder objects. And the process, inflate individually item views from their corresponding XML by calling onCreateViewHolder.
3. After each ViewHolder is created, the RecyclerView will call onBindViewHolder to populate each item with data.
4. Then, when you scroll the RecyclerView will reuse those ViewHolders asking the Adapter to bind new data to them.
And that’s it!
The complete example code here.
By the way, my article and illustrations was inspired by the excellent course “Developing Android Apps” by Udacity. Udacity provides the best courses about Android, AI, Machine Learning, VR made by tech Experts : https://www.udacity.com/
And If you liked my article, please click the💚 below so other people will see this here on Medium.