4.3 Implementation of a Recycler View
Several different classes work together to build your dynamic list.
RecyclerView
is theViewGroup
that contains the views corresponding to your data. It's a view itself, so you addRecyclerView
into your layout the way you would add any other UI element.- Each individual element in the list is defined by a view holder object. When the view holder is created, it doesn't have any data associated with it. After the view holder is created, the
RecyclerView
binds it to its data. You define the view holder by extendingRecyclerView.ViewHolder
. - The
RecyclerView
requests those views, and binds the views to their data, by calling methods in the adapter. You define the adapter by extendingRecyclerView.Adapter
. - The layout manager arranges the individual elements in your list. You can use one of the layout managers provided by the RecyclerView library, or you can define your own. Layout managers are all based on the library's
LayoutManager
abstract class.
- Design how each element in the list is going to look and behave in some layout file. Based on this design, extend the
ViewHolder
class. Your version ofViewHolder
provides all the functionality for your list items. Your view holder is a wrapper around aView
, and that view is managed byRecyclerView
. - Define the
Adapter
that associates your data with theViewHolder
views.
When you define your adapter, you need to override three key methods:
-
onCreateViewHolder()
:RecyclerView
calls this method whenever it needs to create a newViewHolder
. The method creates and initializes theViewHolder
and its associatedView
, but does not fill in the view's contents—theViewHolder
has not yet been bound to specific data. -
onBindViewHolder()
:RecyclerView
calls this method to associate aViewHolder
with data. The method fetches the appropriate data and uses the data to fill in the view holder's layout. For example, if theRecyclerView
displays a list of names, the method might find the appropriate name in the list and fill in the view holder'sTextView
widget. -
getItemCount()
: RecyclerView calls this method to get the size of the data set. For example, in an address book app, this might be the total number of addresses. RecyclerView uses this to determine when there are no more items that can be displayed.
First we introduce the data model that will be used for the rest of this lesson:
data class Book(var bookName: String, var author: String, val publisher: String)
Here's a typical example of a simple adapter with a nested
ViewHolder
that displays a list of data. In this case, the RecyclerView displays a simple list of Book elements. The adapter is passed an array of books, containing the data needed for the ViewHolder
elements:class CustomAdapter(private val dataSet: List<Book>) :
RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
/**
* Provide a reference to the type of views that you are using
* (custom ViewHolder).
*/
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val bookName: TextView = view.findViewById(R.id.book_name)
val author: TextView = view.findViewById(R.id.author)
val publisher: TextView = view.findViewById(R.id.publisher)
}
// Create new views (invoked by the layout manager)
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
// Create a new view, which defines the UI of the list item
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.book_row_item, viewGroup, false)
return ViewHolder(view)
}
// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
viewHolder.bookName.text = dataSet[position].bookName
viewHolder.author.text = dataSet[position].author
viewHolder.publisher.text = dataSet[position].publisher
}
// Return the size of your dataset (invoked by the layout manager)
override fun getItemCount() = dataSet.size
}
The snippet above can be tailored to your specific needs in terms of whatever data you are trying to display as a list with RecyclerView!
The layout for the each view item is defined in an XML layout file, similarly as we do for activities. In this case, the app has a
book_row_item.xml
file like this:<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="12dp"
app:cardElevation="10dp"
app:cardUseCompatPadding="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="110dp"
android:background="@color/white">
<TextView
android:id="@+id/book_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="10dp"
android:layout_marginStart="10dp"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="10dp"
android:layout_marginStart="10dp"
android:textSize="17sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/book_name" />
<TextView
android:id="@+id/publisher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginVertical="10dp"
android:layout_marginStart="10dp"
android:textSize="17sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/author" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
In this case, I use a new
ViewGroup
called CardView
to build beautiful row items for our RecyclerView
! CardView
is an extended version of Framelayout
which can be used to show items inside the card format. With the help of CardView
, we can add radius, elevation to our items of RecyclerView
. CardView
gives a rich look and feel to our list of data. Check this out to learn more!
CardView row for our Book objects
1. We can add
RecyclerView
to our layout file as such:my_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- A RecyclerView with some commonly used attributes -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
2. Integrate it into activity:
MyActivity.kt
class MyActivity : AppCompatActivity() {
private lateinit var recyclerView : RecyclerView
override fun onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.my_activity)
recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view)
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerView.setHasFixedSize(true)
// use a linear layout manager
recyclerView.layoutManager = LinearLayoutManager(this)
// create dataset, format should match what you specified
// in the MyAdapter object
var myDataset = mutableListOf<Book>()
// Populate your myDataset with your data
...
recyclerView.adapter = CustomAdapter(myDataset)
}
// ...
}
In MyActivity.kt, I simply used a LinearLayoutManager to arrange our RecyclerView items. LinearLayoutManager arranges the items in a one-dimensional list but there are other managers available!
- If the grid is arranged vertically,
GridLayoutManager
tries to make all the elements in each row have the same width and height, but different rows can have different heights. - If the grid is arranged horizontally,
GridLayoutManager
tries to make all the elements in each column have the same width and height, but different columns can have different widths.
-
StaggeredGridLayoutManager
is similar toGridLayoutManager
, but it does not require that items in a row have the same height (for vertical grids) or items in the same column have the same width (for horizontal grids). The result is that the items in a row or column can end up offset from each other. - One can also create a customized Layout Manager!

Linear Layout, Grid Layout, Staggered Grid Layout, Custom Grid Layout
This is the bare bone code that is needed to create a recycler view list in Android. In the next section, we’ll be delving into an example of adding touch input.
Last modified 10mo ago