有没有办法在 Kotlin 和 Android 中 bundle 函数引用,以便可以从其他 fragment 调用函数? 例如,我的 fragment 工厂方法如下所示:
fun newInstance(tryAgainFunction: () -> Unit): TimeOutHandlerFragment {
val fragment = TimeOutHandlerFragment()
val bundle = Bundle()
return fragment
}
我希望能够将我的 tryAgainFunction 保存在包中以供进一步检索。
非常感谢!
编辑
最后,最合适的解决方案是使用热键的答案,然后在 onViewCreated 我用传递的函数初始化一个监听器。完整代码如下:
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()
}
}
感谢大家的帮助!
最佳答案
如果 tryAgainFunction
是 Serializable
,则 you can put it into the bundle
使用 bundle.putSerializable("try_again_function", tryAgainFunction);
.
如果它是函数引用 (SomeClass::someFunction
) 或 lambda,它实际上是 Serializable
。但它可能不是,如果它是功能接口(interface) () -> Unit
的一些自定义实现,所以你应该检查它并处理不是的情况。
关于android - 有没有办法在 Activity 之间传递函数引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45617564/