简体   繁体   English

单击另一个片段的Backpressed后返回时恢复片段状态

[英]Restoring a Fragment State when returned after clicking Backpressed of another fragment

Here is my problem area: 这是我的问题所在:

I have a Fragment A. Once it is attached, in its onCreateView, I load a webservice to fetch the data from the server and after that I set that data on the list view using a Base Adapter. 我有一个片段A。将其附加到其onCreateView中后,我将加载一个Web服务以从服务器获取数据,然后使用基本适配器在列表视图中设置该数据。 Now on the Item Clicks of the list view I replace the Fragment A with Fragment B using replace Methods of the Fragment Transactions and addtoBackstack("FragmentA"). 现在,在列表视图的“项目单击”上,我使用片段事务的替换方法和addtoBackstack(“ FragmentA”)将片段A替换为片段B。

FragmentManager fm =getActivity().getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, Fragment B).commit();

Now here when I press back button on Fragment B, it takes me to Fragment A but the webservice again starts loading. 现在在这里,当我按片段B上的后退按钮时,它将带我到片段A,但Web服务再次开始加载。

My Problem: I just want that when it returns to Fragment A, it should show its previous state and should not call the webservices again. 我的问题:我只是希望当它返回到片段A时,它应该显示其先前的状态,并且不应再次调用Web服务。

Thanks 谢谢

OnCreateView for a fragment runs on the creation of the view every time it needs to be drawn. 片段的OnCreateView每次需要绘制视图时都会运行。 By going back you are causing the view to be recreated and hence the webservices are loading again. 通过回退,您将导致重新创建视图,因此Web服务将再次加载。

I believe that if you only want the web services to load once then you could move the code to the "onCreate" method instead, but its probably a better idea to move this code to "onResume" instead and include some logic that checks whether you need to load your webservices again or not. 我相信,如果您只希望Web服务加载一次,则可以将代码移至“ onCreate”方法,但是将代码移至“ onResume”并包含一些检查您是否在运行的逻辑可能是一个更好的主意。是否需要再次加载您的Web服务。

This way everytime the fragment is paused and then loaded again you could ensure that the fragment still has everything it needs. 这样,每次暂停片段然后再次加载时,您都可以确保片段仍然具有所需的一切。

片段生命周期
(source: xamarin.com ) (来源: xamarin.com

EDIT: 编辑:

So for example you could have 例如,您可能有

 @Override
 public void onResume() {
 super.onResume();  // Always call the superclass method first


 if (data == null) { //Or list is empty?
    getWebData()
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM