RecyclerView and CardView in Android

Duration

15 minutes

Tip: If you are doing this exercise live in a session, make sure to make good use of the instructor, they are online to answer any questions you have!

Goals

The goal here is to code a view holder for your restaurant layout file. The restaurant layout contains one TextView and one RatingBar so your view holder will have one property for each of those two views.

Required assets

The provided Resources folder for this part contains a subfolder named Completed with a solution you can use to check your work. This lab is a continuation of the previous one. If you did not complete the previous exercise, you can use the Completed solution from the previous part as starter code for this part.

Challenge

Use the guidelines here to code a view holder for your restaurant layout file. Alternatively, you can use the step-by-step instructions given below.

  1. Create a class named RestaurantViewHolder. Be sure to derive it from the required base.
  2. Add properties for the views inside your layout file.
  3. Code a constructor that takes the root item-view and sets the properties.

Steps

Below are the step-by-step instructions to implement the exercise.

Code a view holder

  1. Add a new class named RestaurantViewHolder to your project.
  2. Derive your view holder from RecyclerView.ViewHolder.
  3. Add a public property for each of the two views inside your layout file: one TextView and one RatingBar.
  4. Implement a constructor.
    1. Your constructor must take one parameter of type View. By convention, a common name for this parameter is itemView since it will be the root view inside of your item-layout file.
    2. Pass the itemView parameter to your base-class constructor for storage in the ItemView property.
    3. Use FindViewById on itemView to get references to the TextView and RatingBar inside itemView. Load the references into your properties.
  5. Compile your app. You do not need to run it since it will not display any output.

Summary

Here you implemented a view holder for your restaurant layout file. This will be used by your adapter to bind data into your UI. This is mainly an efficiency optimization: you call FindViewById one time to get references to your views and then use the references to load new data as the layout is recycled. In other words, your properties are roughly analogous to a cache; you lookup the references once and then cache them for repeated use in the future.

Go Back