How do I programmatically add EditTextPreferences to my PreferenceFragment?

前端 未结 3 2112
北荒
北荒 2021-02-15 14:36

I am new to Android, so I need a little guidance on how to programmatically add EditTextPreference objects to my PreferenceFragment

3条回答
  •  醉梦人生
    2021-02-15 14:59

    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.

提交回复
热议问题