Search code examples
androidandroid-fragmentsandroid-annotations

Call getChildFragmentManager inside EBean class using AndroidAnnotation


I want to create a @EBean class with all functions related to show and hide ProgressDialog and DialogFragment. Ex: I need to show the ErrorDialogFragment inside a Fragment, so getChildFragmentManager() is needed in this below code:

ErrorDialogFragment.showDefaultDialog(getChildFragmentManager(),
                    "Device is disconected!");

Is there a way to call getChildFragmentManager() inside the @EBean class?


Solution

  • @EBean
    public class YourBean {
    
      @RootContext
      FragmentActivity activity;
    
      public void showDialog() {
        activity.getSupportFragmentManager(). ...
      }
    }
    

    However make sure you only inject this bean to a FragmentActivity, because otherwise the Activity itself will not be injected into the bean.

    Edit: You cannot inject the FragmentManager nor the Fragment to the bean with annotations. You have to create a setter method for that:

    @EBean
    public class YourBean {
    
      private FragmentManager fragmentManager;
    
      public void showDialog() {
        ErrorDialogFragment.showDefaultDialog(fragmentManager,
                    "Device is disconected!");
      }
    
      public void setFragmentManager(FragmentManager fragmentManager) {
        this.fragmentManager = fragmentManager;
      }
    }
    

    In your Fragment:

    @AfterInject
    void afterInject() {
      yourBean.setFragmentManager(getChildFragmentManager());
    }