[英]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. 现在谷歌正式支持Kotlin作为android中的主要(或即将成为)语言,我试图翻译我的一个项目。 Even though the Android Studio built-in "Translator" works pretty fine, it apparently couldn't translate a ItemClickListener
for a RecyclerView
虽然Android Studio内置的“Translator”工作得非常好,但它显然无法为RecyclerView
转换ItemClickListener
As an example this is what I have: 举个例子,这就是我所拥有的:
In java, I'm using this class I found on GitHub to implement it. 在java中,我正在使用我在GitHub上找到的这个类来实现它。
This is my Java code: 这是我的Java代码:
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? 如何在Kotlin中为RecyclerView设置ItemClickListener?
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. 实际上,您只需将Java代码粘贴到Kotlin文件中,然后使用内置转换器即可获得使用相同功能的Kotlin代码。
(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.) (您也可以在Windows上使用Ctrl + Alt + Shift + K ,在Mac上使用^⌥⇧K或通过代码 - >将Java文件转换为Kotlin文件从菜单调用整个Java文件的转换器。)
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: 这使用了SAM转换 ,相当于这种更长,更像Java的调用函数形式:
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(
object : ItemClickSupport.OnItemClickListener {
override fun onItemClicked(recyclerView: RecyclerView?, position: Int, v: View?) {
// ...
}
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.