简体   繁体   中英

Set and get checked boxes in MultiSelectListPreference

I'm defining the MultiSelectListPreference in my axml file like this:

 <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

偏好改变

The checked values appear there, but I have no idea how to get them...

This was also my first thought, but e.NewValue doesn't contain a public definition for 'GetEnumerator'.

We can simply cast e.NewValue from object to IEnumerable in our code, for example:

private void PreferenceChange(object sender, Preference.PreferenceChangeEventArgs e)
{
    var selections = e.NewValue as IEnumerable;
    if (selections != null)
    {
        foreach (var selection in selections)
        {
            Console.WriteLine(selection);
        }
    }
}

since e.NewValue is a HashSet, you should be able to iterate through it

foreach (string x in e.NewValue) {
  // do whatever you need to do with each value x here
}

If someone stumbles across this question, here is how i solved it:

Read (the async part is pretty ugly, but I don't know how to add a 'preferenceChangeD' event)

private async void preferenceChange(object sender, Preference.PreferenceChangeEventArgs e)
{
     await System.Threading.Tasks.Task.Delay(100);

     List<string> sList = new List<string>();
     ICollection<string> selectedValues = mslp_dutyMarks.Values;
     foreach(string x in selectedValues)
          sList.Add(x);
}

Write

mslp_dutyMarks.Values = new List<string> { "A", "B", "C" };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM