How to fill ListPreference dynamically when onPreferenceClick is triggered?

前端 未结 3 1835
庸人自扰
庸人自扰 2020-12-13 09:55

I have a preference activity that has a language as ListPreference which displays the available language list. I can fill the list when onCreate is

3条回答
  •  甜味超标
    2020-12-13 10:19

    You are getting the exception because your ListPreference object is not initialized - you either need to set entries and entryValues attributes in your XML or do it programatically in onCreate().

    If if you need to change the items in the list dynamically after the initial ListPreference object has been initialized then you will need to attach the OnPreferenceClickListener directly to the ListPreference object. Use the key you have specified in the XML to get a handle to the preference.

    Since the code to populate the entries and entryValues arrays will have to be run both in onCreate() and in onPreferenceClick, it makes sense to extract it to a separate method - setListPreferenceData() in order to avoid duplication.

    public class SettingsActivity extends PreferenceActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            try {
                addPreferencesFromResource(R.xml.settings);
            } catch (Exception e) {
    
            }
    
            final ListPreference listPreference = (ListPreference) findPreference("language");
    
            // THIS IS REQUIRED IF YOU DON'T HAVE 'entries' and 'entryValues' in your XML
            setListPreferenceData(listPreference);
    
            listPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
    
                    setListPreferenceData(listPreference);
                    return false;
                }
            });
        }
    
        protected static void setListPreferenceData(ListPreference lp) {
                CharSequence[] entries = { "English", "French" };
                CharSequence[] entryValues = {"1" , "2"};
                lp.setEntries(entries);
                lp.setDefaultValue("1");
                lp.setEntryValues(entryValues);
        }
    }
    

    Here is another example from google's DeskClock app:

提交回复
热议问题