Duration
15 minutes
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.
- Create a class named
RestaurantViewHolder
. Be sure to derive it from the required base. - Add properties for the views inside your layout file.
- 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
-
Add a new class named
RestaurantViewHolder
to your project. -
Derive your view holder from
RecyclerView.ViewHolder
. -
Add a public property for each of the two views inside your layout file: one
TextView
and oneRatingBar
. -
Implement a constructor.
-
Your constructor must take one parameter of type
View
. By convention, a common name for this parameter isitemView
since it will be the root view inside of your item-layout file. -
Pass the
itemView
parameter to your base-class constructor for storage in theItemView
property. -
Use
FindViewById
onitemView
to get references to theTextView
andRatingBar
insideitemView
. Load the references into your properties.
-
Your constructor must take one parameter of type
- 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.