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
MyCustomAdapter.kt
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(R.id.list_item_text_view) 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”.
MainActivity.kt
import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val names = mutableListOf<String>() for (i in 1..10) { print(i) names.add("Diana$i") } listView.adapter = MyCustomAdapter(this, names) } }