【发布时间】:2019-11-27 10:00:59
【问题描述】:
我最近在我的一个项目上切换到 Android MVVM,我面临的问题是,我的 Fragments 与 ViewPager 和 TabLayout 一起使用,每个选项卡的数据必须根据每个选项卡的 id 不同,但是因为我我正在使用 AndroidViewModel 连接到我的数据源,相同的数据显示在我的所有选项卡片段中。我知道问题是所有动态片段之间共享相同的 ViewModel [Fragmnet 类相同]。 有没有办法解决?或者我做错了什么。
//返回数据的代码
private MutableLiveData<List<InventoryProduct>> inventoryProductList;
//we will call this method to get the data
public LiveData<List<InventoryProduct>> getCategoriesList(String cat_id,String store_id) {
//if the list is null
if (inventoryProductList == null) {
inventoryProductList = new MutableLiveData<>();
//we will load it asynchronously from server in this method
loadInventoryProducts(cat_id,store_id);
}
//finally we will return the list
return inventoryProductList;
}
【问题讨论】:
-
请给我们看代码
-
对每个片段使用不同的视图模型
-
Fragment 类与基于参数创建的多个[动态] 实例相同。
标签: android android-fragments mvvm viewmodel android-viewmodel