Preserving the state of an Android WebView on screen orientation change

Source code

If you’ve tried to use a WebView inside your app, you know that the standard behavior on screen orientation change is not satisfactory in most cases because the full state of the WebView is not preserved. Here I’m going to show you a possible implementation to keep the full state of the WebView every time you rotate the screen. This is the same implementation I used in my own app (FWebLauncher) for the internal web browser.

Standard implementation (the state is not completely preserved)

Let’s start by taking a look at what a standard implementation would look like. This is how you would usually implement the state saving for a WebView according to the Android documentation:

public class StandardImplActivity extends Activity
{
	protected WebView webView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.standard_impl);

		// Retrieve UI elements
		webView = ((WebView)findViewById(R.id.webView));
		
		// Initialize the WebView
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		webView.setScrollbarFadingEnabled(true);
		webView.getSettings().setLoadsImagesAutomatically(true);

		// Load the URLs inside the WebView, not in the external web browser
		webView.setWebViewClient(new WebViewClient());

		if (savedInstanceState == null)
		{
			// Load a page
			webView.loadUrl("http://www.google.com");
		}
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);

		// Save the state of the WebView
		webView.saveState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);

		// Restore the state of the WebView
		webView.restoreState(savedInstanceState);
	}
}

So we call the saveState and the restoreState methods in the onSaveInstanceState and the onRestoreInstanceState methods of the Activity.

The WebView is declared directly in the layout file for the activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	
	<WebView android:id="@+id/webView"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"/>
	
</LinearLayout>

The main problem with this implementation is that, whenever you rotate the screen, the WebView is created again because the activity is destroyed and its saveState method doesn’t save the full state, but only a part of it like the URL of the page that was loaded and the browsing history. So it happens that for example the zoom and the scroll position are not preserved after the screen orientation change and sometimes the page is reloaded from the web.

State preserving implementation (a possible solution)

I tried many different solutions to preserve the full state of the WebView on screen rotation and the following one proved to be a reliable one that solves our problem. The main point is that the activity must not be destroyed and we must handle the screen orientation change by ourselves. Let’s start by taking a look at the layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	
	<FrameLayout android:id="@+id/webViewPlaceholder"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"/>
	
</LinearLayout>

You immediately notice the difference with the standard implementation. Here we don’t declare the WebView inside the layout file, but we declare a placeholder instead. It is the position where our WebView will be placed inside the activity.

Also the code inside the activity will be different of course and here it is:

public class StatePreservingImplActivity extends Activity
{
	protected FrameLayout webViewPlaceholder;
	protected WebView webView;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.state_preserving_impl);
		
		// Initialize the UI
		initUI();
	}
	
	protected void initUI()
	{
		// Retrieve UI elements
		webViewPlaceholder = ((FrameLayout)findViewById(R.id.webViewPlaceholder));

		// Initialize the WebView if necessary
		if (webView == null)
		{
			// Create the webview
			webView = new WebView(this);
			webView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			webView.getSettings().setSupportZoom(true);
			webView.getSettings().setBuiltInZoomControls(true);
			webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
			webView.setScrollbarFadingEnabled(true);
			webView.getSettings().setLoadsImagesAutomatically(true);

			// Load the URLs inside the WebView, not in the external web browser
			webView.setWebViewClient(new WebViewClient());

			// Load a page
			webView.loadUrl("http://www.google.com");
		}

		// Attach the WebView to its placeholder
		webViewPlaceholder.addView(webView);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		if (webView != null)
		{
			// Remove the WebView from the old placeholder
			webViewPlaceholder.removeView(webView);
		}

		super.onConfigurationChanged(newConfig);
		
		// Load the layout resource for the new configuration
		setContentView(R.layout.state_preserving_impl);

		// Reinitialize the UI
		initUI();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);

		// Save the state of the WebView
		webView.saveState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);

		// Restore the state of the WebView
		webView.restoreState(savedInstanceState);
	}
}

We need to change also the AndroidManifest.xml file to intercept the configuration changes inside the activity:

<activity
	android:name=".StatePreservingImplActivity"
	android:configChanges="keyboard|keyboardHidden|orientation"
	android:label="State preserving implementation"/>

