Is there a way to pass a function reference between activities?

后端 未结 5 473
后悔当初
后悔当初 2020-12-10 12:05

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 look

5条回答
  •  一整个雨季
    2020-12-10 12:36

    Maybe too late but:

    Have you tried to put the val callback inside the companion object? Solution may be something like:

    companion object {
        private lateinit var callback 
    
        fun newInstance(tryAgainFunction: () -> Unit): TimeOutHandlerFragment {
            val fragment = TimeOutHandlerFragment()
            this.callback = tryAgainFunction
            return fragment
        }
    }
    
    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        btnTryAgain.setOnClickListener { callback.invoke() }
    }
    

提交回复
热议问题