Kotlin setOnClickListener使用方法引用不起作用 [英] Kotlin setOnClickListener using method reference not working

查看:555
本文介绍了Kotlin setOnClickListener使用方法引用不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用与Java中相同的方法引用:

I tried to use method reference the same way as in Java:

button.setOnClickListener(this::clickListener);

使用Kotlin:

button.setOnClickListener {this::clickListener}

但是,这在Kotlin中不起作用,解决方案是使用labmda表达式实际调用该函数:

However this doesn't work in Kotlin, the solution is to actually invoke the function withing the labmda expression:

button.setOnClickListener {clickListener()}

在这种情况下,为什么Kotlin不接受方法引用?与Java的原理不同吗?

Why Kotlin doesn't accept the method reference in this case? Isn't the same principle as with Java?

推荐答案

大括号表示lambda表达式的内容. Kotlin已经在幕后传递了一个OnClickListener实例,并正在为您提供onClick()方法.

The curly braces denote the contents of the lambda expression. Kotlin has already passed an instance of an OnClickListener behind the scenes and is providing the onClick() method to you.

如果要传递已分配给变量的侦听器,请使用括号:

If you want to pass a listener you have assigned to a variable, use parentheses:

button.setOnClickListener(clickListener)

如果要使用函数,则与Java相同:

If you want to use a function, it's the same as Java:

button.setOnClickListener(this::clickListener)

fun clickListener(v: View) {}

这篇关于Kotlin setOnClickListener使用方法引用不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