Android WebView: handling orientation changes
The issue is the performance following rotation. The WebView has to reload the page, which can be a bit tedious.
What's the best way of handling an orientation change without reloading the page from source each time?
If you do not want the WebView to reload on orientation changes simply override onConfigurationChanged in your Activity class:
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
And set the android:configChanges attribute in the manifest:
<activity android:name="..."
android:label="@string/appName"
android:configChanges="orientation|screenSize"
for more info see:
http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange
https://developer.android.com/reference/android/app/Activity.html#ConfigurationChanges
Edit: This method no longer works as stated in the docs
Original answer:
This can be handled by overrwriting onSaveInstanceState(Bundle outState)
in your activity and calling saveState
from the webview:
protected void onSaveInstanceState(Bundle outState) {
webView.saveState(outState);
}
Then recover this in your onCreate after the webview has been re-inflated of course:
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blah);
if (savedInstanceState != null)
((WebView)findViewById(R.id.webview)).restoreState(savedInstanceState);
}
The best answer to this is following Android documentation found here Basically this will prevent Webview from reloading:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection|uiMode"
android:label="@string/app_name">
Edit(1/4/2020): You don't need this optional code, the manifest attribute is all you need, leaving optional code here to keep answer complete.
Optionally, you can fix anomalies (if any) by overriding onConfigurationChanged
in the activity:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}