1. 程式人生 > >Writing a RecyclerView Adapter in Kotlin (KAD 16)

Writing a RecyclerView Adapter in Kotlin (KAD 16)

An interesting way to see how Kotlin simplifies your life is by creating a RecyclerView Adapter.

You’ll see that the code can be organized in such a way that its reading is easier and it avoids redundant code.

RecyclerView Adapter in Kotlin

We’ll create an Adapter that will set a title and an image into a cell.

It’ll be a very simple adapter in which we won’t allow the modification of the items. If we want new data, we will create a new adapter and set it to the RecyclerView.

The model

We’ll use a very simple model too, which only needs an identifier, the title and the url of the image.

We’ll use a data class, which if you remember we saw

a few articles ago:

1 data classItem(val id:Long,val title:String,val url:String)

With this we already have a class with its constructor, its immutable properties, and other useful functions like equals

or hashCode implemented.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

The Adapter

The Adapter’s structure would be the following, self-generating the necessary methods:

123456789101112 classMyAdapter:RecyclerView.Adapter(){override fun onCreateViewHolder(parent:ViewGroup?,viewType:Int):ViewHolder{}override fun onBindViewHolder(holder:ViewHolder?,position:Int){}foverride fun getItemCount():Int{}classViewHolder(itemView:View):RecyclerView.ViewHolder(itemView)}

You’ll see that I’ve created a ViewHolder class, which extends from the original.

This is because the Adapter needs an implementation of the original abstract class.

Also, there are some elements marked as nullable. This is because if the library isn’t properly annotated with the annotations @Nullable and @NonNull, Kotlin has no way of knowing if nulls are allowed, and it lets us decide.

If we self-generate the methods, by default it’ll take for granted that the values are nullable.

But studying the support library a bit, we know that those values aren’t null, so we can remove it:

12345678910111213 classMyAdapter:RecyclerView.Adapter(){override fun onCreateViewHolder(parent:ViewGroup,viewType:Int):ViewHolder{}override fun onBindViewHolder(holder:ViewHolder,position:Int){}override fun getItemCount():Int{}classViewHolder(itemView:View):RecyclerView.ViewHolder(itemView)}

The constructor

The adapter needs to receive the items and a listener by parameter. The result is something like this:

1 classMyAdapter(val items:List,val listener:(Item)->Unit)
12345 override fun onCreateViewHolder(parent:ViewGroup,viewType:Int)=ViewHolder(parent.inflate(R.layout.view_item))override fun onBindViewHolder(holder:ViewHolder,position:Int)=holder.bind(items[position],listener)override fun getItemCount()=items.size

There are three methods can be implemented with the contracted form, obtaining the previous result. In three lines we have all the adapter implemented.

Now go for the ViewHolder implementation.

The ViewHolder

The ViewHolder will assign the values from the model to their corresponding views:

1234567 classViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){fun bind(item:Item,listener:(Item)->Unit)=with(itemView){itemTitle.text=item.titleitemImage.loadUrl(item.url)setOnClickListener{listener(item)}}}

As mentioned by Nabil in the comments, this way to use Kotlin Android Extensions in Views has some hidden costs, and is not always optimal. Take a look at the Kotlin Android Extensions article in this blog, where I show a new way to use cache on ViewHolders, and also this other article which talks about this hidden costs I’m mentioning. In any case, my recommendation is to test before optimizing.

Adapter assignment

There’s only one thing left: assign the adapter to the view

1234 recycler.layoutManager=GridLayoutManager(this,2)recycler.adapter=MyAdapter(items){toast("${it.title} Clicked")}

The final function is listener, which receives an item. The code will simply print the title of the item you click on.

Conclusion

As simple as that is to implement a RecyclerView Adapter in Kotlin.

Using a few of the tools we have learned so far, we’ve simplified the code to the minimum.

