有没有办法在活动之间传递函数引用? [英] Is there a way to pass a function reference between activities?

查看:62
本文介绍了有没有办法在活动之间传递函数引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin和Android中是否有捆绑功能引用的方法,以便可以从其他片段中调用功能? 例如,我的片段工厂方法如下:

is there a way of bundling function references in Kotlin and Android so that the functions can be called from other fragments? For instance, my fragment factory method looks like this:

    fun newInstance(tryAgainFunction: () -> Unit): TimeOutHandlerFragment {
        val fragment = TimeOutHandlerFragment()
        val bundle = Bundle()

        return fragment
    }

我希望能够将tryAgainFunction保存在捆绑软件中以进行进一步的检索.

I want to be able to save my tryAgainFunction in the bundle for further retrieval.

非常感谢!

修改

最后,最合适的解决方案是使用热键的答案,然后在onViewCreated中使用传递的函数初始化侦听器.完整的代码如下:

In the end, the most suitable solution was using hotkey's answer and then in onViewCreated I initializing a listener with the passed function. The complete code is as follows:

companion object {
    val CALLBACK_FUNCTION: String = "CALLBACK_FUNCTION"

    fun newInstance(tryAgainFunction: () -> Unit): TimeOutHandlerFragment {
        val fragment = TimeOutHandlerFragment()
        val bundle = Bundle()
        bundle.putSerializable(CALLBACK_FUNCTION, tryAgainFunction as Serializable)
        fragment.arguments = bundle
        return fragment
    }
}

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    try {
        val callback: () -> Unit = arguments.getSerializable(CALLBACK_FUNCTION) as () -> Unit
        btnTryAgain.setOnClickListener { callback.invoke() }
    } catch (ex: Exception) {
        // callback has a wrong format
        ex.printStackTrace()
    }
}

感谢大家的帮助!

推荐答案

如果tryAgainFunctionSerializable,则将其放入bundle .

If tryAgainFunction is Serializable, then you can put it into the bundle using bundle.putSerializable("try_again_function", tryAgainFunction);.

如果它是函数引用(SomeClass::someFunction)或lambda,则实际上为Serializable.但是,如果它是功能接口() -> Unit的某些自定义实现,则可能不是,所以您应该检查一下并处理不存在的情况.

It will actually be Serializable if it is a function reference (SomeClass::someFunction) or a lambda. But it might not be, if it is some custom implementation of the functional interface () -> Unit, so you should check that and handle the cases when it's not.

这篇关于有没有办法在活动之间传递函数引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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