Using PreferenceFragment and JAVA , rather than PreferenceActivity and XML , as shown in https://stackoverflow.com/a/126754/ ... on which this answer is based on:
If you want to dynamically change the items in the list after initializing the original ListPreference object, you will need to bind OnPreferenceClickListener directly to the ListPreference object. Use the key you have specified in the JAVA source (like CUSTOM_LIST ) to get a preference descriptor.
Since the code for filling in the arrays of entries and entryValues must be run both in onCreate() and in onPreferenceClick , it makes sense to extract it in a separate method - setListPreferenceData() , to avoid duplication.
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class myCustomPreferenceFragment extends PreferenceFragment { final private String CUSTOM_LIST= "custom_list"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_custom_frag); PreferenceCategory targetCategory = (PreferenceCategory) findPreference("CUSTOM_FRAG"); final ListPreference lp = setListPreferenceData((ListPreference) findPreference(CUSTOM_LIST), getActivity()); lp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { setListPreferenceData(lp, getActivity()); return false; } }); setHasOptionsMenu(true); targetCategory.addPreference(lp); bindPreferenceSummaryToValue(targetCategory); bindPreferenceSummaryToValue(lp); } protected ListPreference setListPreferenceData(ListPreference lp, Activity mActivity) { CharSequence[] entries = { "One", "Two", "Three" }; CharSequence[] entryValues = { "1", "2", "3" }; if(lp == null) lp = new ListPreference(mActivity); lp.setEntries(entries); lp.setDefaultValue("1"); lp.setEntryValues(entryValues); lp.setTitle("Number Of blahs"); lp.setSummary(lp.getEntry()); lp.setDialogTitle("Number of Blah objects"); lp.setKey(CUSTOM_LIST); return lp; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { startActivity(new Intent(getActivity(), SettingsActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
XML layout:
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:key="CUSTOM_FRAG" android:title="Some Options"> </PreferenceCategory> </PreferenceScreen>
CrandellWS Apr 28 '16 at 3:32 2016-04-28 03:32
source share