Today I will cook a juicy RecyclerView in Kotlin way. Minimum consumables, maximum output. Juicy, fragrant, powerful and simple at the same time. Help yourself!

First you need to create an empty project, not forgetting to enable Kotlin language support in the project settings. Then you need to add the RecyclerView support to the build.gradle file in the app module:

implementation 'com.android.support:recyclerview-v7:28.0.0-alpha3'

Currently the latest version is 28.0.0-alpha3. Of course, over time, the current version will be different. After that, you can remove the default TextView from the layout file and place RecyclerView instead:

<android.support.v7.widget.RecyclerView
    android:id="@+id/myRecycler"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layoutManager="android.support.v7.widget.LinearLayoutManager"
    tools:listitem="@layout/main_item"
    />

And also creating a markup file for the list item and a class code for storing the items:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/firstName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="First name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:layout_marginStart="5dp"
        android:textSize="18sp"
        />

    <TextView
        android:id="@+id/lastName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Last name"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@id/firstName"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:layout_marginStart="5dp"
        android:textSize="18sp"
        />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/colorAccent"
        app:layout_constraintTop_toBottomOf="@id/firstName"
        />

</android.support.constraint.ConstraintLayout>
data class MainItem(
        val firstName: String,
        val lastName: String
)

Now you need to create an adapter:

class MainAdapter(var items: List<MainItem>, val callback: Callback) : RecyclerView.Adapter<MainAdapter.MainHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
            = MainHolder(LayoutInflater.from(parent.context).inflate(R.layout.main_item, parent, false))

    override fun getItemCount() = items.size

    override fun onBindViewHolder(holder: MainHolder, position: Int) {
        holder.bind(items[position])
    }

    inner class MainHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val firstName = itemView.findViewById<TextView>(R.id.firstName)
        private val lastName = itemView.findViewById<TextView>(R.id.lastName)

        fun bind(item: MainItem) {
            firstName.text = item.firstName
            lastName.text = item.lastName
            itemView.setOnClickListener {
                if (adapterPosition != RecyclerView.NO_POSITION) callback.onItemClicked(items[adapterPosition])
            }
        }
    }

    interface Callback {
        fun onItemClicked(item: MainItem)
    }

}

As you can see from the code, the list of elements and the callback interface, which will be implemented in the Activity class, are immediately transferred to the adapter constructor.
Now you can find the RecyclerView in the Activity. At Kotlin, it is very simple. You need to use the kotlin-android-extensions library. Using it, you can simply import the XML layout file into Activity and all elements that have id will be available in the code by this id:

import kotlinx.android.synthetic.main.activity_main.*

Now it’s time to creating a list of test data, declaring the adapter, assigning a list to the adapter, implementing the callback interface and passing the adapter to RecycltrView:

val items = listOf(
        MainItem("Александр", "Пушкин"),
        MainItem("Михаил", "Лермонтов"),
        MainItem("Александр", "Блок"),
        MainItem("Николай", "Некрасов"),
        MainItem("Фёдор", "Тютчев"),
        MainItem("Сергей", "Есенин"),
        MainItem("Владимир", "Маяковский")
)

val myAdapter = MainAdapter(items, object : MainAdapter.Callback {
    override fun onItemClicked(item: MainItem) {
        //TODO Here comes element, that was clicked on. You can continue to work with it.
    }
})

myRecycler.adapter = myAdapter

Actually, that’s all. You can run it and enjoy.

The code in this article can be found on GitHub.

Leave a Reply