androidpreferenceswitchpreference

Programatic SwitchPreference Always Unchecked


I added 3 switch preference in a PreferenceCategory programmatically.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:persistent="true">

    <PreferenceCategory
        android:key="my_key"
        android:title="TEST" />
</PreferenceScreen>

Here is the code for adding switch preferences.

PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("my_key");
for (int i = 0; i < 3; i++) {
    SwitchPreference switchPreference = new SwitchPreference(getActivity());
    switchPreference.setTitle(title);
    switchPreference.setKey(key);
    switchPreference.setDefaultValue(true);
    switchPreference.setChecked(true);

    preferenceGroup.addPreference(switchPreference);
}

The screen shows like below. They're all unchecked. Does anyone know how to fix it? Thanks a lot!

enter image description here


Solution

  • Fixed by setting the default value programmatically.