Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentManager from Context

Tags:

android

I created a new View class. Within that class I need to get access to the FragmentManager, but I cannot figure out how.

Can I access the FragmentManager from a context?

CustomView extends LinearLayout 
like image 919
Steve Avatar asked May 21 '12 17:05

Steve


People also ask

What is the difference between FragmentManager and Supportfragmentmanager?

FragmentManager is class provided by the framework which is used to create transactions for adding, removing or replacing fragments. getSupportFragmentManager is associated with Activity consider it as a FragmentManager for your Activity .

What is a FragmentManager?

FragmentManager is the class responsible for performing actions on your app's fragments, such as adding, removing, or replacing them, and adding them to the back stack.


1 Answers

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.

like image 98
DeeV Avatar answered Sep 19 '22 13:09

DeeV