In the android:configChanges attribute we are telling the system that we don’t want the activity to be restarted when the declared configuration changes happen, but we want to handle the configuration changes by ourselves through the onConfigurationChanged method that will be called every time there is a change.

When the activity is created we initialize its content with the current layout and we initialize the user interface with the initUI method. That’s where the WebView is created, stored in the webView class field and then attached to the webViewPlaceholder element filling its space completely. Every time the screen is rotated, the onConfigurationChanged method is called so we remove the WebView from its current placeholder first, then we load the new activity layout (we can define a different layout for the portrait and the landscape configuration) and reinitialize the UI. After a configuration change, the activity instance is still the same because it has not been destroyed. The initUI method retrieves the new placeholder instance while the WebView instance is still the same because the webView class field is not changed, so the WebView is not created again and all we have to do is attach the old WebView to the new webViewPlaceholder instance.

This implementation is very useful in case you defined a different layout depending on the screen orientation. For example, you could have a my_activity_layout.xml file in the res/layout folder of your Android project for the portrait orientation and another my_activity_layout.xml file in the res/layout-land folder with a different content for the landscape orientation. When onConfigurationChanged is called, the system already has the appropriate resources for the new configuration and when you call the setContentView method passing it a layout resource id, the system uses the correct layout file for the current screen orientation, you just have to make sure that the ids of the UI elements are the same in both files and that the webViewPlaceholder element is present in both the layout configurations. This is what I have also in the internal web browser of my FWebLauncher app and that allows me to have a different position and layout of the buttons bar depending on the screen orientation while keeping the same WebView instance.

I’m sure you noticed that the onSaveInstanceState and onRestoreInstanceState methods are still there, but why since the activity is not destroyed anymore? Well, they are there in case the activity is destroyed for a reason that is not a configuration change (e.g. the system needs to destroy the activity because it is not in foreground and there’s a need to free some memory). In that case we can still restore the original state of the WebView, just without preserving the complete state because we’re going to lose the zoom and the scroll position for example, anyway it’s still better than totally losing the WebView state.

If you want to read more about the configuration change handling in Android, you can check the specific page of the Android documentation. You can also download an example application through the link on top of this post to take a look at the source code that shows what I described in the post.

Comments

Timur
Reply

Thank you!
Very useful solution

Ryan
Reply

How would you add a status bar into this. I have added a status bar. The code looks like this

/**final Activity activity = this;
webView.setWebChromeClient(new WebChromeClient() {

public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && progressBar.getVisibility() == ProgressBar.GONE){
progressBar.setVisibility(ProgressBar.VISIBLE);
LoadingText.setVisibility(TextView.VISIBLE);
}
activity.setProgress(progress);
if(progress == 100) {
progressBar.setVisibility(ProgressBar.GONE);
LoadingText.setVisibility(TextView.GONE);
}
}
}); */

Andrea Bresolin
Reply

@Ryan you just need to:
- make sure that your progressBar and LoadingText instances are retrieved every time the layout is loaded, so you have to do that in the initUI method where also webViewPlaceholder is retrieved;
- initialize the WebChromeClient inside the initUI method right after the WebViewClient initialization because you just need to initialize it once when the WebView is created;
- access the current progressBar and LoadingText instances inside the onProgressChanged handler method to always interact with the correct interface elements (you must not use old references for those elements because whenever the screen is rotated new instances are created and retrieved at the beginning of the initUI method).

@Timur @cits I’m glad you found this post useful :-)

cits
Reply

Thanks! this is THE only solution, as far as I have tried (and it is FOR LONG TIME!)

Paul Gardner
Reply

I cannot get this to work. The onCreate() is called multiple times on an orientation change. For the first change, the webView is still assigned. Later, the webView is null. Any ideas? I am using a TabHost to host the activity that contains the WebView.

Paul Gardner
Reply

Sorry, figured it out. I was guessing that the activity containing the TabHost was being recreated and that’s the case. Instead of storing the webView variable in the activity file, I am storing it in the application context where I can reference it globally. That solved it.

