Android导航组件和Viewmodel之间的交互将如何进行?

时间:2018-06-20 03:49:28

标签: android-viewmodel android-architecture-navigation

Android Viewmodel可以具有活动或片段的作用域/寿命,但是这在导航组件中如何工作?

考虑是否有以下情况:

MainActivity 
 - Contains the NavHostFragment

CustomerListFragment 
 - Starting point for the navigation
 - On click of any customer in the list, will navigate the CustomerDetailsFragment

CustomerDetailsFragment
 - Contains a tab with 3 fragments: CustomerDetailFragment, CustomerContactFragment and CustomerOrderHistoryFragment

CustomerDetailFragment
 - Display customer general information such as name, age, gender, etc...
 - Get data from CustomerViewModel

CustomerContactFragment
 - Display customer address, tel, fax, etc
 - Get data from CustomerViewModel

CustomerOrderHistoryFragment
 - Display customer's order history
 - Get data from OrderHistoryViewModel

在上述情况下,是否可以为CustomerDetailFragment和CustomerContactFragment共享相同的CustomerViewModel实例?

如果我不使用导航组件,则可以将CustomerDetailsFragment设为一个活动,然后将我的视图模型初始化为该活动,但是由于在Navigation中我们只有片段,我该如何最好地实现这一目的?

我虽然:


public class CustomerDetailsFragment extends Fragment {
...
CustomerViewModel model = ViewModelProviders.of(this).get(CustomerViewModel .class);
...

但是如何将viewmodel的这个实例传递给CustomerDetailFragment和CustomerContactFragment?

还是有更好的方法来构造上面的代码以达到相同的结果?

2 个答案:

答案 0 :(得分:2)

您可以将parentFragment用作商店所有者。在您的DetailContact片段中调用它。

CustomerViewModel model = ViewModelProviders.of(getParentFragment()).get(CustomerViewModel.class);

答案 1 :(得分:1)

ViewModel很好地支持了您的方案。

您只需要获取活动范围为ViewModelProviders.of(getActivity).get(...的ViewModel

更多信息在这里: https://developer.android.com/topic/libraries/architecture/viewmodel#sharing