Search code examples
androidandroid-support-libraryandroid-preferencesandroid-preference-v14

SwitchPreference create programmatically, setChecked not working


I want to

  1. create a SwitchPreference programmatically
  2. set setChecked(true) on it
  3. add it to a PreferenceGroup

1 and 3 work fine, but after 3 the SwitchPreference is not checked and clicks on the toggle have no effect (can't be 'turned on'/ checked).

Here's my PreferenceFragment:

public class MyPrefFragment extends PreferenceFragment {
    @Override
    public void onCreatePreferences(final Bundle savedInstanceState, final String rootKey) {

        addPreferencesFromResource(R.xml.prefs);

        PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("pref_cat_1");

        SwitchPreference switchPreference = new SwitchPreference(getActivity());
        switchPreference.setTitle("new");
        switchPreference.setChecked(true);
        switchPreference.setDefaultValue(true);

        switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(final Preference preference, final Object newValue) {

                Toast.makeText(getActivity(), newValue.toString(), Toast.LENGTH_SHORT).show();

                return false;
            }
        });

        preferenceGroup.addPreference(switchPreference);

    }
}

and my PreferenceScreen:

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

    <PreferenceCategory android:title="cat_one">

        <SwitchPreference
            android:key="pref_1"
            android:defaultValue="false"
            android:title="fest"/>

    </PreferenceCategory>

    <PreferenceCategory
        android:key="pref_cat_1"
        android:title="category"/>

</PreferenceScreen>

How can I properly setChecked(true) on a SwitchPreference that was created programmatically?

Test project is on Github.


Solution

  • The SwitchPreference is not checked and clicks on the toggle have no effect.

    It is checked on my machine. Concerning the state after clicking on it you are totally right. That's because you are returning false from onPreferenceChange() callback.

    Documentation of onPreferenceChange():

    Returns: true to update the state of the Preference with the new value.

    So, I've only changed false to true and it works as expected.

    EDIT

    I was running API 25 tablet emulator. Then ran on API 22 emulator, and it didn't work. It's very strange, that it runs as expected only on API 25.