Android: Retain instance of WebView content on rotation

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.

public class CodePeekerActivity extends Activity {
private WebView m_webview = null;
// ...

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


Override Activity.onSaveInstanceState().

// Save the state of the web view when the screen is rotated.
protected void onSaveInstanceState(Bundle outState) {

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

public void onCreate(Bundle savedInstanceState) {

// Load layout
// ...

// Create WebView
m_webview = new WebView(this);

// Add WebView to Activity
// ...

// Reload the old WebView content
if (savedInstanceState != null) {
// Create the WebView
else {
// ... and any other configuration here

// ...

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!



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