Search code examples
androidandroid-fragmentskotlinfragmentmanagerandroid-architecture-components

Get FragmentManager inside AndroidViewModel


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?


Solution

  • 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.