AndroidViewModel
is used to access Application
context. I'm trying to access Activity
's FragmentManager
without passing it explicitly:
class FooViewModel(app: Application) : AndroidViewModel(app) {
private val fm = (app.applicationContext as Activity).fragmentManager
..
}
Getting error, unable to cast Context
to Activity
.
Question: is there any way to get FragmentManager
inside AndroidViewModel
without passing it explicitly?
I think short answer will be "no, there is no way", because Application
context is in no aware of FragmentManager
.
FragmentManager
is an object that subclasses of FragmentActivity
may have. Application
is not a subclass of FragmentActivity
.
Another question would be, why would you ever need a FragmentManager
instance inside your ViewModel
? Most possibly you should delegate view-related stuff to handle to other unit other than ViewModel
(e.g. Activity
, Fragment
). Keep in mind, that this ViewModel
would be retained over configuration change, thus if you keep a reference to the FragmentManager
inside your ViewModel
, you'd be leaking your Activity
instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With