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

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


当前回答

谷歌推出的android架构中最好的组件之一将满足ViewModel的所有要求。

它旨在以生命周期的方式存储和管理与UI相关的数据,并允许数据在屏幕旋转时继续存在

class MyViewModel : ViewModel() {

请参阅:https://developer.android.com/topic/libraries/architecture/viewmodel

其他回答

您可以使用此代码锁定屏幕的当前方向。。。

int currentOrientation =context.getResources().getConfiguration().orientation;
        if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            ((Activity) context). setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

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

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

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

public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_game_list);

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

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

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台设备……没有。(不知道为什么会有什么不同。)

谷歌推出的android架构中最好的组件之一将满足ViewModel的所有要求。

它旨在以生命周期的方式存储和管理与UI相关的数据,并允许数据在屏幕旋转时继续存在

class MyViewModel : ViewModel() {

请参阅:https://developer.android.com/topic/libraries/architecture/viewmodel

修复AndroidManifest.xml中的屏幕方向(横向或纵向)

android:screenOrientation=“纵向”或android:scheenOrientation=“横向”

为此,不会调用onResume()方法。