Updated answer:
Things changed a little bit, as the previously needed dependency - ViewModelProviders
- got deprecated (see the old answer for details). You can now use the ViewModelProvider
constructor directly.
So, in this case, the answer would be:
private val viewModel = ViewModelProvider(this).get(SheduleViewModel::class.java)
Note that, however, if you include the androidx.activity:activity-ktx:$Version
dependency (a few of the commonly used AndroidX dependencies already include it for you), you can make use of property delegation:
private val viewModel: SheduleViewModel by viewModels()
Which internally will use ViewModelProvider
and scope your ViewModel
to your Activity
. It's just a more concise way of writing the same thing. You can do the same for a Fragment
by including the androidx.fragment:fragment-ktx:$Version
dependency instead (again, commonly already included by other AndroidX dependencies).
Both the ViewModelProvider
constructor and by viewModels()
also accept a factory as a parameter (useful for injecting your ViewModel
):
private val viewModel =
ViewModelProvider(this, viewModelFactory).get(SheduleViewModel::class.java)
and
private val viewModel: SheduleViewModel by viewModels { viewModelFactory }
Use the one that best suits you.
Old answer:
Add the androidx.lifecycle:lifecycle-extensions:$lifecycleExtensionsVersion
dependency in order to import ViewModelProviders
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…