12

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

sujay
  • 1,845
  • 9
  • 34
  • 55

2 Answers2

41

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.

Nirali
  • 13,571
  • 6
  • 40
  • 53
  • 11-07 13:44:47.143: E/AndroidRuntime(2586): Caused by: java.lang.IllegalStateException: You are only allowed to have a single MapView in a MapActivity Shows this error when i include this – Anuj Sharma Nov 07 '13 at 08:15
  • Where to add these code in mainActivity OR each Fragment in the activity and R.layout.landscapeView and R.layout.portraitView are two different layout – Kailas Jun 18 '14 at 07:01
5

Since you have specified to the OS that you want to handle orientation change yourself, now you have to handle any changes to the layout yourself, like this:

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

    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        setContentView(R.layout.portrait);
        //do other initialization
    } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.landscape);
        //do other initialization
    }
}
Kai
  • 15,284
  • 6
  • 51
  • 82