自定义列表视图包含虚假信息Xamarin Android

时间:2017-01-27 16:00:54

标签: c# android xamarin xamarin.android baseadapter

我是Xamarin的新编码,因此我制作了一个自定义适配器,我的想法是在用户关闭应用程序时保存所有内容。经过一些研究后,我认为这段代码会起作用:

List<GardenClass> MyList = new List<GardenClass> ();

protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.Main);
        listview.Adapter = new GardenAdapter(this, MyList);
    }

protected override void OnPause()
    {
        base.OnPause();
        write();
    }

public void write()
    {
        string path = System.Environment.GetFolderPath(SpecialFolder.Personal);
        string filename = Path.Combine(path, "Files.txt");

        try
        {
           File.WriteAllText(filename,JsonConvert.SerializeObject(MyList));
        }
        catch (Exception e)
        {
            Console.WriteLine("Failed to serialize. Reason: " + e.Message);
            throw;
        }
    }



public class GardenAdapter : BaseAdapter<GardenClass>
{
    private Context MyCon;

    List<GardenClass> items;
    Activity context;

    public GardenAdapter(Activity context, List<GardenClass> items)
        : base()
    {
        MyCon = context;
        this.context = context;
        this.items = items;
    }

    public override long GetItemId(int position)
    {
        return position;
    }
    public override GardenClass this[int position]
    {
        get { return items[position]; }
    }
    public override int Count
    {
        get { return items.Count; }
    }



    public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
    {
        var item = items[position];

        Android.Views.View view;
        if (convertView == null) { 
        view = context.LayoutInflater.Inflate(Resource.Layout.ListItem, null);
        } else { view = convertView; }
        view.FindViewById<TextView>(Resource.Id.textView1).Text = item.ToDo;
        view.FindViewById<TextView>(Resource.Id.textView2).Text = "Week " + item.Week.ToString();
        view.FindViewById<CheckBox>(Resource.Id.checkBox1).Checked = item.Done;

        CheckBox MyCheckBox;
        checkding = view.FindViewById<CheckBox>(Resource.Id.checkBox1);


        // The folowing code prevents the checkbox of stealing the focus, which make a singular listview item unclickable
        MyCheckBox.Focusable = false;
        MyCheckBox.FocusableInTouchMode = false;
        MyCheckBox.Clickable = true;

        return view;

    }
}

[Serializable]
public class ZaaiSpul
{
    public int Week { get; set; }
    public string ToDo { get; set; }
    public bool Done { get; set; }
}

但是当调用OnPause()函数时,MyList会给我不正确的信息(在调试器中自己看到)。

如果我做了一些错误的事情,我很抱歉,但我是Xamarin的新手。 我希望你能帮助我。

1 个答案:

答案 0 :(得分:0)

您只是在阅读复选框状态,在更改时您永远不会保存它。在GetView中添加:

            MyCheckBox.CheckedChange += (sender, e) =>
            {
                items[position].Done = e.IsChecked;
            };