How do I programmatically add EditTextPreferences to my PreferenceFragment?

我与影子孤独终老i 提交于 2019-12-03 12:55:57

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:

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

</PreferenceScreen>

Hope that helps someone.

I don't know if it works in the onCreateView method but it does in the onViewCreated. Here is my code (Inside a subclass of PreferenceFragment):

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    this.getPreferenceScreen().addPreference(new EditTextPreference(getActivity()));
}

Here is the code to create a PreferenceFragment programmatically:

public class MyPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getActivity());
        setPreferenceScreen(screen);

        EditTextPreference preference = new EditTextPreference(screen.getContext());
        preference.setKey("EditTextPreference");
        preference.setTitle("Edit Text Preference");
        preference.setSummary("Click the preference to edit text.");
        screen.addPreference(preference);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!