سؤال

I have webview for displaying coments from Disqus service. Here is the part of the fragment code :

@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>";
    }

Problem is on rotation the webview reloads and I would like to know why. I try to save and restore state and in log i get to restoring state statement, but it looks like it is still reloading on rotation change. How can I prevent this reloading ?

هل كانت مفيدة؟

المحلول

Use this code.

  @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);
}

نصائح أخرى

To your activity at AndroidManifest.xml

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

And to your Java code

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

Works for me :)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top