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”.

Adapter
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.

ViewHolder
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.

MainActivity
onCreate – Set up the RecyclerView

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

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