ListView with ViewHolder in Kotlin

In this post we will create a ListView with ViewHolder adapter but we will write the code in Kotlin.

For creating xml files for ListView and list items, follow the steps from this post.

Next, you have to create a new Kotlin class for the adapter. Name the new created file MyCustomAdapter


import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView

class MyCustomAdapter(context: Context, val items: List<String>) : BaseAdapter() {
    private val layoutInflater = LayoutInflater.from(context)

    override fun getCount(): Int {
        return items.size

    override fun getView(position: Int, view: View?, viewGroup: ViewGroup?): View? {
        val viewHolder: ViewHolder
        val rowView: View?

        if (view == null) {
            rowView = layoutInflater.inflate(R.layout.list_item, viewGroup, false)

            viewHolder = ViewHolder(rowView)
            rowView.tag = viewHolder

        } else {
            rowView = view
            viewHolder = rowView.tag as ViewHolder

        viewHolder.itemName.text = items[position]

        return rowView

    override fun getItem(position: Int): Any {
        return 0

    override fun getItemId(position: Int): Long {
        return 0

    private class ViewHolder(view: View?) {
        val itemName = view?.findViewById( as TextView


What’s different in this adapter written in Kotlin compared to the one in Java is that we had to create rowView variable in order to be able to inflate the list_item layout to the view. In Kotlin if we try to inflate the layout directly to the view: View? attribute we will get an error “Val cannot be reassigned”.


import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        val names = mutableListOf<String>()

        for (i in 1..10) {

        listView.adapter = MyCustomAdapter(this, names)
Exit mobile version