To pass data back to fragment A from fragment B, first set a result listener on fragment A, the fragment that receives the result. Call setFragmentResultListener() on fragment A's FragmentManager, as shown in the following example:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getParentFragmentManager().setFragmentResultListener("requestKey", this, new FragmentResultListener() {
@Override
public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
// We use a String here, but any type that can be put in a Bundle is supported.
String result = bundle.getString("bundleKey");
// Do something with the result.
}
});
}
In fragment B, the fragment producing the result, set the result on the same FragmentManager by using the same requestKey. You can do so by using the setFragmentResult() API:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle result = new Bundle();
result.putString("bundleKey", "result");
getParentFragmentManager().setFragmentResult("requestKey", result);
}
});
Fragment A then receives the result and executes the listener callback once the fragment is STARTED.
You can have only a single listener and result for a given key. If you call setFragmentResult() more than once for the same key, and if the listener is not STARTED, the system replaces any pending results with your updated result.
If you set a result without a corresponding listener to receive it, the result is stored in the FragmentManager until you set a listener with the same key. Once a listener receives a result and fires the onFragmentResult() callback, the result is cleared. This behavior has two major implications:
Fragments on the back stack do not receive results until they have been popped and are STARTED.
If a fragment listening for a result is STARTED when the result is set, the listener's callback then fires immediately.
Note: Because the fragment results are stored at the FragmentManager level, your fragment must be attached to call setFragmentResultListener() or setFragmentResult() with the parent FragmentManager.