ViewModelProviders is deprecated in 1.1.0

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

提交回复
热议问题