Search code examples
c#androidxamarinxamarin.formsxamarin.android

ConfigurationChanged not getting fired in Android


This is my AndroidManifest.xml

<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name="LoginActivity"
              android:configChanges="orientation|keyboardHidden|screenSize|uiMode"/>
</application>

When the fragment/popUp is launched from Activity, and when I charge the device with the popUp open, then this attached screen comes up by default

On Charge

The activity and fragment are getting recreated. I suspect that the configuration must be changed. However OnConfigurationChanged is not getting fired in my activity. I tried having this overridden in the baseactivity as well, but it didn't help.

 [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
  public partial class LoginActivity : BaseActivity
  {
    // other code
    public override void OnConfigurationChanged(Configuration newConfig)
    {
        base.OnConfigurationChanged(newConfig);
        // To handle attaching Scanner(or Keyboard) at runtime withOUT restarting activity
    }     
  }

OnConfigurationChanged is not getting fired at all. I tried checking similar posts, one such post mentioned to remove portrait/landscape mode from the activity which I tried. Any suggestion on this would be helpful. Thanks.


Solution

  • In Xamaring.Android, when using the [Activity] attributes, whatever you put in the AndroidManifest.xml file gets overwritten as at compile time these attributes will be looked up and a AndroidManifest.xml file will be generated. You can see the resulting one in obj/Debug/android/.

    So instead as Leon suggested in the comments, add the properties needed in the [Activity] attribute:

    [Activity(
        Label = "@string/app_name",
        Theme = "@style/AppTheme",
        MainLauncher = true,
        ConfigurationChanges =
            ConfigChanges.ScreenSize | 
            ConfigChanges.Orientation |
            ConfigChanges.UiMode |
            ConfigChanges.KeyboardHidden
    )]
    public partial class LoginActivity : BaseActivity
    {
        // other code
        public override void OnConfigurationChanged(Configuration newConfig)
        {
            base.OnConfigurationChanged(newConfig);
            // To handle attaching Scanner(or Keyboard) at runtime withOUT restarting activity
        }     
    }
    

    This will add an entry like:

    <activity android:label="LoginActivity" android:mainLauncher="true" android:theme="@style/AppTheme" android:configChanges="orientation|keyboardHidden|screenSize|uiMode" />