Android: Retain instance of WebView content on rotation

0 Comments

Unlike fragments, the WebView doesn't retain it's own instance very easily. Nothing more annoying than a web page reloading itself when you rotate the screen...

The way I managed this before in CodePeeker was to save the whole HTML string into memory and set it whenever the screen was rotated. This was slow, horribly inefficient with memory and just plain embarassing.

There have been numerous attempts at fixing it on StackOverflow, but the solution found by Andrea Bresolin seems to be the magic bullet that fixes it. His trick with keeping the WebView out of the layout XML was the missing voodoo ingredient I needed for the fix.

I managed to simplify his solution down a little further and update it for the newer API levels.

First of all, you'll need to extract your WebView out from the layout XML and move it into the code. For this to work, this control has to be created dynamically.

1.public class CodePeekerActivity extends Activity {
2.  private WebView m_webview = null;
3.  // ...
4.}

Secondly, ensure that your app manages the configuration changes upon rotation. In AndroidManifest.xml, add configChanges to your Activity declaration.

1.<activity
2.  android:name=".CodePeekerActivity"
3.  ...
4.  android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
5.  >

Override Activity.onSaveInstanceState().

1.// Save the state of the web view when the screen is rotated.
2.@Override
3.protected void onSaveInstanceState(Bundle outState) {
4.  super.onSaveInstanceState(outState);
5.  m_webview.saveState(outState);
6.}

Lastly, take control of your Activity's onCreate().

01.@Override
02.public void onCreate(Bundle savedInstanceState) {
03.  super.onCreate(savedInstanceState);
04. 
05.  // Load layout
06.  // ...
07. 
08.  // Create WebView
09.  m_webview = new WebView(this);
10. 
11.  // Add WebView to Activity
12.  // ...
13. 
14.  // Reload the old WebView content
15.  if (savedInstanceState != null) {
16.    m_webview.restoreState(savedInstanceState);
17.  }
18.  // Create the WebView
19.  else {
20.    m_webview.getSettings().setJavaScriptEnabled(true);
21.    m_webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
22.    m_webview.getSettings().setBuiltInZoomControls(true);
23.    // ... and any other configuration here
24.  }
25. 
26.  // ...
27.}

Just be sure that you're only restoring when the savedInstanceState data exists.

If you set any options before calling WebView.restoreState(), then the call to restore won't work!

Once that's all in place, you can rotate until your heart's content!

6K6YS 
Rotate I say! ROTAAAAAAAAAAATE!

Sources

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog