恢复WebView的状态

时间:2014-04-29 08:44:40

标签: android webview

我有用于显示来自Disqus服务的coments的webview。这是片段代码的一部分:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_coments, container, false);

        mComentsView = (WebView)root.findViewById(R.id.coments_view);

        String htmlComments = getHtmlComment(createId(), "androidaci");

        mComentsView.getSettings().setJavaScriptEnabled(true);
        mComentsView.setWebViewClient(new ComentsWebViewer(htmlComments));
        mComentsView.setWebChromeClient(new WebChromeClient());
        if(savedInstanceState != null){
            Log.e("restoring", "state");
            mComentsView.restoreState(savedInstanceState);
        } else {
            Log.e("loading", "website");
            mComentsView.loadData(htmlComments, "text/html", null);
        }
        return root;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mComentsView.saveState(outState);
    }


    public String getHtmlComment(String idPost, String shortName) {

        return "<div id='disqus_thread'></div>"
                + "<script type='text/javascript'>"
                + "var disqus_identifier = '"
                + idPost
                + "';"
                + "var disqus_shortname = '"
                + shortName
                + "';"
                + " (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;"
                + "dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';"
                + "(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();"
                + "</script>";
    }

问题在于旋转webview重新加载,我想知道原因。我尝试保存和恢复状态,并在日志中我得恢复状态语句,但看起来它仍在重新加载轮换更改。我怎样才能阻止这种重装?

2 个答案:

答案 0 :(得分:0)

使用此代码。

  @Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the WebView state (including history stack)
    mWebView.saveState(savedInstanceState);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

答案 1 :(得分:0)

到您在AndroidManifest.xml的活动

android:configChanges="keyboard|keyboardHidden|screenSize|orientation" 

以及您的Java代码

// survive screen orientation change
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

适合我:)