android – kotlin如何使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) -> Unit
fun setMyListener(listener: MyListener) { ... }

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...