在方向更改后保留/恢复可见性

时间:2012-02-15 19:59:44

标签: android xamarin.android

我有一个包含多个嵌套LinearLayouts的RelativeLayout。默认情况下,LinearLayouts的可见性设置为已消失,因此当活动首次加载时,它们都不可见。我有两个按钮,按下时应显示/隐藏LinearLayouts。除非重新定向设备并且可见性属性重置为xml中的默认“已消失”,否则一切都很有效。如何在方向更改期间保留视图的当前可见状态?

编辑:有问题的其他任何人的最终代码。基本上只需将可见视图标记添加到void中的SharedPreferences,以更改可见性并在OnCreate中检查它。

[Activity(Label = "My Activity", Theme="@style/TitleBar")]
public class CallManagement : Activity
{
    public LinearLayout parts; 
    public LinearLayout status; 

    ISharedPreferences p;

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

        SetContentView(Resource.Layout.CallManager);

        parts = (LinearLayout)FindViewById(Resource.Id.partLayout);
        status = (LinearLayout)FindViewById(Resource.Id.statLayout);

        p = PreferenceManager.GetDefaultSharedPreferences(this);
        var visible = p.GetString("VisibleLayout", null);

        if (visible != null && visible != "None")
        {
            RelativeLayout container = (RelativeLayout)FindViewById(Resource.Id.container);
            LinearLayout current = (LinearLayout)container.FindViewWithTag(visible);
            changeVisibility(current);
        }

        Button statusb = (Button)FindViewById(Resource.Id.changeStat);
        Button partsb = (Button)FindViewById(Resource.Id.addParts);

        statusb.Click += delegate
        {
            LinearLayout current = status;
            changeVisibility(current);
        };

        partsb.Click += delegate
        {
            LinearLayout current = parts;
            changeVisibility(current);
        };
    }

    void changeVisibility(View v)
    {           
        LinearLayout current = (LinearLayout)v;

        parts.Visibility = ViewStates.Gone;
        status.Visibility = ViewStates.Gone;

        var editor = p.Edit();

        if (v.Visibility == ViewStates.Gone)
        {
            v.Visibility = ViewStates.Visible;
            editor.PutString("VisibleLayout", v.Tag.ToString());
        }
        else
        {
            editor.PutString("VisibleLayout", "None");
        }

        editor.Commit();
    }

}

1 个答案:

答案 0 :(得分:1)

执行此操作的方法是在字段中维护视图的状态,如果要维护很多设置,则可能需要创建私有类。然后:

  1. 覆盖onRetainNonConfigurationInstance方法并返回该实例。
  2. 在onCreate方法中,检索实例,如果它不为null,则使用它来恢复这些值。像this.activityState = (UserAccountData) getLastNonConfigurationInstance();
  3. 之类的东西

    大多数人都没有意识到每当您更改方向时都会重新创建活动。因此,这可以让您将这些设置传达给新实例。