How to create RecyclerView with Header in Kotlin

In this android kotlin source code example, we are going to create RecyclerView with Header in Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to create RecyclerView with Header in Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".recyclerView.RecyclerViewActivity16">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        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"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.bluapp.kotlinview.R
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager


class RecyclerViewActivity16 : AppCompatActivity() {
    private var list: RecyclerView? = null
    private val TYPE_HEADER: Int = 0
    private val TYPE_ITEM: Int = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_recycler_view16)
        list = findViewById(R.id.list) as RecyclerView
        val linearLayoutManager = LinearLayoutManager(this@RecyclerViewActivity16)
        list!!.setLayoutManager(linearLayoutManager)
        list!!.setHasFixedSize(true)
        val customAdapter = CustomRecyclerViewAdapter(getDataSource())
        list!!.setAdapter(customAdapter)
    }

    inner class CustomRecyclerViewAdapter(private val itemObjects: List<ItemObject>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            if (viewType == TYPE_HEADER) {
                val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.header_layout, parent, false)
                return HeaderViewHolder(layoutView)
            } else if (viewType == TYPE_ITEM) {
                val layoutView = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
                return ItemViewHolder(layoutView)
            }
            throw RuntimeException("No match for $viewType.")
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val mObject = itemObjects[position]
            if (holder is HeaderViewHolder) {
                (holder as HeaderViewHolder).headerTitle.setText(mObject.contents)
            } else if (holder is ItemViewHolder) {
                (holder as ItemViewHolder).itemContent.setText(mObject.contents)
            }
        }

        private fun getItem(position: Int): ItemObject {
            return itemObjects[position]
        }

        override fun getItemCount(): Int {
            return itemObjects.size
        }

        override fun getItemViewType(position: Int): Int {
            return if (isPositionHeader(position)) TYPE_HEADER else TYPE_ITEM
        }

        private fun isPositionHeader(position: Int): Boolean {
            return position == 0
        }
    }

    inner class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var headerTitle: TextView
        init {
            headerTitle = itemView.findViewById(R.id.header)
        }
    }

    inner class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var itemContent: TextView
        init {
            itemContent = itemView.findViewById(R.id.itemcontent) as TextView
        }
    }

    inner class ItemObject(val contents: String)

    private fun getDataSource(): List<ItemObject> {
        val data = ArrayList<ItemObject>()
        data.add(ItemObject("Country"))
        data.add(ItemObject("Nigeria"))
        data.add(ItemObject("Finland"))
        data.add(ItemObject("Denmark"))
        data.add(ItemObject("Argentina"))
        data.add(ItemObject("Andorra"))
        return data
    }
}

header_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16sp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textStyle="bold"
        android:textColor="#000000"
        android:text="Header"/>
</LinearLayout>

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <TextView
            android:id="@+id/itemcontent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="20dp"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="16sp"
            android:gravity="center"
            android:text="Item" />

    </androidx.cardview.widget.CardView>

</LinearLayout>

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.