下面列出了怎么用android.preference.ListPreference的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(index >= 0? listPreference.getEntries()[index] : null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(" " + stringValue);
}
return true;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity activity = getActivity();
sLocaleManager = LocaleManager.getInstance(activity, false);
addPreferencesFromResource(R.xml.settings);
PreferenceScreen root = getPreferenceScreen();
// System time zone
Preference timezonePref = root.findPreference("key_time_zone");
timezonePref.setSummary(getGmtOffSet(activity));
// Language settings
ListPreference languagePref = (ListPreference) root.findPreference("key_locale");
languagePref.setEntryValues(LocaleManager.LOCALES);
languagePref.setValueIndex(sLocaleManager.getLanguageIndex());
languagePref.setSummary(languagePref.getEntry());
languagePref.setOnPreferenceChangeListener(this);
}
private static void setListPreferenceIconsPacksData(ListPreference lp, Context context) {
IconsHandler iph = GlobState.getIconsHandler(context);
iph.loadAvailableIconsPacks();
Map<String, String> iconsPacks = iph.getAllIconsThemes();
CharSequence[] entries = new CharSequence[iconsPacks.size()];
CharSequence[] entryValues = new CharSequence[iconsPacks.size()];
int i = 0;
for (String packageIconsPack : iconsPacks.keySet()) {
entries[i] = iconsPacks.get(packageIconsPack);
entryValues[i] = packageIconsPack;
i++;
}
lp.setEntries(entries);
lp.setDefaultValue(IconsHandler.DEFAULT_PACK);
lp.setEntryValues(entryValues);
}
@SuppressWarnings("deprecation")
private void configSensorType(boolean hasAntSupport) {
ListPreference preference = (ListPreference) findPreference(
getString(R.string.sensor_type_key));
String value = PreferencesUtils.getString(
this, R.string.sensor_type_key, PreferencesUtils.SENSOR_TYPE_DEFAULT);
String[] options = getResources().getStringArray(
hasAntSupport ? R.array.sensor_type_all_options : R.array.sensor_type_bluetooth_options);
String[] values = getResources().getStringArray(
hasAntSupport ? R.array.sensor_type_all_values : R.array.sensor_type_bluetooth_values);
if (!hasAntSupport && value.equals(R.string.sensor_type_value_ant)) {
value = PreferencesUtils.SENSOR_TYPE_DEFAULT;
PreferencesUtils.setString(this, R.string.sensor_type_key, value);
}
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference pref, Object newValue) {
updateUiBySensorType((String) newValue);
return true;
}
};
configureListPreference(preference, options, options, values, value, listener);
}
@Override
public void onResume() {
super.onResume();
IconsHandler iph = GlobState.getIconsHandler(this.getActivity());
findPreference(getString(R.string.pref_key_icon_tint)).setEnabled(iph.isIconTintable());
ListPreference iconsPack = (ListPreference)findPreference(getString(R.string.pref_key_icons_pack));
setListPreferenceIconsPacksData(iconsPack, this.getActivity());
// iconsPack.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
// @Override
// public boolean onPreferenceChange(Preference preference, Object newValue) {
// getActivity().finish();
// return true;
// }
// });
prefs.registerOnSharedPreferenceChangeListener(this);
}
private void setRefreshSummary(String p_refreshInterval) {
ListPreference refreshPref = (ListPreference) findPreference("REFRESH_INTERVAL");
if (refreshPref.findIndexOfValue(p_refreshInterval) >= 0) {
CharSequence listDesc = refreshPref.getEntries()[refreshPref.findIndexOfValue(p_refreshInterval)];
refreshPref.setSummary(listDesc);
} else {
// not in the list (old value?)
int refresh_interval = 0;
try {
refresh_interval = Integer.valueOf(_sharedPreferences.getString("REFRESH_INTERVAL", "500"));
} catch (NumberFormatException nfe) {
refresh_interval = Constants.REFRESH_INTERVAL_DEFAULT;
}
refresh_interval = refresh_interval % 100000;
if (refresh_interval < 1000) {
refreshPref.setSummary(refresh_interval + " ms");
} else {
refreshPref.setSummary(refresh_interval/1000 + " s");
}
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
ListPreference speedListPreference = (ListPreference) findPreference("min_speed");
ListPreference effListPreference = (ListPreference) findPreference("default_efficiency");
//Statistics.setDefault_efficiency(Integer.valueOf(String.valueOf(effListPreference.getValue())));
//Statistics.setMin_speed(Integer.valueOf(String.valueOf(speedListPreference.getValue())));
speedListPreference.setValueIndex(3);
speedListPreference.setValue("4");
effListPreference.setValueIndex(7);
effListPreference.setValue("600");
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("min_speed"));
bindPreferenceSummaryToValue(findPreference("default_efficiency"));
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
if (preference instanceof ListPreference) {
String stringValue = value.toString();
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
}
// else {
// // For all other preferences, set the summary to the value's
// // simple string representation.
// preference.setSummary(stringValue);
// }
return true;
}
private static void configureAudioPreferences(final PreferenceScreen screen) {
ListPreference inputPreference = (ListPreference) screen.findPreference(Settings.PREF_INPUT_METHOD);
inputPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
updateAudioDependents(screen, (String) newValue);
return true;
}
});
// Scan each bitrate and determine if the device supports it
ListPreference inputQualityPreference = (ListPreference) screen.findPreference(Settings.PREF_INPUT_RATE);
String[] bitrateNames = new String[inputQualityPreference.getEntryValues().length];
for(int x=0;x<bitrateNames.length;x++) {
int bitrate = Integer.parseInt(inputQualityPreference.getEntryValues()[x].toString());
boolean supported = AudioRecord.getMinBufferSize(bitrate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT) > 0;
bitrateNames[x] = bitrate+"Hz" + (supported ? "" : " (unsupported)");
}
inputQualityPreference.setEntries(bitrateNames);
updateAudioDependents(screen, inputPreference.getValue());
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
private void entrySummary(String key) {
ListPreference preference = (ListPreference) findPreference(key);
if (preference == null) {
return;
}
preference.setSummary(preference.getEntry());
if (Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD.equals(key)) {
if ("0".equals(preference.getValue())) {
AppPreference.setNotificationEnabled(getActivity(), true);
AppPreference.setNotificationPresence(getActivity(), "permanent");
AppPreference.setRegularOnlyInterval(getActivity());
} else {
AppPreference.setNotificationEnabled(getActivity(), false);
AppPreference.setNotificationPresence(getActivity(), "when_updated");
NotificationManager notificationManager =
(NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
}
}
/**
* Set the entries for the given preference. The given preference needs
* to be a {@link ListPreference}
*/
private void setEntries(Preference preference)
{
if (!(preference instanceof ListPreference))
{
return;
}
ListPreference listPreference = (ListPreference) preference;
if (listPreference.getKey().equals(Keys.KEY_PICTURE_SIZE_BACK))
{
setEntriesForSelection(mPictureSizes.backCameraSizes, listPreference);
} else if (listPreference.getKey().equals(Keys.KEY_PICTURE_SIZE_FRONT))
{
setEntriesForSelection(mPictureSizes.frontCameraSizes, listPreference);
} else if (listPreference.getKey().equals(Keys.KEY_VIDEO_QUALITY_BACK))
{
setEntriesForSelection(mPictureSizes.videoQualitiesBack.orNull(), listPreference);
} else if (listPreference.getKey().equals(Keys.KEY_VIDEO_QUALITY_FRONT))
{
setEntriesForSelection(mPictureSizes.videoQualitiesFront.orNull(), listPreference);
}
}
@Override
public boolean onPreferenceChange(final Preference preference, final Object value) {
if (D) Log.d(TAG, "onPreferenceChange()");
final String stringValue = value.toString();
if (preference instanceof ListPreference) {
final ListPreference listPreference = (ListPreference) preference;
final int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
} else {
preference.setSummary(stringValue);
}
return true;
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
// For all preferences, set the summary to the value's
// simple string representation.
if(preference.getKey().equalsIgnoreCase(pref_posts_min_score) || preference.getKey().equalsIgnoreCase(pref_comments_min_score)) {
if (stringValue.isEmpty()) {
stringValue = "Show all submissions";
}
}else if(preference.getKey().equalsIgnoreCase(pref_comments_num_display)){
if(stringValue.isEmpty()){
stringValue = "200";
}else if(stringValue.equalsIgnoreCase("0")){
stringValue = "1";
}else if(Integer.parseInt(stringValue) > 500){
stringValue = "500";
}
}else if(preference.getKey().equalsIgnoreCase(pref_sync_period)){
stringValue = ((ListPreference)preference).getEntry().toString();
}
preference.setSummary(stringValue);
return true;
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
} else {
// For all other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
/**
* Configures the preferred units list preference.
*/
private void configUnitsListPreference() {
@SuppressWarnings("deprecation")
ListPreference listPreference = (ListPreference) findPreference(
getString(R.string.stats_units_key));
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference pref, Object newValue) {
boolean metricUnits = PreferencesUtils.STATS_UNITS_DEFAULT.equals((String) newValue);
configRateListPreference(metricUnits);
return true;
}
};
String value = PreferencesUtils.getString(
this, R.string.stats_units_key, PreferencesUtils.STATS_UNITS_DEFAULT);
String[] values = getResources().getStringArray(R.array.stats_units_values);
String[] options = getResources().getStringArray(R.array.stats_units_options);
configureListPreference(listPreference, options, options, values, value, listener);
}
/**
* Configures the track color mode preference.
*/
@SuppressWarnings("deprecation")
private void configTrackColorModePerference() {
ListPreference preference = (ListPreference) findPreference(
getString(R.string.track_color_mode_key));
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference pref, Object newValue) {
updateUiByTrackColorMode((String) newValue);
return true;
}
};
String value = PreferencesUtils.getString(
this, R.string.track_color_mode_key, PreferencesUtils.TRACK_COLOR_MODE_DEFAULT);
String[] values = getResources().getStringArray(R.array.track_color_mode_values);
String[] options = getResources().getStringArray(R.array.track_color_mode_options);
String[] summary = getResources().getStringArray(R.array.track_color_mode_summary);
configureListPreference(preference, summary, options, values, value, listener);
}
private void initializePreferredVideoFpsPreferences(ListPreference pref) {
List<CharSequence> entries = new ArrayList<CharSequence>();
List<CharSequence> values = new ArrayList<CharSequence>();
entries.add(getString(R.string.pref_none));
values.add("0");
for (int i = 5; i <= 30; i += 5) {
String str = Integer.toString(i);
entries.add(str);
values.add(str);
}
setListPreferenceValues(pref, entries, values);
String value = Integer.toString(mPrefs.getPreferredVideoFps());
if (value.equals("0")) {
value = getString(R.string.pref_none);
}
pref.setSummary(value);
pref.setValue(value);
}
private void initializeTransportPreference(ListPreference pref) {
List<CharSequence> entries = new ArrayList<CharSequence>();
List<CharSequence> values = new ArrayList<CharSequence>();
entries.add(getString(R.string.pref_transport_udp));
values.add(getString(R.string.pref_transport_udp_key));
entries.add(getString(R.string.pref_transport_tcp));
values.add(getString(R.string.pref_transport_tcp_key));
if (!getResources().getBoolean(R.bool.disable_all_security_features_for_markets)) {
entries.add(getString(R.string.pref_transport_tls));
values.add(getString(R.string.pref_transport_tls_key));
}
setListPreferenceValues(pref, entries, values);
if (! isNewAccount) {
pref.setSummary(mPrefs.getAccountTransportString(n));
pref.setDefaultValue(mPrefs.getAccountTransportKey(n));
pref.setValueIndex(entries.indexOf(mPrefs.getAccountTransportString(n)));
} else {
pref.setSummary(getString(R.string.pref_transport_udp));
pref.setDefaultValue(getString(R.string.pref_transport_udp));
pref.setValueIndex(entries.indexOf(getString(R.string.pref_transport_udp)));
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference instanceof ListPreference) {
//把preference这个Preference强制转化为ListPreference类型
ListPreference listPreference = (ListPreference) preference;
//获取ListPreference中的实体内容
CharSequence[] entries = listPreference.getEntries();
//获取ListPreference中的实体内容的下标值
int index = listPreference.findIndexOfValue((String) newValue);
//把listPreference中的摘要显示为当前ListPreference的实体内容中选择的那个项目
listPreference.setSummary(entries[index]);
if (preference.getKey().equals("warning_time")) {
int i = Integer.parseInt( listPreference.getEntryValues()[index].toString());
postMessage(MyService.DURATION_CHANGE_KEY, MyService.DURATION_CHANGE, i);
}
}
return true;
}
private static void updatePrefSummary(Preference pref) {
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry());
}
if (pref instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
if (pref.getKey().contains("password") || pref.getKey().contains("secret")) {
pref.setSummary("******");
} else if (editTextPref.getText() != null) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText());
} else {
for (PluginBase plugin : MainApp.getPluginsList()) {
plugin.updatePreferenceSummary(pref);
}
}
}
if (pref != null)
adjustUnitDependentPrefs(pref);
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list pref_general, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other pref_general, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
public static void setListPreferenceData(ListPreference p) {
final Type[] types = Type.values();
final CharSequence[] entries = new CharSequence[types.length];
final CharSequence[] entryValues = new CharSequence[types.length];
for (int i = 0; i < types.length; i++) {
// Not sure exactly of what the overhead of this will be
// perhaps we should save it to a cache...
final CalibrationAbstract plugin = getCalibrationPlugin(types[i]);
entries[i] = (plugin != null) ? plugin.getNiceNameAndDescription() : "None";
entryValues[i] = types[i].toString();
}
p.setEntries(entries);
p.setEntryValues(entryValues);
}
private static void loadPref_timeFormat(final Activity context, final ListPreference timeformatPref)
{
WidgetSettings.TimeFormatMode mode = WidgetSettings.loadTimeFormatModePref(context, 0);
int index = timeformatPref.findIndexOfValue(mode.name());
if (index < 0)
{
index = 0;
WidgetSettings.TimeFormatMode mode0 = mode;
mode = WidgetSettings.TimeFormatMode.values()[index];
Log.w("loadPref", "timeFormat not found (" + mode0 + ") :: loading " + mode.name() + " instead..");
}
timeformatPref.setValueIndex(index);
timeformatPref.setSummary(timeFormatPrefSummary(mode, context));
}
public void createOutputPortPreferences() {
String currentValue = null;
String currentLabel = null;
final List<String> entryNames = new ArrayList<String>();
final List<String> entryValues = new ArrayList<String>();
MidiPlayer midiPlayer = MidiPlayer.getInstance(this.findContext());
List<MidiOutputPort> outputPorts = midiPlayer.listOutputPorts();
for(MidiOutputPort outputPort : outputPorts) {
entryNames.add(outputPort.getName());
entryValues.add(outputPort.getKey());
if( midiPlayer.isOutputPortOpen(outputPort.getKey()) ) {
currentValue = outputPort.getKey();
currentLabel = outputPort.getName();
}
}
final ListPreference listPreference = (ListPreference) this.findPreference(TGTransportProperties.PROPERTY_MIDI_OUTPUT_PORT);
listPreference.setEntries(entryNames.toArray(new CharSequence[entryNames.size()]));
listPreference.setEntryValues(entryValues.toArray(new CharSequence[entryValues.size()]));
if( currentValue != null ) {
listPreference.setValue(currentValue);
}
listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object o) {
int index = ( o != null ? entryValues.indexOf(o.toString()) : -1);
String selectedLabel = ( index >= 0 ? entryNames.get(index) : null);
updatePreferenceSummary(preference, selectedLabel, R.string.preferences_midi_output_port_summary, R.string.preferences_midi_output_port_summary_empty);
return true;
}
});
updatePreferenceSummary(listPreference, currentLabel, R.string.preferences_midi_output_port_summary, R.string.preferences_midi_output_port_summary_empty);
}
protected static void setListPreferenceData(ListPreference lp, Context context) {
//TODO performance lost here
SettingsLoader settingslolo = new SettingsLoader(lp.getPreferenceManager().getSharedPreferences(), context);
CharSequence[] entries = settingslolo.getLastBooks();
CharSequence[] entryValues = settingslolo.getLastBooksValues();//{"2", "3", "4"};
lp.setEntries(entries);
lp.setDefaultValue("0");
lp.setEntryValues(entryValues);
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference instanceof RingtonePreference) {
if (TextUtils.isEmpty(stringValue)) {
preference.setSummary(R.string.pref_ringtone_silent);
} else {
Ringtone ringtone = RingtoneManager.getRingtone(
preference.getContext(), Uri.parse(stringValue));
if (ringtone == null) {
preference.setSummary(null);
} else {
String name = ringtone.getTitle(preference.getContext());
preference.setSummary(name);
}
}
} else {
preference.setSummary(stringValue);
}
return true;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
Preference pref = findPreference(key);
// Remove empty string settings
if (pref instanceof EditTextPreference)
if ("".equals(prefs.getString(key, null))) {
SharedPreferences.Editor edit = prefs.edit();
edit.remove(key);
edit.apply();
}
if (PREF_ENABLED.equals(key))
pref.setSummary(prefs.getBoolean(PREF_ENABLED, true) ? getString(R.string.summary_enabled) : null);
else if (PREF_TOAST.equals(key))
pref.setSummary(prefs.getBoolean(PREF_TOAST, true) ? getString(R.string.summary_toast) : null);
else if (PREF_ALTITUDE.equals(key))
pref.setSummary(prefs.getBoolean(PREF_ALTITUDE, true) ? getString(R.string.summary_altitude) : null);
else if (PREF_ACCURACY.equals(key))
pref.setTitle(getString(R.string.title_accuracy, prefs.getString(key, DEFAULT_ACCURACY)));
else if (PREF_TIMEOUT.equals(key))
pref.setTitle(getString(R.string.title_timeout, prefs.getString(key, DEFAULT_TIMEOUT)));
else if (PREF_KNOWN.equals(key)) {
ListPreference lpref = (ListPreference) pref;
int index = lpref.findIndexOfValue(prefs.getString(key, DEFAULT_KNOWN));
pref.setTitle(getString(R.string.title_known, lpref.getEntries()[index]));
}
}