调用活动时Bool数组值丢失

时间:2017-12-11 20:21:16

标签: c# android xamarin xamarin.android

我希望在活动调用之间保留存储在bool数组 checkedZonesBool 中的值,但下次调用 PickActivity 时,全部重置为默认值( false )。当我再次调用 PickActivity 时,如何让它记住bool数组值?以下是我的代码......

public class PickActivity : Activity
{        
    private Button nextOrderBtn;
    private Button zoneSelectBtn;

    public static readonly List<string> CheckedZonesList = new List<string>();

    private readonly string[] zones = {
        "A",
        "B",
        "C",
        "D",
        "E",
        "F"
    };

    private readonly bool[] checkedZonesBool = {
        false,
        false,
        false,
        false,
        false,
        false
    };

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ZoneSelect);

        zoneSelectBtn = FindViewById<Button>(Resource.Id.zoneSelect);
        zoneSelectBtn.Click += ZoneSelect_Click;

        nextOrderBtn = FindViewById<Button>(Resource.Id.nextOrder);
        nextOrderBtn.Click += NextOrder_Click;
        nextOrderBtn.Enabled = CheckedZonesList.Any();
    }

    private void ZoneSelect_Click(object sender, EventArgs e)
    {
        var dialog = new AlertDialog.Builder(this);
        dialog.SetTitle(SelectZones);
        dialog.SetPositiveButton(OK, (c, ev) =>
        {
            nextOrderBtn.Enabled = CheckedZonesList.Any();
        });

        dialog.SetMultiChoiceItems(zones, checkedZonesBool, MultiListClicked);

        var alert = dialog.Create();
        alert.Show();
    }

    private void MultiListClicked(object sender, DialogMultiChoiceClickEventArgs e)
    {
        checkedZonesBool[e.Which] = !checkedZonesBool[e.Which];

        if (checkedZonesBool[e.Which])
        {
            if (!CheckedZonesList.Contains(zones[e.Which]))
            {
                CheckedZonesList.Add(zones[e.Which]);
            }
        }
        else
        {
            CheckedZonesList.Remove(zones[e.Which]);
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用SharedPreferences

在您的活动的OnCreate覆盖:

// read them
using (var settings = GetSharedPreferences("ZoneSettings", FileCreationMode.Private))
{
    for (int i = 0; i < zones.Length; i++)
    {
        checkedZonesBool[i] = settings.GetBoolean(zones[i], false);
    }
}

在您的活动的OnStop覆盖:

// saved them
using (var editor = GetSharedPreferences("ZoneSettings", FileCreationMode.Private).Edit())
{
    for (int i = 0; i < zones.Length; i++)
    {
        editor.PutBoolean(zones[i], checkedZonesBool[i]);
    }
    editor.Apply();
}