ViewModelProviders is deprecated in 1.1.0

后端 未结 22 1415
说谎
说谎 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:17

    Yes @Tarek, it is deprecated. Use now with AndroidX:

    val yourViewModel = ViewModelProvider.NewInstanceFactory().create(YourVideoModel::class.java)
    
    0 讨论(0)
  • 2020-12-07 10:17

    Use ViewModelProvider directly instead of user ViewModelProviders.of() as mentioned in the docs.

    ViewModelProvider(this).get(XViewModel::class.java)
    

    https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders

    0 讨论(0)
  • 2020-12-07 10:17

    I'm no expert but i have a line of code that solved my problem in Java. Hope this helps someone.

    viewModel = 
    new ViewModelProvider
    .AndroidViewModelFactory(getApplication())
    .create(ViewModel.class);
    

    As i said i would love to provide more details, but this fixed this problem for me.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题