android–kotlin如何使setOnClickListener接受函数作为参数

android–kotlin如何使setOnClickListener接受函数作为参数,第1张

概述在kotlin中,我们可以像这样使用setOnClickListener():view.setOnClickListener{println("Hello")}但是如果我定义自己的界面,我只能传递这样的匿名对象:obj.setMyListener(object:MyListener(){...})我只是想知道他们如何使setOnClickListener()接受一个函数而不

在kotlin中,我们可以像这样使用setonClickListener():

vIEw.setonClickListener { println("Hello") }

但是如果我定义自己的界面,我只能传递这样的匿名对象:

obj.setMyListener(object: MyListener() {    ...})

我只是想知道他们如何使setonClickListener()接受一个函数而不是一个匿名对象.

解决方法:

根据Kotlin关于Java interop的文档,对于Java中定义的功能接口,您可以使用SAM转换.

Just like Java 8, Kotlin supports SAM conversions. This means that
Kotlin function literals can be automatically converted into
implementations of Java interfaces with a single non-default method,
as long as the parameter types of the interface method match the
parameter types of the Kotlin function.

val runnable = Runnable { println("This runs in a runnable") }val executor = ThreadPoolExecutor()// Java signature: voID execute(Runnable command)executor.execute { println("This runs in a thread pool") }

但是,Kotlin具有功能类型,因此SAM转换不适用于Kotlin中定义的接口:

Also note that this feature works only for Java interop; since Kotlin
has proper function types, automatic conversion of functions into
implementations of Kotlin interfaces is unnecessary and therefore
unsupported.

可能的解决方案:

>使用Java定义接口.如果它是可以从Java代码使用的库/代码,则很有用.
>使方法接收函数作为参数

// Example Listener receives a bool and return unit.  fun setMyListener(Listener: (isChecked: Bool) -> Unit) { ... }  // Usage:  obj.setMyListener { isChecked -> }

>使用类型别名(仅在Kotlin 1.1中支持):

typealias MyListener = (Bool) -> Unitfun setMyListener(Listener: MyListener) { ... }
总结

以上是内存溢出为你收集整理的android – kotlin如何使setOnClickListener接受函数作为参数全部内容,希望文章能够帮你解决android – kotlin如何使setOnClickListener接受函数作为参数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1096734.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存