One missing feature in the preferences activity in Android applications is to display the selected value of a ListPreference. By default, to view the selected value of a ListPreference you must click the preference and see what's selected in the combo box.
Here's an example how to create a preferences activity which displays the selected value of any number of ListPreferences in the activity.
public class MyPreferenceActivity extends PreferenceActivity 
  implements SharedPreferences.OnSharedPreferenceChangeListener {
    
    private ArrayList<ListPreference> mListPreferences;
    private String[] mListPreferencesKeys = new String[] {
     "prefKey1", // The 'android:key' value of the ListPreference
     "prefKey2"  // The 'android:key' value of the ListPreference
     ....
     ....
     ....
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        
        mListPreferences = new ArrayList<ListPreference>();
        SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
        sharedPrefs.registerOnSharedPreferenceChangeListener(this);
        for (String prefKey : mListPreferencesKeys) {
         ListPreference pref = (ListPreference)getPreferenceManager().findPreference(prefKey);
         mListPreferences.add(pref);
         onSharedPreferenceChanged(sharedPrefs, prefKey);
        }
    }
    @Override
 public void onSharedPreferenceChanged(SharedPreferences pref, String prefKey) {
     for (ListPreference listPref : mListPreferences) {
      if (listPref.getKey().equals(prefKey))
       listPref.setSummary(listPref.getEntry());
     }
 }
}
Notes:
- This code will update the values if the user selects a new value
 
- If you're defining preferences keys in the strings.xml file, make the mListPreferencesKeys list an integer list, and get the string at run time using 'getString'
 
 
No comments:
Post a Comment