How would you communicate between two Fragments?
ReportQuestion
3 years ago 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.
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