If you want to learn a lot more about all this and get enough fluency to create your own Android Apps, I recommend that you get the free guide to learn how to build your first project, or just get the book and learn how to create a complete App from scratch.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Writing a RecyclerView Adapter in Kotlin (KAD 16)

An interesting way to see how Kotlin simplifies your life is by creating a RecyclerView Adapter. You’ll see that the code can be organized in such a

Writing A Twitter Bot in Golang

In this tutorial I’m going to be demonstrating how to build a twitter bot using go-twitter, a popular Go client library for the Twitter API. I’ll

Performance gain by writing a C extension in python

Performance gain by writing a C extension in pythonInterpreted language will never match the performance of compiled languages . Ever since I moved on to p

Functional operations with collections in Kotlin (KAD 11)

I must admit that, for me, one of the most frustrating things when writing Java ccode is the list handling. Java 8 has some improvements in this resp

Say goodbye to NullPointerException. Working with nulls in Kotlin (KAD 19)

It had taken me too long to write an article to one of the most important parts of Kotlin: the treatment of nullity. Tony Hoare, the creator of the i

Data Classes in Kotlin: save a good bunch of lines of code (KAD 10)

We’ve already seen the classes in an earlier article, but data classes go a little further in helping us simplify our code. What are data classes? A

Reified Types in Kotlin: how to use the type within a function (KAD 14)

One of the limitations that most frustrates Java developers when using generics is not being able to use the type directly. Normally this is solved b

Display Objects of Different Types in a RecyclerView

The InterfaceLet’s start by creating a Literature interface that all our objects will implement. In the interface we will add a getType() method and some c

Operator overload in Kotlin: Add standard operations to any class (KAD 17)

In Kotlin, as in every language, we have predefined operators to perform certain operations. The most typical are the addition (+), subtraction (-),

How lambdas work in Kotlin. setOnClickListener transformation (KAD 18)

Although I spoke a little about it in another article, I’d like to explain in depth how lambdas work in Kotlin, and how they transform the interfaces

Custom Views in Android with Kotlin (KAD 06)

When we saw the article about classes, you may remember that in general only one constructor is used. This is a problem for creating custom views. Th

Ninja Functions in Kotlin. Understanding the power of generics (KAD 12)

The combined use of several Kotlin features mixed with the use of generics allow to create functions that will greatly simplify your code, while main

Classes in Kotlin: More power with less effort (KAD 03)

Classes in Kotlin are as simple as possible so that you can express the maximum amount of logic with the less code possible. I’ll show quickly how yo

Variables in Kotlin, differences with Java. var vs val (KAD 02)

In this second chapter we will see how variables work in Kotlin, what is val and var , and when to use one or the other. I wanted to start from he

Lambdas in Kotlin, and how they simplify Android development (KAD 07)

Lambdas are one of the most powerful tools in Kotlin, and in any other modern language, since it allows modelling functions in a much simpler way. Th

Extension functions in Kotlin: Extend the Android Framework (KAD 08)

Extension functions are a really cool feature that Kotlin provides, and that you’ll find yourself using a lot when writing Android Apps. We have to a

Property delegation in Kotlin: Assign values in Android without having the context (KAD 15)

As we’ve seen in previous articles, properties need a default value, they can’t be declared without assigning them a value. This is a problem, becaus

Anko to run background tasks with Kotlin in Android (KAD 09)

Anko is an Android library written in Kotlin by Jetbrains, that can be used for a lot of different stuff. Its main feature is to create views by code

Being a Good Boy in Spring Festival(杭電1850)(尼姆博弈)

cor gree 強烈 方案 con tracking output script 主動 Being a Good Boy in Spring Festival Time Limit: 1000/1000 MS (Java/Others) Memory Limi

A First Course in Abstract Algebra with Applications》-chaper1-數論-棣莫弗定理

mage strac str 技術分享 log -1 time img -c 定理1.24 (棣莫弗定理) 對每個實數x和每個正整數n有 基於棣莫弗定理的推論如下: 《A First Course in Abstract Algebr