Search code examples
c#androidxamarin.androidorientation-changes

Working with orientation change in mono for android


I've used following code snippet for my activity in order to deal with orientation change.

[Activity (Label = "Activity",ConfigurationChanges = ConfigChanges.Orientation 
| ConfigChanges.KeyboardHidden)]

and

public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
        {
            base.OnConfigurationChanged (newConfig);
            if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape)
            {
                Console.WriteLine("landscape");
            } 
            else if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait)
            {
                Console.WriteLine("portrait");
            }
        }

I start with Portrait mode, then switch to Landscape mode and again switch back to Portrait mode. So the expected output should be:

landscape

portrait

but Console Output shows

landscape

landscape

portrait

i.e. When switching from Landscape mode to Portrait mode, if and else both gets executed.

I've no idea why this is happening.

I'm absolute beginner to Mono for Android, so any help appreciated.


Solution

  • try this its working ...

    1) declare above oncreate()

    int prev_orientation =0;
    

    2) overide below method:

    @Override
        public void onConfigurationChanged(Configuration newConfig) {
            // TODO Auto-generated method stub
            int orientation = getResources().getConfiguration().orientation;
            if(prev_orientation!=orientation){
                prev_orientation = orientation;
            if(orientation ==1){            
                //por
                Toast.makeText(getApplicationContext(),"ort::pot"+orientation,Toast.LENGTH_LONG).show();
            }else if(orientation ==2){
                //land
                Toast.makeText(getApplicationContext(),"ort::land"+orientation,Toast.LENGTH_LONG).show();
            }
            }
            super.onConfigurationChanged(newConfig);
        }
    

    3) Add below line in manifeast file of activity:

    android:configChanges="keyboardHidden|orientation"