0 votes
in Android by
How would you communicate between two Fragments?

1 Answer

0 votes
by

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.

Related questions

0 votes
0 votes
asked Mar 28, 2023 in Android by Robin
0 votes
asked Aug 31, 2023 in Android by Robindeniel
...