How would you communicate between two Fragments?

Technology CommunityCategory: AndroidHow would you communicate between two Fragments?
VietMX Staff asked 3 years ago

All Fragment-to-Fragment communication is done either through a shared ViewModel or through the associated Activity. Two Fragments should never communicate directly.

The recommended way to communicate between fragments is to create a shared ViewModel object. Both fragments can access the ViewModel through their containing Activity. The Fragments can update data within the ViewModel and if the data is exposed using LiveData the new state will be pushed to the other fragment as long as it is observing the LiveData from the ViewModel.

public class SharedViewModel extends ViewModel {
 private final MutableLiveData < Item > selected = new MutableLiveData < Item > ();

 public void select(Item item) {
  selected.setValue(item);
 }

 public LiveData < Item > getSelected() {
  return selected;
 }
}


public class MasterFragment extends Fragment {
 private SharedViewModel model;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
  itemSelector.setOnClickListener(item -> {
   model.select(item);
  });
 }
}


public class DetailFragment extends Fragment {
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
  model.getSelected().observe(this, {
   item ->
   // Update the UI.
  });
 }
}

Another way is to define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value.