WebView reloading when Fragment in ViewPager is retained form BackStack

前端 未结 3 1065
Happy的楠姐
Happy的楠姐 2020-12-15 06:04

Here is a code for a basic Fragment which contains a WebView.
WebFragment.java

public class WebFragment exte         


        
3条回答
  •  遥遥无期
    2020-12-15 06:19

    This is a classic case of falling victim to the easy patch-fix of overriding android:configChanges to solve a problem. Unfortunately there are multiple reasons why a config change will occur. So simply catching for a screen size change will miss a lot of them...as you have discovered.

    First, completely remove android:configChanges. Then add the following to your WebView fragment.

    protected void onSaveInstanceState(Bundle outState) {
      webView.saveState(outState);
    }
    

    Adjust your WebView fragment's onActivityCreated method to include the following:

    public void onActivityCreated(Bundle savedInstanceState) {
        webView = (WebView) getView().findViewById(R.id.helloWebview);
        initWebView();
    
        if (savedInstanceState != null)
            webView.restoreState(savedInstanceState);
        else
            webView.loadUrl(currentUrl);
    

    }

    That should get you going in the right direction. Note, calling a WebView's saveState() will not save display data. Eg, input tags will not perserve user input. You'll need to parse through the webpage manually to persist that data. Depending on what you are using the WebView for, this will be a major pain.

提交回复
热议问题