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

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


当前回答

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

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

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

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

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

其他回答

我所做的。。。

在清单的活动部分中,添加了:

android:configChanges="keyboardHidden|orientation"

在活动代码中,实现:

//used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI()
{
    //get views from ID's
    this.textViewHeaderMainMessage = (TextView) this.findViewById(R.id.TextViewHeaderMainMessage);

    //etc... hook up click listeners, whatever you need from the Views
}

//Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    InitializeUI();
}

//this is called when the screen rotates.
// (onCreate is no longer called when screen rotates due to manifest, see: android:configChanges)
@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
    setContentView(R.layout.main);

    InitializeUI();
}

我只是简单地补充了一句:

android:configChanges="keyboard|keyboardHidden|orientation"

在AndroidManifest.xml文件中,并且没有在我的活动中添加任何onConfigurationChanged方法。

所以,每当键盘滑出或滑入时,什么都不会发生!也可以查看这篇关于这个问题的文章。

将此代码添加到manifest.xml中。

这是你的活动。

<activity
....
..
android:configChanges="orientation|screenSize"/>

我刚刚发现了这个传说:

为了通过方向更改保持活动活动,并通过onConfigurationChanged处理活动,上面的文档和代码示例在Manifest文件中建议:

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

这有一个额外的好处,那就是它总是有效的。

另一个好处是,省略keyboardHidden可能看起来合乎逻辑,但它会导致模拟器失败(至少对于Android 2.1):只指定方向会使模拟器有时同时调用OnCreate和onConfigurationChanged,而其他时候只调用OnCreate。

我还没有看到设备出现故障,但我听说过其他设备的仿真器出现故障。因此值得记录。

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

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