I am new to Android, so I need a little guidance on how to programmatically add EditTextPreference objects to my PreferenceFragment
You can add preferences, e.g. EditTextPreference, CheckBox, etc, programmatically in the "onCreate" method of the PreferenceFragment.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load "dummy" (empty) preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_channelconfig);
PreferenceScreen screen = this.getPreferenceScreen(); // "null". See onViewCreated.
// Create the Preferences Manually - so that the key can be set programatically.
PreferenceCategory category = new PreferenceCategory(screen.getContext());
category.setTitle("Channel Configuration");
screen.addPreference(category);
CheckBoxPreference checkBoxPref = new CheckBoxPreference(screen.getContext());
checkBoxPref.setKey(channelConfig.getName() + "_ENABLED");
checkBoxPref.setTitle(channelConfig.getShortname() + "Enabled");
checkBoxPref.setSummary(channelConfig.getDescription());
checkBoxPref.setChecked(channelConfig.isEnabled());
category.addPreference(checkBoxPref);
}
The crucial step is the addPreferencesFromResource(...)
, with a dummy xml to attach an empty PreferenceScreen to the fragment. Without this, there is no "top-level Preference that is the root of a Preference hierarchy", thus this.getPreferenceScreen()
returns Null.
The XML I used was just:
Hope that helps someone.