How to get an Instance of ViewModel in activity in 2020/21?

后端 未结 9 1674
野的像风
野的像风 2021-02-13 04:27

I am new to the mvvm pattern. I created a ViewModel for the main activity. Now I want to get an instance of the ViewModel in the main activity.

Most Tutorials and answe

9条回答
  •  我在风中等你
    2021-02-13 05:02

    Using Fragment-ktx libr in your app you can get viewModel as below

    First Update Gradle File as app -> build.gradle

    implementation 'androidx.fragment:fragment-ktx:1.1.0'
    

    // get ViewModel in Activity or Fragment as

    private val viewModel: MainActivityViewModel by viewModels()
    

    // If you want to get same instance of ViewModel in ChildFragment as

     private val viewModel: MainActivityViewModel by viewModels(
        ownerProducer = { requireParentFragment() }
    )
    

提交回复
热议问题