ViewModelProviders is deprecated in 1.1.0

后端 未结 22 1417
说谎
说谎 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 09:58

    ViewModelProviders.of() has been deprecated.

    Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.

     mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
    
    0 讨论(0)
  • 2020-12-07 09:58

    In case you watch a video from Udacity where you create a GameViewModel and you do not want to write deprecated code just replace:

    viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)
    

    with the following code:

    viewModel = ViewModelProvider(this).get(GameViewModel::class.java)
      
    

    and return back to reading ASAP!!

    0 讨论(0)
  • 2020-12-07 09:59

    I use lifecycle-extensions 2.2.0 version:

    implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" 
    

    It should be work, using ViewModelProvider constructor.

    // With ViewModelFactory   
    val viewModel = ViewModelProvider(this, YourViewModelFactory).get(YourViewModel::class.java)
    
    
    //Without ViewModelFactory
    val viewModel = ViewModelProvider(this).get(YourViewModel::class.java)
    

    2020/5/15 Update

    I find another elegant way to achieve, Android KTX can help

    implementation "androidx.fragment:fragment-ktx:1.2.4"
    val viewmodel: MYViewModel by viewModels()
    val viewmodel: MYViewModel by viewModels { myFactory } //With factory
    

    Ref: https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels

    2020/06/25: corrected the case of the delegate

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

    it should work this way

     viewModel = ViewModelProviders.of(this@MainActivity).get(MainActivityViewModel::class.java)
    
    0 讨论(0)
  • 2020-12-07 10:03

    If you use Kotlin, you can use the property delegate viewModels() like this:

    val viewModel: YourViewModel by viewModels()
    

    Source: https://forums.bignerdranch.com/t/solution-to-deprecated-method-viewmodelproviders-of/16833

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

    Use this:

    YourViewModel yourViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);
    
    0 讨论(0)
提交回复
热议问题