FragmentManager from Context

后端 未结 5 1178
旧时难觅i
旧时难觅i 2020-12-15 03:09

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

相关标签:
5条回答
  • 2020-12-15 03:35

    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)

    0 讨论(0)
  • 2020-12-15 03:38

    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");
    }
    
    0 讨论(0)
  • 2020-12-15 03:38

    Since your context object can't always be directly casted to Activity, this is a more reliable way to do this:

    @Nullable
    public static Activity getActivityFromContext(@NonNull Context context){
        while (context instanceof ContextWrapper) {
            if (context instanceof Activity) return (Activity) context;
            context = ((ContextWrapper)context).getBaseContext();
        }
        return null; //we failed miserably 
    }
    
    0 讨论(0)
  • 2020-12-15 03:40

    You can get access to a FragmentManager (or SupportFragmentManager) in an Application - but as other answers suggests, you can only do this via an Activity instance.

    However, you can gain access to a FragmentManager via an Activity without needing to directly call any Activities using the ActivityLifecycleCallbacks interface:

    registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks {
    
        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
            activity.getFragmentManager()
            if(activity instanceof FragmentActivity) {
                ((FragmentActivity)activity).getSupportFragmentManager();
            }
            unregisterActivityLifecycleCallbacks(this);
        }
    
        ...
    
    0 讨论(0)
  • 2020-12-15 03:54

    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.

    0 讨论(0)
提交回复
热议问题