RecyclerView in Kotlin: A Modern Way to Display Lists in Android

Reza Ramesh
2 min readJul 6, 2023

--

RecyclerView is a view group that displays a list of scrollable items. It’s a more advanced version of ListView with improved performance and flexibility. RecyclerView is part of the Android Jetpack library, which provides a set of components, tools, and guidance to help developers write high-quality apps more easily.

To use RecyclerView in your app, you need to follow these steps:

  • Add the RecyclerView dependency to your project’s build.gradle file.
  • Add the RecyclerView element to your layout file.
  • Create a ViewHolder class that extends RecyclerView.ViewHolder and defines the views for each item in the list.
  • Create an Adapter class that extends RecyclerView.Adapter and binds the data to the views in the ViewHolder.
  • Set the Adapter on the RecyclerView.

For example, you can create a simple RecyclerView that displays a list of text elements:

class MyAdapter(private val myDataset: Array<String>) :
RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
 class MyViewHolder(val textView: TextView) :   RecyclerView.ViewHolder(textView)
    override fun onCreateViewHolder(parent: ViewGroup,
viewType: Int): MyAdapter.MyViewHolder {
val textView = LayoutInflater.from(parent.context)
.inflate(R.layout.my_text_view, parent, false) as TextView
return MyViewHolder(textView)
}
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = myDataset[position]
}
    override fun getItemCount() = myDataset.size
}

Then, you can create a layout file that contains the RecyclerView element:

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />

And you can set up the RecyclerView in your activity or fragment:

val recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = MyAdapter(arrayOf("Item 1", "Item 2", "Item 3"))

If you want to learn more about RecyclerView and how to use it to display lists in your app, you can check out the following resources:

RecyclerView is a powerful and flexible view group that lets you display lists of data in your Android app. With Kotlin skills, you can build better apps faster and easier. So what are you waiting for? Start scrolling today!

Reza Ramesh

--

--

Reza Ramesh
Reza Ramesh

Written by Reza Ramesh

I am an Android developer and UI/UX designer with 5 years of experience in creating engaging and user-friendly mobile applications

No responses yet