Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get ViewModel scoped to this Fragment (fragment-ktx)
//my sample
//https://github.com/alexshr/android-kotlin-fundamentals-apps/tree/master/MarsRealEstateFinal
//doc
//https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels
version_fragment = '1.2.0-alpha01'
implementation "androidx.fragment:fragment-ktx:${version_fragment}"
--------------------------------------------------------------------------------------
// Get a reference to the ViewModel scoped to this Fragment (fragment-ktx)
val viewModel by viewModels<DetailViewModel> {DetailViewModelFactory(marsProperty, application)}
//default provider (viewmodel without args)
val viewModel by viewModels<OverviewViewModel>()
----------------------------------------------------------------------------------------------
class DetailViewModelFactory(
private val marsProperty: MarsProperty,
private val application: Application) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DetailViewModel::class.java)) {
return DetailViewModel(marsProperty, application) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment