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

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


当前回答

在清单中添加此行:android:configChanges=“orientation | screenSize”

其他回答

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

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

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

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


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

}

您可以在活动中使用ViewModel对象。

ViewModel对象在配置更改期间自动保留,以便它们所保存的数据可立即用于下一个活动或片段实例。阅读更多信息:https://developer.android.com/topic/libraries/architecture/viewmodel

将以下代码放在Android清单中的活动中。

android:configChanges="orientation"

当你改变方向时,这不会重新开始你的活动。

该方法是有用的,但在使用碎片时是不完整的。

片段通常在配置更改时重新创建。如果您不希望发生这种情况,请使用

setRetainInstance(true);在Fragment的构造函数中

这将导致在配置更改期间保留碎片。

http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(布尔值)