Display ListPreference selected item on summary

Refer to the article "Implement ListPreference in PreferenceFragment", the default display on summary field is hard-coded in /res/xml/preferences.xml. Such that, the user cannot know the current selected item of ListPreference, without open the ListPreference dialog.

To update summary of ListPreference programmatically, call ListPreference.setSummary().

Display ListPreference selected item on summary
Display ListPreference selected item on summary


Implement updateListPrefSummary_PREF_LIST() to update summary of ListPreference with key="PREF_LIST", call it in onCreate() in fragment start-up. And also implement OnSharedPreferenceChangeListener to call it when ListPreference with key="PREF_LIST" changed. Register and Unregister in onResume() and onPause().

package com.example.androidpreferencefragment;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.PreferenceFragment;

public class PrefFragment extends PreferenceFragment
implements OnSharedPreferenceChangeListener{

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);

updateListPrefSummary_PREF_LIST();
}

@Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}

@Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}

//Apply for ListPreference with key="PREF_LIST"
private void updateListPrefSummary_PREF_LIST(){
ListPreference preference = (ListPreference)findPreference("PREF_LIST");
CharSequence entry = ((ListPreference) preference).getEntry();
preference.setSummary("current selection: " + entry);
}

@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {

//if changed SharedPreference is ListPreference with key="PREF_LIST",
// update summary
if(key.equals("PREF_LIST")){
updateListPrefSummary_PREF_LIST();
};

}

}


0 Response to "Display ListPreference selected item on summary"

Posting Komentar