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

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


当前回答

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

其他回答

注意:如果将来有人和我面临同样的问题,我会发布这个答案。对我来说,下面这行是不够的:

android:configChanges="orientation"

当我旋转屏幕时,没有调用方法`onConfigurationChanged(配置新配置)。

解决方案:即使问题与方向有关,我也必须添加“screenSize”。因此,在AndroidManifest.xml文件中,添加以下内容:

android:configChanges="keyboardHidden|orientation|screenSize"

然后实现方法onConfigurationChanged(Configuration newConfig)

尽管这不是“Android方式”,但我自己处理方向变化,并简单地在视图中重新定位小部件,以将改变的方向考虑在内,从而获得了非常好的结果。这比任何其他方法都快,因为您的视图不必保存和恢复。它还为用户提供了更无缝的体验,因为重新定位的小部件是完全相同的小部件,只是移动和/或调整大小。不仅可以以这种方式保存模型状态,还可以保存视图状态。

RelativeLayout有时对于需要不时调整自身方向的视图来说是一个不错的选择。您只需为每个子控件提供一组纵向布局参数和一组景观布局参数,每个参数上有不同的相对定位规则。然后,在onConfigurationChanged()方法中,将适当的值传递给每个子级的setLayoutParams()调用。如果任何子控件本身需要在内部重新定向,只需调用该子控件上的方法来执行重新定向。该子控件类似地调用其任何需要内部重新定向的子控件上的方法,依此类推。

我所做的。。。

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

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

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

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清单中的活动中。

android:configChanges="orientation"

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