ViewModelProviders is deprecated in 1.1.0

后端 未结 22 1473
说谎
说谎 2020-12-07 09:14

Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:

val model = ViewModelProviders         


        
22条回答
  •  生来不讨喜
    2020-12-07 10:18

    I'm using android X and also had this issue.

    First of all, you should add these dependencies to your Gradle:

    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" 
    

    In my case, the $lifecycle_version was 2.2.0-rc02

    Second: The import for the ViewModelProvider should be:

    import androidx.lifecycle.ViewModelProvider
    

    Than you can initial your vIewModel like the examples below:

    val viewModel = ViewModelProvider(this, YourFactoryInstace).get(MainViewModel::class.java)
    
    val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
    

提交回复
热议问题