How would you communicate between two Fragments?

Report
Question
752 views

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

Please explain why do you think this question should be reported?

Report Cancel
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.
  });
 }
}

Thread Reply

Leave an comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>