91378246
91378246

Reputation: 377

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:

preference change

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

Upvotes: 0

Views: 207

Answers (3)

Grace Feng
Grace Feng

Reputation: 16652

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);
        }
    }
}

Upvotes: 1

91378246
91378246

Reputation: 377

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" };

Upvotes: 0

Jason
Jason

Reputation: 89102

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
}

Upvotes: 0

Related Questions