android 防止更改方向时刷新

android prevent refresh on change orientation

我有 layout/activity_main.xmllayout-land/activity_main.xml。当我改变方向时 activity 再次重新加载。

我尝试使用此代码 android:configChanges="keyboardHidden|orientation" 并且它起作用了 activity 并没有重新加载我喜欢的内容,但问题是布局没有从 layout/activity_main.xml 切换到 layout-land/activity_main.xml

如何从 layout/activity_main.xml 切换到 layout-land/activity_main.xml。不刷新 activity.

试试这个:

android:configChanges="orientation|screenSize"

在您的 Android 清单中 在您的 <activity> 标签中限制 activity.

的重新加载

通过声明 android:configChanges="orientation|screenSize",您指示 Activity 管理器不要重新启动您的 activity 并让您通过 onConfigurationChanged().

处理配置更改

If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the activity restart, then you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.

来源:http://developer.android.com/guide/topics/resources/runtime-changes.html

这意味着 onCreate() 将在配置更改时被跳过,并且您不能交换布局(因为 onCreate() 是您重新创建视图的地方)。

在你的情况下,你想改变布局,所以别无选择,只能刷新你的 activity,这意味着删除 android:configChanges="orientation|screenSize"。如果你想保持状态,你可以保存并检查传递给你的 onCreate()Bundle 以相应地恢复状态。

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // set your layoutId according to landscape/portrait
    setContentView(layoutId);
    if (savedInstanceState != null) {
        // restore your state here
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // save your state here
}

更多参考:http://developer.android.com/training/basics/activity-lifecycle/recreating.html