You should add the configChanges
flag with the value keyboardHidden
, orientation
and screenSize
in your Activity
flags
can be added with Android.Content.PM.ConfigChanges
more or less so:
[Activity (Label = "@string/app_name", MainLauncher = true, Icon="@drawable/launcher",
ConfigurationChanges = ConfigChanges.KeyboardHidden | ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : ...
I'm not sure if Xamarin provides control over the generated Manifest.xml, but if it makes available to the <activity>
tag, add android:configChanges="keyboardHidden|orientation|screenSize"
, for example:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:configChanges="keyboardHidden|orientation|screenSize">
I do not know if this is necessary for Xamarin (or if it depends on a newer version of Android), but if the previous configuration is not enough then save the instances:
Add to methods (or create them) with override :
private WebView minhaWebView; //Se a sua webView nesta variável
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
...
}
protected override void OnSaveInstanceState(Bundle outState)
{
base.OnSaveInstanceState(outState); //Salva Activity
minhaWebView.SaveState(outState); //Salva WebView
}
protected override void OnRestoreInstanceState(Bundle savedInstanceState)
{
base.OnRestoreSaveInstanceState(savedInstanceState); //Restaura o Activity
minhaWebView.RestoreState(savedInstanceState); //Restaura o WebView
}
private WebView minhaWebView; //Defina a webView nesta variável
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
@Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState); //Salva Activity
minhaWebView.saveState(outState); //Salva WebView
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState); //Restaura o Activity
minhaWebView.restoreState(savedInstanceState); //Restaura o WebView
}
Activities on Android are destroyed and re-created when the screen rotates. You need to save the required data in a Bundle before it is destroyed in the onSaveInstanceState () method and then restore the Bundle data in OnCreate if it is not null.
More details here: link
To complement, a shortcut you can turn to is the use of setRetainInstance (true) ;, so your problems with persistence when your activity or fragment is destroyed will be resolved in part. xD