How to access FragmentManger from context from a class that does not extend FragmentActivity

13,113

Solution 1

If the Context you have is from the FragmentActivity, you can just cast it to FragmentActivity, though I don't know for sure if that's your case.

That said, it sounds like what you're doing is bad practice. I would keep all Fragment transactions within the FragmentActivity class. If another class needs to request a different Fragment shown, you should use callbacks or something similar.

Solution 2

Just answered this in another thread, but this may help others. I was in a situation perhaps similar to yours with no precise answers for how to work around having an Adapter class separate from the FragmentActivity class, while needing to access the getSupportFragmentManager() within the Adapter.

Passing the context didn't work because it doesn't allowing casting of the FragmentActivity (for reasons I still don't understand).

But I gave up and just saved access to the manager itself and call it directly:

public ViewPagerAdapter(Context context, FragmentManager fm, Fragment f) {
    super(fm);  
    _fm = fm; // declared in the class "private FragmentManager _fm;"
    _context=context;       
}
Share:
13,113
user1276092
Author by

user1276092

Updated on June 04, 2022

Comments

  • user1276092
    user1276092 almost 2 years

    I am developing an android application in which I need to launch an Fragment from the class which doesnot extend FragmentActivity . I am using support v4 package. I will having the context in my current class. Can any one help me how to create FragmentManager object from current context?

    public ToolBarGenerator(Context c)
    {
          context = c;
    }
    
    FragmentManager fm = (FragmentActivity)context.getSupportFragmentManager(); //getting error at this line.
    //Called like the above
    new ToolBarGenerator(getActivity())
    
  • user1276092
    user1276092 almost 12 years
    public ToolBarGenerator(Context c){context =c;} //MyClass FragmentManager fm = (FragmentActivity)context.getSupportFragmentManager(); <br> I did like the above but I am getting error
  • Jason Robinson
    Jason Robinson almost 12 years
    Change the parameter from Context to FragmentActivity and pass that in as a parameter instead.
  • Admin
    Admin almost 9 years
    With context cannot be cast to android.support.v4.app.FragmentActivity