Kotlin series has been developed keeping in mind, you are already familiar at least at beginner’s level.
This is the Sixth milestone towards our Kotlin series. Go to the fifth milestone if you haven’t done so.
In this series, we will simply follow the coding challenges developed for the Android Developer Fundamentals Course, Unit 2— Lesson4.
How to create RecyclerView and adapter in kotlin?
- Basically recyclerView code is pretty much the same as in java.
// Connect the wordListAdapter with the recycler view.
recyclerview!!.adapter = wordListAdapter// Give the recycler view a default layout manager.
recyclerview!!.layoutManager = LinearLayoutManager(this)// Notify the wordListAdapter, that the data has changed.
recyclerview!!.adapter.notifyItemInserted(wordListSize)
- The recyclerView adapter is also the same except for the viewHolder, where we can access the item in the adapter and how we can initialize the onClickListener as:
inner class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val wordItemView = itemView.word
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View) {
// All we do here is prepend "Clicked! " to the text in the // view, to verify that the correct item was clicked. The underlying // data does not change.
wordItemView.text = "Clicked! " + wordItemView.text
}
}
Project Source code: RecyclerView in Kotlin
The Seventh milestone in this series.
7. Working in the Background in Kotlin
References:
- Using Kotlin for Android development ~ Kotlin.org
- Resources to Learn Kotlin ~ developer.android
- Video of Lectures ~ youtube.com
- RecyclerView ~ developer.android