sm
Reply

After an Orientation change the keyboard is dead: I type and nothing shows up. Also the keyboard is exactly the same. It appears that something else has changed in the configuration I’ve no idea what I’m doing wrong. (I’m using Android 2.3)

sm
Reply

Correction:

After an Orientation change the keyboard is dead: I type and nothing shows up. Also the keyboard is not exactly the same. Some buttons are missing, It appears that something else has changed in the configuration I’ve no idea what I’m doing wrong. (I’m using Android 2.3)

Andrea Bresolin
Reply

@sm Have you tried the following code to keep your keyboard working? If not, give it a try.


webView.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
// This is useful to make the text input work on text fields
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus())
{
v.requestFocus();
}
break;
}

return false;
}
});

Paul
Reply

Hi,
first of all thanks for your tutorial, great explanation of the topic!
I followed your guide, but it didn’t work and I don’t know why. I hope it’s ok to post my code here and you can help me. Thanks for your time!

Layout:

Code:

import org.apache.http.util.EncodingUtils;

import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.MenuItem;

public class PayPalActivity extends SherlockActivity {

private ActionBar actionbar;
private WebView webview;
private TextView loadingtxt;
private ProgressBar progressbar;
private FrameLayout webViewPlaceholder;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paypal);

initUI();
}

private void initUI() {

actionbar = getSupportActionBar();
actionbar.setTitle(R.string.paypal_actionbar_headline);
actionbar.setHomeButtonEnabled(true);
this.actionbar.setDisplayHomeAsUpEnabled(true);

webViewPlaceholder = ((FrameLayout)findViewById(R.id.webViewPlaceholder));
loadingtxt = (TextView) findViewById(R.id.paypal_loadingtext);
progressbar = (ProgressBar) findViewById(R.id.paypal_progressbar);

if(webview == null) {

webview = new WebView(this);
// webview = (WebView) findViewById(R.id.paypal_webview);
webview.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
webview.requestFocus(View.FOCUS_DOWN); // Enables the keyboard in landscape mode
webview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}

return false;
}
});

webview.getSettings().setJavaScriptEnabled(true); // Enables JavaScript
webview.getSettings().setBuiltInZoomControls(true); // Enables zoom

webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // Displays scrollbars outside the view
webview.setScrollbarFadingEnabled(false);

webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);

webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {

loadingtxt.setVisibility(TextView.VISIBLE);
progressbar.setVisibility(ProgressBar.VISIBLE);
webview.setVisibility(WebView.GONE);

progressbar.setProgress(progress);
if(progress == 100) {
loadingtxt.setVisibility(LinearLayout.GONE);
progressbar.setVisibility(LinearLayout.GONE);
webview.setVisibility(WebView.VISIBLE);
}
}
});

webview.setWebViewClient(new WebViewClient());

byte[] post = EncodingUtils.getBytes(“blabla”, “BASE64″);
webview.postUrl(“some url.com”, post);
}

webViewPlaceholder.addView(webview);
}

@Override
public void onConfigurationChanged(Configuration newConfig)
{
if (webview != null)
{
// Remove the WebView from the old placeholder
webViewPlaceholder.removeView(webview);
}

super.onConfigurationChanged(newConfig);

// Load the layout resource for the new configuration
// setContentView(R.layout.paypal);

// Reinitialize the UI
initUI();
}

@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);

// Save the state of the WebView
webview.saveState(outState);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);

// Restore the state of the WebView
webview.restoreState(savedInstanceState);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
finish();
return(true);
default:
return super.onOptionsItemSelected(item);
}
}
}

I’m using SherlockActionBar. Maybe thats the problem?
Thanks,
Paul

mrana
Reply

Thx for this tutorial.

I wanna use this but getting error(“The specified child already has a parent. You must call removeView() on the child’s parent first.”)

In my app i have 9 buttons which upon pressing opens hyperlinks to my website. Before implementing ur technique i was using simple browser to display those web pages.

What i think is i need some mechanism by which i could remove the webview after user is done reading/using the page that has been opened by the button press.

In ur code, you have done the same thing on onConfirationChange();

