You can read Part 1 here.
Next, step of the recyclerView implementation is to implement the recyclerView Adapter. It has two main jobs:
- to create the item views and return them to the recyclerView
- and to populate the item views.
RecyclerView creates the items that are visible but also for some before and after. Instead of creating new items, it takes one item that is last/old, moves it to the front and then recyclerView populates it with new data. In other words, the adapter recycles the views/items
Create a recyclerView Adapter
Create a new class file for the adapter.
Create an inner class ViewHolder that extends RecyclerView.ViewHolder. ViewHolder holds a reference to the main view and to the contained views. It must have fields for all the views used to display the information we need. Create also a default constructor.
Now extend the adapter class, the outer class. It should extend RecyclerView.Adapter that takes a type argument the ViewHolder you created.
Now, override the three methods that are important.
Before we implement the methods, we need three private fields. Context, LayoutInflater and a List for the data
Now while on the Context or List<>, press Alt + Enter and click Add constructor parameters. Select Context, List and click OK
It creates a new constructor with those two parameters
Now create a LayoutInflater from the context
Create a View and return the ViewHolder. Inflate takes 3 parameters, the item layout, the viewgroup that passed, and false because we do not want the view to be attached to its parent.
getIemCount must return the total amount of the data we have
Before we bind the data to our view we need to get the references for all the views in the item layout. Create public fields so they can be called from the outer class and then get the references in the ViewHolder inner class.
Now, it is time to bind the data to the view
Now at the activity java class that has the recyclerView, we need to create a reference to the recyclerView
Create a new Linear Layout Manager and set it to the recyclerView
Associate the RecyclerView adapter with the recyclerView. But first we need to instantiate the adapter with the data.
Here is how it looks 😛
END OF PART 2
- Android – Notifications
- Content Provider – Part 3 – insert, delete, update, getType
- Content Provider – Part 2 – create and query