I want to
- create a
SwitchPreference
programmatically - set
setChecked(true)
on it - 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.
It is checked on my machine. Concerning the state after clicking on it you are totally right. That's because you are returning
false
fromonPreferenceChange()
callback.Documentation of
onPreferenceChange()
:So, I've only changed
false
totrue
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.