如何将接口附加到片段,Kotlin,Android

如何将接口附加到片段,Kotlin,Android,android,kotlin,Android,Kotlin,我想连接接口,但我只知道一种方法: override fun onAttach(context: Context) { super.onAttach(context) try { myInterface=context as MyInterface }catch (e: Exception){ Log.d("myLog",e.message) } } 但是在这种情况下,接口

我想连接接口,但我只知道一种方法:

override fun onAttach(context: Context) {
        super.onAttach(context)

        try {
            myInterface=context as MyInterface
        }catch (e: Exception){
            Log.d("myLog",e.message)
        }
    }

但是在这种情况下,接口只能在主活动中使用。我需要在ViewModel中使用它。问题是:如何实现这一点?提前感谢。

如果您指的是活动中接口的实例,则可以在viewModel中放置setter方法。然后你可以自由使用它

在viewModel中:

class MyViewModel: ViewModel(){
    private var mInterface: MyInterface? = null 

    fun setInterface(myInt: MyInterface){
        mInterface = myInt
    }
}
在活动中:

override fun onCreate(...){
     viewModel.setInterface(this)
}

您是否计划在
onDestroy
null
输出该接口?但问题是,在主活动中,我无法获取对viewModel的引用,因为我使用视图模型工厂创建了它。viewModel的所有者是Activity,所以应该不会有问题。在活动中,您应该按viewModels{myViewModelFactory}执行val viewModel:MyViewModel