Below is my code(I have just modified the UI method rest code is same as yours):

protected void initUI() {

wbPlaceHolder = (FrameLayout) findViewById(R.id.wbPlaceHolder);

if (wv == null) {
wv = new WebView(this);

wv.setLayoutParams(new ViewGroup.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
wv.getSettings().setSupportZoom(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setBuiltInZoomControls(true);
wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
wv.setScrollbarFadingEnabled(true);
wv.getSettings().setLoadsImagesAutomatically(true);

rBundle = this.getIntent().getExtras();

if (rBundle.containsKey(“1″)) {
url = (String) getIntent().getSerializableExtra(“1″);
try {
wv.loadUrl(url);

} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“2″)) {

url = (String) getIntent().getSerializableExtra(“2″);
try {
wv.loadUrl(url);

} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“3″)) {

url = (String) getIntent().getSerializableExtra(“3″);
try {
wv.loadUrl(url);

} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“4″)) {

url = (String) getIntent().getSerializableExtra(“4″);
try {
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“5″)) {

url = (String) getIntent().getSerializableExtra(“5″);
try {
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“6″)) {

url = (String) getIntent().getSerializableExtra(“6″);
try {
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“7″)) {

url = (String) getIntent().getSerializableExtra(“7″);
try {
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}

} else if (rBundle.containsKey(“8″)) {

url = (String) getIntent().getSerializableExtra(“8″);
try {
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
} else if (rBundle.containsKey(“9″)) {

url = (String) getIntent().getSerializableExtra(“9″);
try {
wv.loadUrl(url);
} catch (Exception e) {
e.printStackTrace();
}
}

}
wbPlaceHolder.addView(wv);
}

mrana
Reply

Sorry for inconvenience, i have Solved the issue :)

Thanks,

bmcwhirt
Reply

mrana, how did you resolve your error? I’m getting the same thing…

Marlo Fullerton
Reply

This example is great. I was able to get this to work, mostly, in my app, but am having a problem with the website that uses cgi.

I am using webView to go to a website app written in perl that the user inputs their information and when submitted a page returns with detailed voting information. When I go to the main page or any static html pages and change the orientation, the state is preserved. If I click on start on the main page and go to the form page (now we are in the cgi part of the app) and then change the orientation I get the android page…Webpage not available…with a link to the page, https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi..if you click on that link the page comes up (the main page of the app). If I don’t change the orientation I am able to get through the app just fine. I am not sure what the problem is. I thought may be the cookies/session info was not being saved. I added…

CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
CookieManager.getInstance().setAcceptCookie(true);

..in onCreate. This did not help. May be I don’t have it in the correct place?

In LogCat I see the orientation change and
handleIntent() android.intent.action.CONFIGURATION_CHANGED handled by com.android.portal.EvbridgeService

Is this correct?

Then I see Unknown chromium error: -400
PageStarted: https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi
PageFinished: https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi
PageStarted: https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi
PageStarted: https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi
PageFinished: https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi
PageFinished: https://app.mt.gov/cgi-bin/voterinfo/voterinfo.cgi

I have been googling the chromium error and this situation and can not find any answers. Any help is greatly appreciated. I can post my activity code if needed.

Thanks!

Fabio
Reply

Very good tutorial, the example works fine on Android 2.2 – 2.3, but is not ok on Android 4 and 4.1.
I have checked with a real device and with emulator, but I don’t find the mistake. Can you help me?

Thank’s,
Fabio

Fabio
Reply

Solved the mistake on Android > 4.
Just add “screenSize” to configChanges ans set “project build target” >= 3.2.
Now configChanges is:
android:configChanges=”keyboard|keyboardHidden|screenSize|orientation”

Fabio

Rocco
Reply

Great article! Just one idea that can simplify things quite a lot:

If you have only one fullscreen-webview in your activity (what is often the case), you don’t need no placeholder.

Just create a webview in your activity like

myWebView = new WebView( this );

… setup, config etc it, then:

setContentView( myWebView );

No layout or whatsoever XML is required.

onConfigurationChanged() then simplifies to

super.onConfigurationChanged(newConfig);
setContentView( myWebView );

