在我的Android应用程序中,当我旋转设备(滑出键盘)时,“活动”将重新启动(调用onCreate)。现在,这可能是应该的,但我在onCreate方法中做了很多初始设置,所以我需要:

将所有初始设置放在另一个功能中,这样不会在设备旋转或使其不再调用Create,布局仅调整或将应用程序限制为仅肖像,以便不调用onCreate。


当前回答

有很多方法可以做到这一点:

在创建时使用标志在清单文件中添加以下行


> android:screenOrientation=“纵向”


在onCreate()中


setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

使用onConfigurationChanged()方法


在清单文件中,为Android 3.2及更高版本添加以下行/

     


android:configChanges="keyboardHidden|orientation" / android:configChanges="keyboardHidden|orientation|screenSize"

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

if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
        //Handle rotation from landscape to portrait mode here
    } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
        //Handle rotation from portrait to landscape mode here
    }
}

使用onSaveInstanceState()@覆盖public void onSaveInstanceState(捆绑outState){/在此处保存要还原的数据示例:outState.putLong(“time_state”,time),时间是一个长变量/super.onSaveInstanceState(outState);}

和恢复

@覆盖protected void onCreate(捆绑savedInstanceState){super.onCreate(savedInstanceState);

if(savedInstanceState!= null){
   /*When rotation occurs
    Example : time = savedInstanceState.getLong("time_state", 0); */
} else {
  //When onCreate is called for the first time
}

}

其他回答

我发现这样做的方法是使用onRestoreInstanceState和onSaveInstanceState事件在Bundle中保存一些东西(即使您不需要保存任何变量,也只需在其中放置一些东西,这样Bundle就不会为空)。然后,在onCreate方法上,检查Bundle是否为空,如果为空,则进行初始化,如果不是,则执行初始化。

您所描述的是默认行为。您必须通过添加以下内容自行检测和处理这些事件:

android:configChanges

然后是您想要处理的更改。因此,对于方向,您可以使用:

android:configChanges="orientation"

对于正在打开或关闭的键盘,您可以使用:

android:configChanges="keyboardHidden"

如果要同时处理这两种情况,只需使用pipe命令将它们分开,如:

android:configChanges="keyboardHidden|orientation"

这将在您调用的任何Activity中触发onConfigurationChanged方法。如果重写该方法,则可以传入新值。

希望这有帮助。

将以下代码放入Manifest.xml中的<activity>标记中:

android:configChanges="screenLayout|screenSize|orientation"
onConfigurationChanged is called when the screen rotates. 
(onCreate is no longer called when the screen rotates due to manifest, see:  
android:configChanges)

清单的哪个部分告诉它“不要调用onCreate()”?

而且谷歌的文档说要避免使用android:configChanges(除非作为最后手段)。但是,他们建议的替代方法都使用android:configChanges。

根据我的经验,模拟器总是在旋转时调用onCreate()。但我运行相同代码的1-2台设备……没有。(不知道为什么会有什么不同。)

与其试图阻止onCreate()被完全激发,不如尝试检查传递到事件中的Bundle savedInstanceState,看看它是否为null。

例如,如果我有一些逻辑应该在真正创建“活动”时运行,而不是在每次方向更改时运行,那么只有当savedInstanceState为空时,我才在onCreate()中运行该逻辑。

否则,我仍然希望布局按照方向正确重新绘制。

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_game_list);

        if(savedInstanceState == null){
            setupCloudMessaging();
        }
}

不确定这是否是最终答案,但这对我来说是有效的。