0

I have two Fragments Fragment1 and Fragment2,In Fragment1 I use findNavController().navigate() launch the Fragment2,When Fragment2 finished,How to pass the data to Fragment1?(Translate by Google)

1

1 Answer 1

0

You can use getParentFragment() in Fragment2 to transfer data to Fragment1. This only works if you create Fragment2 via getChildFragmentManager() of Fragment1.

If you use getSupportFragmentManager() of Activity then you have to create a listener.

class Fragment2 {
    private UpdateFragment1Listener updateFragment1Listener;

    void sendDataToFragment1() {
        updateFragment1Listener.updateFragment(myData);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof UpdateFragment1Listener ) {
            updateFragment1Listener = (UpdateFragment1Listener ) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement UpdateFragment1Listener ");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        updateFragment1Listener = null;
    }

    interface UpdateFragment1Listener {
        void updateFragment1(MyData myData);
    }
}

class MyActivity implements Fragment2.UpdateFragment1Listener {
    private Fragment1 fragment1;

    @Override
    void updateFragment1(MyData myData) {
        fragment1.update(myData);
    }
}
2
  • I want an official solution, not an interface. Thank you all the same. Now I used EventBus to solve this problem.
    – Saxxhw
    Jul 2, 2019 at 1:22
  • I don't know how official you want it to be but the interface solution literally comes from Android Studio itself. But yeah EventBus should work. Jul 2, 2019 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.