Android: RecyclerView (Kotlin)

XML Layout
Create a new layout file with a LinearLayout at the top level if you plan to display multiple Views for each item. If you will only have one view, i.e. a TextView, you can make that your top level View instead. Give it an id and set the layout_width and layout_height to “wrap_content”.

MyAdapter extends RecyclerView.Adapter<MyViewHolder>
Once you have created the Adapter class, go ahead and create the inner ViewHolder class so the implemented methods will have the correct type. Then implement the Adapter classes:
onCreateViewHolder – Inflate the xml layout, and use it to create and return an instance of your ViewHolder.

val adapterLayout = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)

onBindViewHolder – Get the item from the cached list of items, and use it to set the content of the View inside the ViewHolder (be sure to handle a null list of items).
getItemCount – Return the size of the cached list of items – handle null case.

MyViewHolder extends RecyclerView.ViewHolder. This can be an inner class of the Adapter. The constructor takes a View as a parameter. This is the layout that gets inflated by the adapter. Get any Views from the parent and store them as a member variables. You can call findViewById on the parent View to get its children.

onCreate – Set up the RecyclerView

// Kotlin
// Initialize data.
val myDataset = Datasource().loadAffirmations()
val recyclerView = findViewById<RecyclerView>(
recyclerView.adapter = ItemAdapter(this, myDataset)

// Java
RecyclerView recyclerView = findViewById(;
recyclerView.setAdapter(new MyAdapter(this));
// a layout manager must be provided for the RecyclerView to function
recyclerView.setLayoutManager(new LinearLayoutManager(this));

How To: View Binding in Android

In your app build.gradle file, add the following lines to the “android” section:

buildFeatures {
    viewBinding = true

In your main class, create a member variable called, “binding”, where the name of the binding class is the name of the layout converted to camelCase:

 lateinit var binding: ActivityMainBinding

In onCreate(), initialize the view binding:

binding = ActivityMainBinding.inflate(layoutInflater)

Call setContentView with “binding.root” instead of the main layout file:


Now you can access views using the binding object like this, where the name of the view is its id converted to camelCase.: