简体   繁体   中英

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. 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").

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.

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.

Thanks

OnCreateView for a fragment runs on the creation of the view every time it needs to be drawn. By going back you are causing the view to be recreated and hence the webservices are loading again.

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.

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 )

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()
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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