Yakhyo Mashrapov
Yakhyo Mashrapov

Reputation: 390

How to attach interface to a fragment, Kotlin, Android

I want to attach the interface, but I only know one way to do it:

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

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

But in this case, the interface can only be used in the Main Activity. And I need to use it in the ViewModel. Question is: How can this be implemented? Thank you in advance.

Upvotes: 1

Views: 713

Answers (1)

Khamidjon Khamidov
Khamidjon Khamidov

Reputation: 8859

if you mean the instance of the interface in the Activity, you can put a setter method inside viewModel. Then you can use it freely.

In the viewModel:

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

    fun setInterface(myInt: MyInterface){
        mInterface = myInt
    }
}

in activity:

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

Upvotes: 1

Related Questions