PS:
Please add Fabio’s discovery to your code, it’s vital on modern hardware…

Moob
Reply

This is brilliant. Thanks!

Is any reader able to tell me how to reset the zoom of the webView on orientation change? I want landscape views to be zoomed out to fit the full width of the page.

I’m new to this (and probably a bit dumb ;) )

mrana
Reply

Hi there,
I’m facing an issue(black screen)with ur code.
Steps to produce the bug:
In my case, i have 6 buttons navigating to various web pages using web view.
1. Try to load any webview and after page finsh loading click on “HOME” button.
2. App goes back to background, now try to re-launch the app a black screen appears.

I think you need to override the onPause and onStop to make ur code more effective. I’m lil bit curious to know that how u will handle the onPaue and onStop.

Waiting for the update :)

DX
Reply

This turned out to be much more complicated than was necessary, at least for me. According to the android WebView docs:

“The standard behavior for an Activity is to be destroyed and recreated when the device orientation or any other configuration changes. This will cause the WebView to reload the current page. If you don’t want that, you can set your Activity to handle the orientation and keyboardHidden changes, and then just leave the WebView alone. It’ll automatically re-orient itself as appropriate. Read Handling Runtime Changes for more information about how to handle configuration changes during runtime.”

That’s pretty much all I needed to do. On the Activity that contained the WebView, I added:

android:configChanges=”orientation|screenSize”

I didn’t have to add any extra code, the WebView natively handles the rotation, you don’t need to add your own code to do it.

7c0
Reply

Very helpful article. Spent a whole day trying to preserve the state of a complex page until I found the heads up here. Works like a charm for me (with a lot of modifications of course, but the basic idea stays). Can’t help but wonder if there couldn’t have been a more robust saveState function in the API… It’s really tiring to override the half of the Android API just to get a simple job done.

PBOS
Reply

When using google maps in a WEBVIEW an API-key is required.
In the layou XML file this would be: android:apiKey=”djfd345v3f4f35345f3″. How could I provide the key in your approach?

Regards

tdtruong
Reply

thank you very much, i am needing

Cor
Reply

Hi DX,

Your suggestions using
android:configChanges=”orientation|screenSize”
works like a charme. Little issue though, in my case I had to use:
android:configChanges=”orientation|screenLayout”
because eclipse did not swollow the screenSize option.

Cheers.

Ala'a Karss
Reply

Hello ,thanks for the amazing example ,it works fine with me.

I need to know how to make a view of tow web views in fragments work fine in land scape mode to be displayed beside each other ?

David Jones
Reply

I want to save the instance of webview and load its state in onResume() function. How can i do that?

Daniel
Reply

When I rotate and initUI is hit, webview is always null. Why is this? My code is exactly as in the example.

Alex
Reply

The line in manifest should read
android:configChanges=”keyboard|keyboardHidden|orientation|screenSize”

Notice screenSize – you want to catch that one as well.

From docs: Caution: Beginning with Android 3.2 (API level 13), the “screen size” also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the “screenSize” value in addition to the “orientation” value. That is, you must decalare android:configChanges=”orientation|screenSize”. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

Fantastic tutorial! Thank you.

Greg
Reply

Strange solution – To preserve the state of an Android WebView upon a screen orientation change, all you need to do is simply add this line in the activity section of your AndoidManifest.xml:

android:configChanges=”orientation|screenSize”

Anyhow, I tried your solution and found that after opening a link from within the WebView, the whole app closed upon pressing the Back button???

Cheers.

crom_x
Reply

Hi,

This is this is a brilliant solution. Thank you very much.
I have a question although.
When screen is rotated and WebView is still loading, the load process will be interrupted and downloaded data will be lost?
How can you keep the WebView to load data while the screen is rotated ?

Thanks.

Lesly
Reply

THANKS!

Vernon
Reply

Oh my goodness! Incredible article dude! Thank you so much, However I am experiencing troubles with your RSS. I don’t know the reason why I am unable to join it. Is there anybody getting the same RSS problems? Anyone that knows the solution can you kindly respond? Thanx!!

Leave a comment

name*

email* (not published)

website