Android WebView: handling orientation changes
If you do not want the WebView to reload on orientation changes simply override onConfigurationChanged in your Activity class:
@Overridepublic 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 hereBasically 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:
@Overridepublic 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(); }}