简体   繁体   English

防止在方向更改时重新启动活动

[英]prevent activity restarting when orientation changes

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 . 我是Android开发的新手。我有纵向和横向模式的单独屏幕。当我改变我的方向时,相应的屏幕被加载并且活动重新开始。 Now i do not want my activity to restart when i change the orientation but should load its corresponding screen(axml). 现在我不希望我的活动在我改变方向时重新启动,但是应该加载相应的屏幕(axml)。

I have tried 我试过了

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

the above line stops activity getting restarted but it loads the same screen(axml). 上面的行停止活动重新启动但它加载相同的屏幕(axml)。 Please suggest . 请建议。 thanks 谢谢

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. 因此,这将处理这两件事,它不会重新启动您的活动,并将根据您的方向更改加载布局。

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM