如何重写java/kotlin中另一个类示例的方法?

gpfsuwkq  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(312)

我有一个类,其中有一个片段示例,希望重写片段方法。我怎么能在这里做这种覆盖?

class MyClass(val fragment: Fragment) {
    init {
        fragment.onActivityCreated = onActivityCreated //what should be written?
    }

    fun onActivityCreated(savedInstanceState: Bundle?) {
        actions()
        super.onActivityCreated(savedInstanceState)
    }
}
hyrbngr7

hyrbngr71#

由于删除了答案,完成的机制如下所示:

class MyClass<T>(private val viewModelPayments: PaymentsViewModel, val fragment: T) where T : Fragment, T : Featured {

    init {
        fragment.doOnActivityCreated(::onActivityCreated)
        fragment.doOnActivityResult(::onActivityResult)
    }

    private fun onActivityCreated(savedInstanceState: Bundle?) {
        //...
    }

    private fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 
        //...
    }
}

interface Featured {
    fun doOnActivityCreated(action: (savedInstanceState: Bundle?) -> Unit)
    fun doOnActivityResult(action: (requestCode: Int, resultCode: Int, data: Intent?) -> Unit)
}

abstract class FeatureFragment : BaseFragment(), Featured {
    private var onActivityCreatedAction: ((savedInstanceState: Bundle?) -> Unit)? = null
    private var onActivityResultAction: ((requestCode: Int, resultCode: Int, data: Intent?) -> Unit)? = null

    override fun doOnActivityCreated(action: (savedInstanceState: Bundle?) -> Unit) {
        onActivityCreatedAction = action
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        onActivityCreatedAction?.invoke(savedInstanceState)
    }

    override fun doOnActivityResult(action: (requestCode: Int, resultCode: Int, data: Intent?) -> Unit) {
        onActivityResultAction = action
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        onActivityResultAction?.invoke(requestCode, resultCode, data)
    }
}

相关问题