public class SharedViewModel extends ViewModel {
}
public class FragmentA extends Fragment {
private SharedViewModel model;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//pass the host Activity
model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
}
}
public class FragmentB extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//pass the host Activity
SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
}
}
1条答案
按热度按时间0x6upsns1#
按照文档进行操作,并记住使用相同的
ViewModelStoreOwner
,如下所示: