[英]Trying to pass a function parameter in Kotlin
I have a function:我有一个功能:
fun test(){
Timber.d("Button Clicked")
}
And I'm trying to pass this function to a fragment.我正在尝试将此函数传递给片段。 Here is that field inside my fragment.
这是我的片段中的那个字段。
class MyFragment(val layout: Int) : Fragment() {
var clickEvent1: (() -> Unit)? = null
}
And this is how I'm setting this field before beginning fragment transaction.这就是我在开始片段交易之前设置这个字段的方式。
fragment.clickEvent1 = {test()}
My goal is to run this function on my button click inside my fragment.我的目标是在我的片段内单击按钮时运行此函数。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
dialog_option_1.setOnClickListener { clickEvent1 }
}
There's an issue with the way I'm doing this because the "test" function does not run.我这样做的方式有问题,因为“测试”功能没有运行。 Can someone point me in the right direction?
有人可以指出我正确的方向吗? Thanks
谢谢
Use用
dialog_option_1.setOnClickListener(clickEvent1)
You need to pass the lambda itself to method, so you should use () parentheses instead of {}, which create a new lambda that just does almost nothing in your case.您需要将 lambda 本身传递给方法,因此您应该使用 () 括号而不是 {},这会创建一个新的 lambda,在您的情况下几乎不执行任何操作。
Should be应该
dialog_option_1.setOnClickListener { clickEvent1() }
if you want to do it like that.如果你想这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.