Efficient communication between fragments in Android is essential for building responsive and maintainable apps. Here are some advanced tips for achieving this:
-
Use a Shared ViewModel:
-
Description: Leverage the
ViewModelandLiveDataarchitecture components to share data between fragments. It ensures that both fragments observe the same data and react to changes simultaneously. -
Implementation:
public class SharedViewModel extends ViewModel { private final MutableLiveData<String> selected = new MutableLiveData<String>(); public void select(String item) { selected.setValue(item); } public LiveData<String> getSelected() { return selected; } }Within your fragments, you can then observe changes:
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class); model.getSelected().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(@Nullable final String item) { // Update the UI. } });
-
-
Fragment Result API:
- Description: Use the Fragment Result API, which provides a clean solution to send data from child to parent fragments.
- Implementation:
// In child fragment Bundle result = new Bundle(); result.putString("bundleKey", "result"); getParentFragmentManager().setFragmentResult("requestKey", result); // In parent fragment getChildFragmentManager().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 } });


