简体   繁体   English

如何处理活动方向更改以不重新创建活动?

[英]How to handle activity orientation change to dont recreate the activity?

I start an activity with startActivityForResult() but after the orientatikn changed and i return to the onActivityResult() method the requestCode not the same. 我使用startActivityForResult()启动活动,但是在更改方向后,我返回到onActivityResult()方法,requestCode不相同。 I would like to use different layout if the screen orientation is in landscape mode. 如果屏幕方向为横向模式,我想使用其他布局。 I tried in the manifest the configuration with orientation and screenSize params, but if i use this the layout not changed to the landscape layout. 我在清单中尝试了带有direction和screenSize参数的配置,但是如果使用此配置,则布局不会更改为横向布局。 I started the activity with requestCode=0 but after the orientation changed i see that the requestCode = 66357 or something. 我从requestCode = 0开始活动,但是在方向改变后,我看到requestCode = 66357之类的东西。

Create two types of the layout folders. 创建两种类型的布局文件夹。 "layout-land" and "layout-port". “布局土地”和“布局端口”。 put the required xml in both the directory with same name. 将所需的xml放在同一个目录中。

you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity. 您可以声明您的活动自行处理配置更改,从而阻止系统重新启动您的活动。

In your AndriodMainfest.xml define configChanges 在您的AndriodMainfest.xml中定义configChanges

<activity android:name=".ResultActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

Then in your ResultActivity.java(that you call to get result) define onConfigurationChanged() 然后在您的ResultActivity.java(您为了获取结果而调用)中定义onConfigurationChanged()

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

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

official link 官方链接

You have two options: 您有两种选择:

A)Set your app to not rotate. A)将您的应用设置为不旋转。

B)Or accept that the world is not perfect yet and modify your app to handle configuration change B)或接受世界还不完美的想法,并修改您的应用以处理配置更改

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

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