prevent activity restarting when orientation changes

sujay picture sujay · Jul 30, 2013 · Viewed 28.2k times · Source

I am new to android development .I have separate screens for portrait and landscape mode.When i change my orientation corresponding screen gets loaded and activity restarts . Now i do not want my activity to restart when i change the orientation but should load its corresponding screen(axml).

I have tried

[Activity (Label = "MyActivity",ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation)]

the above line stops activity getting restarted but it loads the same screen(axml). Please suggest . thanks

Answer

Nirali picture Nirali · Jul 30, 2013

Write this code in your activity

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.landscapeView);

    } else {
        setContentView(R.layout.portraitView);
    }
}

And also add this line in your Manifest file

android:configChanges="orientation|keyboardHidden|screenSize"

So this will handle both things, it will not restart your activity and will load the layout as per your orientation changes.