I have a ViewModel named SharedViewModel:
public class SharedViewModel<T> extends ViewModel {
private final MutableLiveData<T> selected = new MutableLiveData<>();
public void select(T item) {
selected.setValue(item);
}
public LiveData<T> getSelected() {
return selected;
}
}
I've implemented it based on SharedViewModel example on the Google's Arch ViewModel reference page:
It is very common that two or more fragments in an activity need to communicate with each other. This is never trivial as both fragments need to define some interface description and the owner activity must bind the two together. Moreover, both fragments must handle the case where the other fragment is not yet created or not visible.
I have two fragments, called ListFragment
and DetailFragment
.
Until now I used these two fragments inside an activity called MasterActivity
, and everything worked well.
I got the ViewModel in ListFragment
, selected the value to use it on DetailFragment
.
mStepSelectorViewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
However, now, in certain cases, I need that ListFragment
(a layout to a different device configuration) will be added to a different activity, called DetailActivity
. Is there a way to do that similarly to the above example?