[英]ViewModel + LiveData in Fragment, How to keep data of the ListItemFragment when navigate back from ItemDetailFragment
At the bottom in the onCreateView of ListItemFragment, i make a network call to get all items. 在ListItemFragment的onCreateView的底部,我进行网络调用以获取所有项目。 like this: 像这样:
viewmodel.getAllItems()
Then, observe the data to populate items to the RecyclerView. 然后,观察数据以将项目填充到RecyclerView。 I'm using Navigation Architecture Component to navigate to ItemDetailFragment when User click on each Item. 当用户单击每个项目时,我正在使用导航体系结构组件导航到ItemDetailFragment。 The problem is, when i hit back button, ListItemFragment's onCreateView call again, then viewmodel.getAllItems() also call again. 问题是,当我按下返回按钮时,ListItemFragment的onCreateView再次调用,然后viewmodel.getAllItems()也再次调用。 So, what i want is prevent call getAllItems() again, and keep current position of RecyclerView. 因此,我要防止再次调用getAllItems(),并保持RecyclerView的当前位置。
YourItemType yourItems; //define this as global field
In onCreateView; 在onCreateView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle
if(yourItems == null){
yourItems = viewmodel.getAllItems();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.