通过旋转方向更改布局而无需重新加载 OnCreate()

Via rotate orientation change layout without reload OnCreate()

我在不同的文件夹中有 3 个布局:

1.layout/HomeLayout.axml(其中 layout 是布局的文件夹,HomeLayout.axml 是全局 axml 文件)。
2.layout-large-port/HomeLayout.amxl(其中layout-large-port是大(显示尺寸)纵向的文件夹,HomeLayout.axml是一个xml文件)。
3.layout-large-land/HomeLayout.axml(其中 layout-large-land 是大(显示尺寸)风景的文件夹和 HomeLayout.axml是一个xml文件)。

在这个 activity 上,我得到了带有一些数据的 ListView,当我从 纵向 [=51= 旋转我的 phone 时] 到 landscape ,我需要保存我在 Portrait 模式下所做的所有内容(listview 上的每一行都有buttons/textview 等)并显示在 Landscape 上。

那么当前做了什么。在 HomeActivity 上,我声明了这一点:

ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation

这个代码片段运行良好,但有一个大问题:旋转后(从 PortraitLandscape)仍然是纵向布局。我该如何解决?

我还尝试 覆盖 方法 OnConfigurationChanged :

 public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
        {
            base.OnConfigurationChanged (newConfig);

            if(newConfig.Orientation == Android.Content.Res.Orientation.Landscape)
                {
                   SetContentView(Resource.Layout.ProductsLayout); //system understand that now is Landscape and put correct layout;  
                }
            else
                {
                    SetContentView(Resource.Layout.ProductsLayout); //same here
                }  

所以这个方法对我没有帮助,因为当我旋转 phone 时,布局设置正确但没有数据(列表视图为空),之后,当我试图从 横向纵向,布局设置正确但列表为空。
有什么建议吗?

PS对不起我的英语!

Android 将在配置更改时完全破坏并重新创建您的 activity; activity 中的所有视图及其保存的数据也将被丢弃。

来自Android docs

Caution: Your activity will be destroyed and recreated each time the user rotates the screen. When the screen changes orientation, the system destroys and recreates the foreground activity because the screen configuration has changed and your activity might need to load alternative resources (such as the layout).

在配置更改之间持久保存数据的标准机制是使用 ActivityOnSaveInstanceState 回调保存视图数据,然后使用 OnCreate 提供的包恢复数据]回调。

这是一个粗略的示例:

public class MainActivity : Activity
{
    public const string ARG_LIST_STATE = "list_state";
    ListView _listView;

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        SetContentView (Resource.Layout.Main);

        if (bundle != null) {
            // Existing data to restore!
            if (bundle.ContainsKey (ARG_LIST_STATE)) {
                var listState = bundle.GetStringArray (ARG_LIST_STATE);
                // TODO: Restore state into list view.
            }
        }
    }

    protected override void OnSaveInstanceState (Bundle outState)
    {
        string[] listState= new string[5]; // TODO: Grab data from the list view and serialize it into the outState
        outState.PutStringArray(ARG_LIST_STATE, listState);

        base.OnSaveInstanceState (outState);
    }
}

另一个示例由 Xamarin here.

提供

我强烈建议您查看 activity lifecycle docs 以便更好地了解 Android 如何管理活动。

解决方案是(对我而言)为肖像设计可接受的设计,这与横向模式没有区别(只需使用 sum_weight 等)。