获取ListView内部开关的检查状态

时间:2019-06-10 17:59:58

标签: c# xamarin.android

我有问题。我有一个带有自定义适配器的ListView。在适配器内部,我将开关添加到一行。现在,我在适配器代码中创建了以下代码:

SettingSwitch.CheckedChange += (s, b) =>
{
    bool isChecked = SettingSwitch.Checked;


    SettingDb setting = new SettingDb()
    {
        Name = SettingName.Text,
        Value = isChecked.ToString()
    };

    MainActivity.db.UpdateTableSettings(setting);
};

但是事实证明SettingSwitch.Checked总是返回false!

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

您可以创建一个集合来存储开关的检查状态,然后在将其加载到getView中时加载该集合,这样可以获取正确的状态:

class YourAdapter : BaseAdapter,CompoundButton.IOnCheckedChangeListener
{
    private Dictionary<int, bool> checkDictionary = new Dictionary<int, bool>();
    int[] item;  //raplace your own data
    public MyAdapter(int[] value) //raplace your own data
    {
        item = value;
        for (int i = 0; i < item.Length; i++)
        {
            checkDictionary.Add(i,false);
        }
    }

     public override View GetView(int position, View convertView, ViewGroup parent)
        {
            if (convertView == null)
            {
                convertView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.layout6, null);
            }

            Switch sSwitch = convertView.FindViewById<Switch>(Resource.Id.SettingSwitch);
            sSwitch.SetOnCheckedChangeListener(null);
            sSwitch.Checked = checkDictionary[position];
            sSwitch.Tag = position;
            sSwitch.SetOnCheckedChangeListener(this);
            return convertView;

        }
    public void OnCheckedChanged(CompoundButton buttonView, bool isChecked)
        {
            var position = buttonView.Tag;

            //here store the correct state and do something you want
            checkDictionary[(int) position] = isChecked;

        }
 }