FragmentManager from Context

Solution 1:

Only if the given Context extends Activity (Post-Honeycomb) or FragmentActivity (pre-honeycomb).

In which case you'd have to make 100% sure it's an activity using reflection or try-catch.

try{
  final Activity activity = (Activity) context;

  // Return the fragment manager
  return activity.getFragmentManager();

  // If using the Support lib.
  // return activity.getSupportFragmentManager(); 

} catch (ClassCastException e) {
  Log.d(TAG, "Can't get the fragment manager with this");
}

Thought I recommend refactoring so a View is really just meant for showing stuff and shouldn't actually modify the state of your app, but that's my opinion.

Solution 2:

if you are using support fragments, you probably actually want:

try {
  FragmentManager fragmentManager = ((FragmentActivity) context).getSupportFragmentManager();
} catch (ClassCastException e) {
  Log.e(TAG, "Can't get fragment manager");
}

Solution 3:

This is what worked for me:

Context mContext;
...


//Get FragmentManager
FragmentManager fragmentManager = ((Activity) mContext).getFragmentManager();

(Of course you have to first of all initialize mContext)