Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
0leg Avatar asked Jan 04 '23 21:01

0leg


1 Answers

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.

like image 155
azizbekian Avatar answered Jan 06 '23 10:01

azizbekian