androidandroid-fragmentsandroid-recyclerviewlisteners

Adding a listener between two fragments


I have two fragments, A and B let's say, where B contains a list. I would like to add a listener on Fragment B that notifies Fragment A of the chosen list item. I couldn't figure out how to initialize the listener in Fragment B since it is bad practice to pass arguments in fragment's constructors.

NOTE: Fragment B is contained inside Fragment A. i.e. I have a FrameLayout in Fragment A; and Fragment B covers that FrameLayout.

Any idea how I could do that?


Solution

  • If you're saying that Fragment B is a child fragment of Fragment A (that is, you've added it to Fragment A using Fragment A's getChildFragmentManager()), then you can use the same approach that you use for Activity interfaces, but using getParentFragment() instead of getActivity().

    For example:

    Fragment B:

    @Override
    public void onAttach(Context context) {
        MyInterface myInterface = (MyInterface) getParentFragment();
    }
    

    Assuming that Fragment A implements MyInterface.

    One convenience method we've used to avoid having to know whether a Fragment is hosted by another Fragment or an Activity is something like:

    public static <T> getInterface(Class<T> interfaceClass, Fragment thisFragment) {
        final Fragment parent = thisFragment.getParentFragment();
        if (parent != null && interfaceClass.isAssignableFrom(parent)) {
            return interfaceClass.cast(parent);
        }
    
        final Activity activity = thisFragment.getActivity();
        if (activity != null && interfaceClass.isAssignableFrom(activity)) {
            return interfaceClass.cast(activity);
        }
    
        return null;
    }
    

    Then you can just use:

    MyInterface myInterface = getInterface(MyInterface.class, this);
    

    and it doesn't matter whether Fragment B is hosted as a child Fragment or in an Activity directly.