How to prevent fragment recovery when choosing from NavigationDrawer?

I have a simple activity in which he placed a navigation box. One of his input is a WebView, which loads a lot (it displays Gmail, so after all these nasty redirects, quite a lot is required).

I would like to keep the fragment, even if different options arise. I thought these solutions might work. They did not do this.

1) Do not restore fragment: even if mWebmailFragment is actually not null , onCreateView () is called in any case.

private Fragment mWebmailFragment /*, the others */; public void selectItem(int position) { Fragment fragment = null; switch (position) { case FRAGMENT_CODE_WEBMAIL: mWebmailFragment = mWebmailFragment!=null ? mWebmailFragment : new WebmailFragment(); fragment = mWebmailFragment; break; // ... } 

2) if onCreateView () is called, the state of the WebView object is saved. Well, this is not so: debugging I found that savedInstanceState is always null. I do not know why.

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); // Retain instance setRetainInstance(true); //.... // SavedState if (savedInstanceState != null) { mWebView.restoreState(savedInstanceState); } else { // do stuff } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mWebView.saveState(outState); } 
+6
source share
1 answer

I think you are not using hide / Show correctly. In a fragment transaction, use add () to load the fragment instead of replace ().

Change it

 final FragmentManager myFragmentManger = myContext .getSupportFragmentManager(); final FragmentTransaction myFragmentTransaction = myFragmentManger .beginTransaction(); myFragmentTransaction.replace(R.id.content, aFragment, aFragmentTag.getFragment()); 

to

 final FragmentManager myFragmentManger = myContext .getSupportFragmentManager(); final FragmentTransaction myFragmentTransaction = myFragmentManger .beginTransaction(); myFragmentTransaction.add(R.id.content, aFragment, aFragmentTag.getFragment()); 

If you use replace, createview () of the fragment will be called every time. Try using add () as the code above does.

0
source

Source: https://habr.com/ru/post/957176/


All Articles