Friday, May 27, 2011

Android WebView Orientation Changes

We know, Android destroys the current activity and re-creates the same activity all over again.So for the webview it has to reload the page during orientation changes.

This can be resolved by overriding onSaveInstanceState(Bundle outState) in your activity and calling saveState from the Webview:

@Override


protected void onSaveInstanceState(Bundle outState) {


webView.saveState(outState);


}


Then rewrite your onCreate :

public void onCreate(final Bundle savedInstanceState) {


super.onCreate(savedInstanceState);


setContentView(R.layout.blah);


if (savedInstanceState != null)


((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);


else
webview.loadUrl("yourUrl");


}


And set the android:configChanges attribute in the manifest:

android:label="@string/appName"
android:configChanges="keyboardHidden|orientation"

5 comments:

Unknown said...

one more addition

Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation.

So configuration should be changed as
android:configChanges="keyboardHidden|orientation|screenSize"

Bert Steve said...

Finally something that actually works. Took me 3 months!!! THANK YOU!!!

Pccore said...

Thank you very mutch!!! :)

Cristiana M. said...

This is great , really works!

siva said...

hey well said on Android Online Training