我正在try 构建一个setOnFocusChangeListener的内联函数

This is what I got so far:

inline fun EditText.onFocusChange(crossinline hasFocus: (Boolean) -> Unit) {
    setOnFocusChangeListener(View.OnFocusChangeListener { view, b -> })
}

我就是这样用的

freightTimeOfDay.onFocusChange { doSomething() }

不幸的是,虽然它没有给我错误,但doSomething()永远不会被调用.

I'm looking for two things here:

1 - Get a param in there so I can pass it on to doSomething(). For example

freightTimeOfDay.onFocusChange { doSomething(hasFocus) }

2 - Make it work :p, as right now nothing is happening.

Update:

Seems like kotlin already has some type of inline for this

editText.setOnFocusChangeListener { view, b -> doSomething(b) }

However this isn't working for me either, doSomething(hasFocus: Boolean) is never called.

Thanks in advance!

推荐答案

只是为了澄清一下,创建内联方法扩展实际上并没有什么意义. 这是我最初的目标,但后来我意识到使用:

editText.setOnFocusChangeListener { view, b -> doSomething(b) }

是可能的,它是内联的,很漂亮,不需要额外的工作

Kotlin相关问答推荐

最好的方法来创建一个 map 在kotlin从两个列表

Kotlin -从列表中获取特定过滤器的唯一列表值

无法访问类kotlin.coroutines.CoroutineContext';.判断模块类路径中是否存在丢失或冲突的依赖项

为什么Kotlin不用static inner class来实现带有object关键字的单例呢?

Kotlin:调用 CoroutineScope.launch 与在协程内启动之间的区别

Kotlin 协程按顺序执行,但仅在生产机器上执行

Kotlin 插件之间的区别

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

从带有 Room 和 Flows 的 SQLite 表中获取祖先树

嵌套数组 indexOf()

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

Android 导航组件 - 向上导航打开相同的片段

Kotlin:内部类如何访问在外部类中声明为参数的变量?

Fragment的onDestroy()中是否需要将ViewBinding设置为null?

使用 clear() 删除 EncryptedSharedPreferences 不起作用

Kotlin惰性默认属性

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

在Kotlin中传递并使用函数作为构造函数参数

指定为非null的参数在ArrayAdaper中为null

在android java类中使用Kotlin扩展