Skip to content

Instantly share code, notes, and snippets.

@polson
Last active May 27, 2019 06:15
Show Gist options
  • Save polson/57ed47d7446c4674cb75a13bc443b6f1 to your computer and use it in GitHub Desktop.
Save polson/57ed47d7446c4674cb75a13bc443b6f1 to your computer and use it in GitHub Desktop.
Gist demonstrating how to get an ViewModel from your custom view
class MyView(context: Context) : FrameLayout(context) {
private val viewModel by lazy { setupViewModel() }
private val activity by lazy { scanForActivity(context) }
private fun scanForActivity(context: Context?): FragmentActivity = when (context) {
is FragmentActivity -> context
is ContextWrapper -> scanForActivity(context.baseContext)
else -> throw IllegalArgumentException("Context must be a FragmentActivity!")
}
private fun setupViewModel() = createViewModel(id.toString()) {
MyViewModel()
}
@Suppress("UNCHECKED_CAST")
private inline fun <reified T : ViewModel> createViewModel(key: String, crossinline initializer: () -> T): T {
val factory = object : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T = initializer() as T
}
return ViewModelProviders.of(activity, factory).get(key, T::class.java)
}
class MyViewModel : ViewModel() {
//TODO
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment