Daniele
Daniele

Reputation: 4343

Kotlin - How to implement an ItemClickListener for RecyclerVIew

Now that google officially support Kotlin as the primary (or soon to be) language in android, I was trying to translate a project of mine. Even though the Android Studio built-in "Translator" works pretty fine, it apparently couldn't translate a ItemClickListener for a RecyclerView

As an example this is what I have:

In java, I'm using this class I found on GitHub to implement it.

This is my Java code:

ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
                @Override
                public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                    ...
            });

How do I set an ItemClickListener for a RecyclerView in Kotlin?

Upvotes: 1

Views: 2820

Answers (1)

zsmb13
zsmb13

Reputation: 89678

You can actually just copy paste that Java code into a Kotlin file, and you'll get the Kotlin code that does the same thing, using the built in converter.

(You can also invoke this converter for an entire Java file with Ctrl+Alt+Shift+K on Windows, ^⌥⇧K on Mac, or from the menu via Code -> Convert Java File to Kotlin File.)

What it gives you is the following:

ItemClickSupport.addTo(recyclerView).setOnItemClickListener { recyclerView, position, v ->
    // ...
}

This makes use of SAM conversion, and is equivalent to this longer, more Java-like form of calling the function:

ItemClickSupport.addTo(recyclerView).setOnItemClickListener(
        object : ItemClickSupport.OnItemClickListener {
            override fun onItemClicked(recyclerView: RecyclerView?, position: Int, v: View?) {
                 // ...
            }
        }
)

Upvotes: 4

Related Questions