下面列出了android.preference.ListPreference#getEntries ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String stringValue = newValue.toString();
Log.v(LOG_TAG, "String Value: " + stringValue);
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
CharSequence[] labels = listPreference.getEntries();
Log.v(LOG_TAG, "Labels: " + labels.length);
preference.setSummary(labels[prefIndex]);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
/**
* This method is called when the user has changed a Preference.
* Update the displayed preference summary (the UI) after it has been changed.
* @param preference the changed Preference
* @param value the new value of the Preference
* @return True to update the state of the Preference with the new value
*/
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
// Update the summary of a ListPreference using the label
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
CharSequence[] labels = listPreference.getEntries();
preference.setSummary(labels[prefIndex]);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
/**
* set lowBatPollInterval to normal poll interval at least
* and adapt the selectable values
*
* @param pollIntervalPref
* @param lowBatPollIntervalPref
*/
private void setMinBatPollIntervall(ListPreference pollIntervalPref, ListPreference lowBatPollIntervalPref) {
final String currentValue = lowBatPollIntervalPref.getValue();
final int pollIntervalPos = (pollIntervalPref.findIndexOfValue(pollIntervalPref.getValue()) >= 0?pollIntervalPref.findIndexOfValue(pollIntervalPref.getValue()):0),
length = pollIntervalPref.getEntries().length;
CharSequence[] entries = new String[length - pollIntervalPos],
entryValues = new String[length - pollIntervalPos];
// generate temp Entries and EntryValues
for(int i = pollIntervalPos; i < length; i++) {
entries[i - pollIntervalPos] = pollIntervalPref.getEntries()[i];
entryValues[i - pollIntervalPos] = pollIntervalPref.getEntryValues()[i];
}
lowBatPollIntervalPref.setEntries(entries);
lowBatPollIntervalPref.setEntryValues(entryValues);
// and set the correct one
if (lowBatPollIntervalPref.findIndexOfValue(currentValue) == -1) {
lowBatPollIntervalPref.setValueIndex(0);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_video_player);
// set up the list of available video resolutions
VideoResolution.setupListPreferences((ListPreference) findPreference(getString(R.string.pref_key_preferred_res)));
// if we are running an OSS version, then remove the last option (i.e. the "official" player
// option)
if (BuildConfig.FLAVOR.equals("oss")) {
final ListPreference videoPlayersListPref = (ListPreference) getPreferenceManager().findPreference(getString(R.string.pref_key_choose_player));
final CharSequence[] videoPlayersList = videoPlayersListPref.getEntries();
CharSequence[] modifiedVideoPlayersList = Arrays.copyOf(videoPlayersList, videoPlayersList.length - 1);
videoPlayersListPref.setEntries(modifiedVideoPlayersList);
}
Preference creditsPref = findPreference(getString(R.string.pref_key_switch_volume_and_brightness));
creditsPref.setOnPreferenceClickListener(preference -> {
SkyTubeApp.getSettings().showTutorialAgain();
return true;
});
}
private void setSummary(PreferenceManager prefMng, String key, String value/*, Context context*/)
{
SharedPreferences preferences = prefMng.getSharedPreferences();
if (key.equals(PREF_EVENT_PERIPHERAL_ENABLED)) {
SwitchPreferenceCompat preference = prefMng.findPreference(key);
if (preference != null) {
GlobalGUIRoutines.setPreferenceTitleStyleX(preference, true, preferences.getBoolean(key, false), false, false, false);
}
}
if (key.equals(PREF_EVENT_PERIPHERAL_TYPE))
{
ListPreference listPreference = prefMng.findPreference(key);
if (listPreference != null) {
int index = listPreference.findIndexOfValue(value);
CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null;
listPreference.setSummary(summary);
}
}
}
static void updateListPreferenceSummaryToCurrentValue(final String prefKey,
final PreferenceScreen screen) {
// Because the "%s" summary trick of {@link ListPreference} doesn't work properly before
// KitKat, we need to update the summary programmatically.
final ListPreference listPreference = (ListPreference)screen.findPreference(prefKey);
if (listPreference == null) {
return;
}
final CharSequence[] entries = listPreference.getEntries();
final int entryIndex = listPreference.findIndexOfValue(listPreference.getValue());
listPreference.setSummary(entryIndex < 0 ? null : entries[entryIndex]);
}
static void updateListPreferenceSummaryToCurrentValue(final String prefKey,
final PreferenceScreen screen) {
// Because the "%s" summary trick of {@link ListPreference} doesn't work properly before
// KitKat, we need to update the summary programmatically.
final ListPreference listPreference = (ListPreference)screen.findPreference(prefKey);
if (listPreference == null) {
return;
}
final CharSequence entries[] = listPreference.getEntries();
final int entryIndex = listPreference.findIndexOfValue(listPreference.getValue());
listPreference.setSummary(entryIndex < 0 ? null : entries[entryIndex]);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
ListPreference languagePref = (ListPreference) findPreference("app_language");
CharSequence[] entries = languagePref.getEntries();
int index = languagePref.findIndexOfValue(
sharedPreferences.getString("app_language", "")
);
languagePref.setSummary(entries[index]);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
switch (s) {
case "app_language":
ListPreference languagePref = (ListPreference) findPreference(s);
CharSequence[] entries = languagePref.getEntries();
String languageCode = sharedPreferences.getString("app_language", "zh_CN");
int index = languagePref.findIndexOfValue(languageCode);
CharSequence languageName = entries[index];
languagePref.setSummary(languageName);
break;
}
}
static void updateListPreferenceSummaryToCurrentValue(final String prefKey,
final PreferenceScreen screen) {
// Because the "%s" summary trick of {@link ListPreference} doesn't work properly before
// KitKat, we need to update the summary programmatically.
final ListPreference listPreference = (ListPreference)screen.findPreference(prefKey);
if (listPreference == null) {
return;
}
final CharSequence entries[] = listPreference.getEntries();
final int entryIndex = listPreference.findIndexOfValue(listPreference.getValue());
listPreference.setSummary(entryIndex < 0 ? null : entries[entryIndex]);
}
private boolean updateListPreferenceSummary(
ListPreference listPreference, String newValue) {
int index = listPreference.findIndexOfValue(newValue);
CharSequence[] entries = listPreference.getEntries();
if (index < 0 || index >= entries.length) {
LogUtils.log(this, Log.ERROR,
"Unknown preference value for %s: %s",
listPreference.getKey(), newValue);
return false;
}
listPreference.setSummary(entries[index]);
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]);
}
// 设置hosts
if (preference.getKey().equals("system_host")) {
DeviceUtils.changeHost(((SysApplication)getApplication()).proxy,newValue.toString());
hostPreference.setSummary(getHost());
}
// 重启抓包进程
if (preference.getKey().equals("enable_filter")) {
Toast.makeText(this, "重启程序后生效", Toast.LENGTH_SHORT).show();
// ((SysApplication)getApplication()).stopProxy();
// ((SysApplication)getApplication()).startProxy();
// Toast.makeText(this, "抓包进程重启完成", Toast.LENGTH_SHORT).show();
}
return true;
}
@Override
public void onClick(DialogInterface dialogInterface, int i) {
resetKeymap();
KeyComboModel keyComboModel = getKeyComboManager().getKeyComboModel();
// Update preference.
String preferenceKeyForTriggerModifier =
keyComboModel.getPreferenceKeyForTriggerModifier();
ListPreference listPreference =
(ListPreference) findPreference(preferenceKeyForTriggerModifier);
listPreference.setValue(triggerModifierToBeSet);
// Update KeyComboModel.
keyComboModel.notifyTriggerModifierChanged();
// Update UI.
Set<String> keySet =
getKeyComboManager().getKeyComboModel().getKeyComboCodeMap().keySet();
for (String key : keySet) {
KeyboardShortcutDialogPreference preference =
(KeyboardShortcutDialogPreference) findPreference(key);
preference.onTriggerModifierChanged();
}
// Announce that trigger modifier has changed.
CharSequence[] entries = listPreference.getEntries();
CharSequence newTriggerModifier =
entries[listPreference.findIndexOfValue(triggerModifierToBeSet)];
announceText(
getString(R.string.keycombo_menu_announce_new_trigger_modifier, newTriggerModifier),
getActivity());
triggerModifierToBeSet = null;
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
// Damage control if user inputs an empty profile name
if(stringValue.isEmpty() && preference.getKey().equals("profile_name")) {
stringValue = name;
listener.setEmptyTitle(name);
}
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);
CharSequence summary = index >= 0 ? listPreference.getEntries()[index] : null;
// Set the summary to reflect the new value.
if(summary == null) {
stringValue = listener.generateBlurb(preference.getKey(), stringValue);
preference.setSummary(stringValue);
} else
preference.setSummary(summary);
} else {
if((preference.getKey().equals("density") && !stringValue.isEmpty())
|| preference.getKey().equals("size"))
stringValue = listener.generateBlurb(preference.getKey(), stringValue);
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
static void updateListPreferenceSummaryToCurrentValue(final String prefKey,
final PreferenceScreen screen) {
// Because the "%s" summary trick of {@link ListPreference} doesn't work properly before
// KitKat, we need to update the summary programmatically.
final ListPreference listPreference = (ListPreference)screen.findPreference(prefKey);
if (listPreference == null) {
return;
}
final CharSequence entries[] = listPreference.getEntries();
final int entryIndex = listPreference.findIndexOfValue(listPreference.getValue());
listPreference.setSummary(entryIndex < 0 ? null : entries[entryIndex]);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_updates);
SensorManager senSensorManager = (SensorManager) getActivity()
.getSystemService(Context.SENSOR_SERVICE);
Sensor senAccelerometer = senSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
boolean deviceHasAccelerometer = senSensorManager.registerListener(
sensorListener,
senAccelerometer,
SensorManager.SENSOR_DELAY_FASTEST);
senSensorManager.unregisterListener(sensorListener);
Preference updateWidgetUpdatePref = findPreference(Constants.KEY_PREF_LOCATION_AUTO_UPDATE_PERIOD);
ListPreference updateListPref = (ListPreference) updateWidgetUpdatePref;
int accIndex = updateListPref.findIndexOfValue("0");
if (!deviceHasAccelerometer) {
CharSequence[] entries = updateListPref.getEntries();
CharSequence[] newEntries = new CharSequence[entries.length - 1];
int i = 0;
int j = 0;
for (CharSequence entry : entries) {
if (i != accIndex) {
newEntries[j] = entries[i];
j++;
}
i++;
}
updateListPref.setEntries(newEntries);
if (updateListPref.getValue() == null) {
updateListPref.setValueIndex(updateListPref.findIndexOfValue("60") - 1);
}
} else if (updateListPref.getValue() == null) {
updateListPref.setValueIndex(accIndex);
}
LocationsDbHelper locationsDbHelper = LocationsDbHelper.getInstance(getActivity());
List<Location> availableLocations = locationsDbHelper.getAllRows();
boolean oneNoautoLocationAvailable = false;
for (Location location: availableLocations) {
if (location.getOrderId() != 0) {
oneNoautoLocationAvailable = true;
break;
}
}
if (!oneNoautoLocationAvailable) {
ListPreference locationPreference = (ListPreference) findPreference("location_update_period_pref_key");
locationPreference.setEnabled(false);
}
ListPreference locationAutoPreference = (ListPreference) findPreference("location_auto_update_period_pref_key");
locationAutoPreference.setEnabled(locationsDbHelper.getLocationByOrderId(0).isEnabled());
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
mRecoverSavedInstance = true;
mEnclosingActivity = getActivity();
Themer.applyTheme(mEnclosingActivity);
Languager.setLanguage(mEnclosingActivity);
mServiceIntent = new Intent(mEnclosingActivity, StorageAndControlService.class);
addPreferencesFromResource(R.xml.alarm_settings);
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(mEnclosingActivity);
mExchangeListPref = (ListPreference) findPreference(PREF_KEY_EXCHANGE);
mSpecificCat = (PreferenceCategory) findPreference(PREF_KEY_SPECIFIC);
mPairListPref = (ListPreference) findPreference(PREF_KEY_PAIR);
mLastValuePref = (EditTextPreference) findPreference(PREF_KEY_LAST_VALUE);
mAlarmTypePref = (ListPreference) findPreference(PREF_KEY_TYPE);
mAlarmAlertTypePref = (ListPreference) findPreference(PREF_KEY_ALARM_ALERT_TYPE);
mAlertSoundPref = (ThemableRingtonePreference) findPreference(PREF_KEY_ALARM_ALERT_SOUND);
mVibratePref = (ListPreference) findPreference(PREF_KEY_ALARM_VIBRATE);
mUpperLimitPref = (EditTextPreference) findPreference(PREF_KEY_UPPER_VALUE);
mLowerLimitPref = (EditTextPreference) findPreference(PREF_KEY_LOWER_VALUE);
mIsPercentPref = (CheckBoxPreference) findPreference(PREF_KEY_CHANGE_IN_PERCENTAGE);
mChangePref = (EditTextPreference) findPreference(PREF_KEY_CHANGE_VALUE);
mTimeFramePref = (EditTextPreference) findPreference(PREF_KEY_TIME_FRAME);
mUpdateIntervalPref = (EditTextPreference) findPreference(PREF_KEY_UPDATE_INTERVAL);
mSnoozeOnRetracePref = (CheckBoxPreference) findPreference(PREF_KEY_SNOOZE_ON_RETRACE);
Preference[] prefs = { mExchangeListPref, mPairListPref, mLastValuePref, mAlarmTypePref, mUpperLimitPref,
mLowerLimitPref, mIsPercentPref, mChangePref, mTimeFramePref, mUpdateIntervalPref, mAlarmAlertTypePref,
mAlertSoundPref, mVibratePref, mSnoozeOnRetracePref };
for (Preference pref : prefs) {
pref.setOnPreferenceChangeListener(mListener);
}
CharSequence[] entries = mAlarmAlertTypePref.getEntries();
entries[0] = mEnclosingActivity.getString(R.string.default_value, getDefaultAlertTypeName());
mAlarmAlertTypePref.setEntries(entries);
entries = mVibratePref.getEntries();
entries[0] = mEnclosingActivity.getString(R.string.default_value, getDefaultVibrateName());
mVibratePref.setEntries(entries);
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String preferenceKeyForTriggerModifier =
getKeyComboManager().getKeyComboModel().getPreferenceKeyForTriggerModifier();
if (preference instanceof KeyboardShortcutDialogPreference
&& newValue instanceof Long) {
KeyboardShortcutDialogPreference keyBoardPreference =
(KeyboardShortcutDialogPreference) preference;
keyBoardPreference.setKeyComboCode((Long) newValue);
keyBoardPreference.notifyChanged();
} else if (preference.getKey() != null
&& preference.getKey().equals(getString(R.string.pref_select_keymap_key))
&& newValue instanceof String) {
String newKeymap = (String) newValue;
// Do nothing if keymap is the same.
if (keymap.equals(newKeymap)) {
return false;
}
// Replace preference fragment.
TalkBackKeyboardShortcutPreferenceFragment fragment =
TalkBackKeyboardShortcutPreferenceFragment.createFor(newKeymap);
getFragmentManager()
.beginTransaction()
.replace(android.R.id.content, fragment)
.commit();
// Set new key combo model.
KeyComboManager keyComboManager = getKeyComboManager();
keyComboManager.setKeyComboModel(keyComboManager.createKeyComboModelFor(newKeymap));
// Announce new keymap.
announceText(
String.format(
getString(R.string.keycombo_menu_announce_active_keymap),
getKeymapName(newKeymap)),
getActivity());
} else if (preference.getKey() != null
&& preference.getKey().equals(preferenceKeyForTriggerModifier)
&& newValue instanceof String) {
triggerModifierToBeSet = (String) newValue;
ListPreference listPreference = (ListPreference) preference;
if (listPreference.getValue().equals(triggerModifierToBeSet)) {
return false;
}
CharSequence[] entries = listPreference.getEntries();
CharSequence newTriggerModifier =
entries[listPreference.findIndexOfValue(triggerModifierToBeSet)];
// Show alert dialog.
AlertDialog dialog =
new AlertDialog.Builder(getActivity())
.setTitle(R.string.keycombo_menu_alert_title_trigger_modifier)
.setMessage(
getString(
R.string.keycombo_menu_alert_message_trigger_modifier,
newTriggerModifier))
.setPositiveButton(
android.R.string.ok, chooseTriggerModifierConfirmDialogPositive)
.setNegativeButton(
android.R.string.cancel, chooseTriggerModifierConfirmDialogNegative)
.show();
focusCancelButton(dialog);
return false;
}
return true;
}
private void setListPreferenceData() {
ArrayList<FileItem>fileItems=FileItemContainer.getFileItems();
if(fileItems==null || fileItems.size()==0)
return;
@SuppressWarnings("deprecation")
ListPreference listPrefPrimary=(ListPreference) findPreference(getString(R.string.key_primary_text_selection));
CharSequence[] defaultEntries = listPrefPrimary.getEntries();
int defaultItemSize=defaultEntries.length;
/*oldItemSize=oldItemSize<=MainActivity.Total_Default_Quran_Texts ?
oldItemSize : MainActivity.Total_Default_Quran_Texts;*/
int totalItems=defaultItemSize+fileItems.size();
CharSequence[] newEntries=new CharSequence[totalItems];
CharSequence[] entryValues=new CharSequence[totalItems];
for(int i=0;i<defaultItemSize;i++){
newEntries[i]=defaultEntries[i];
entryValues[i]=Integer.toString(i);
}
for(int i=0,j=defaultItemSize;i<fileItems.size();i++){
newEntries[i+j]=fileItems.get(i).getFileAliasName();
entryValues[i+j]=Integer.toString(i+j);
}
listPrefPrimary.setEntries(newEntries);
listPrefPrimary.setEntryValues(entryValues);
@SuppressWarnings("deprecation")
ListPreference listPrefSecondary=(ListPreference) findPreference(getString(R.string.key_secondary_text_selection));
CharSequence[] newEntriesSecondary=newEntries.clone();
newEntriesSecondary[0]="No Secondary Text";
listPrefSecondary.setEntries(newEntriesSecondary);
listPrefSecondary.setEntryValues(entryValues);
Log.i("update", "list pref updated");
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if(key.equals(PREF_KEY_EXCHANGE)) {
ListPreference listPref = (ListPreference) preference;
mExchangeIndex = listPref.findIndexOfValue((String) newValue);
String exchangeName = (String) listPref.getEntries()[mExchangeIndex];
listPref.setSummary(exchangeName);
mPairIndex = 0;
updatePairsList((String) newValue, exchangeName, null);
} else if(key.equals(PREF_KEY_PAIR)) {
mPairIndex = Integer.parseInt((String) newValue);
preference.setSummary(mPairs.get(mPairIndex).toString());
updateDependentOnPairAux();
} else if(key.equals(PREF_KEY_TYPE)) {
Fragment creationFrag;
Bundle args = new Bundle();
args.putInt("exchangeIndex", mExchangeIndex);
args.putInt("pairIndex", mPairIndex);
args.putString("alertType", mAlarmAlertTypePref.getValue());
args.putString("alertSound", mAlertSoundPref.getValue());
args.putString("vibrate", mVibratePref.getValue());
if(newValue.equals(PREF_VALUE_PRICE_CHANGE)) {
creationFrag = new PriceChangeAlarmCreationFragment();
} else { // newValue.equals(PREF_VALUE_PRICE_HIT))
creationFrag = new PriceHitAlarmCreationFragment();
}
creationFrag.setArguments(args);
mEnclosingActivity.getFragmentManager().beginTransaction().replace(android.R.id.content, creationFrag).commit();
} else if(key.equals(PREF_KEY_UPDATE_INTERVAL)) {
preference.setSummary(mEnclosingActivity.getString(R.string.seconds_abbreviation, newValue));
} else if(key.equals(PREF_KEY_ALARM_ALERT_TYPE)) {
ListPreference alertTypePref = (ListPreference) preference;
String alertType = (String) newValue;
alertTypePref.setSummary(alertTypePref.getEntries()[alertTypePref.findIndexOfValue(alertType)]);
// Change selectable ringtones according to the alert type
mAlertSoundPref.setRingtoneType(alertType);
mAlertSoundPref.setDefaultValue();
} else if(key.equals(PREF_KEY_ALARM_ALERT_SOUND)) {
// Nothing to do.
} else if(key.equals(PREF_KEY_ALARM_VIBRATE)) {
ListPreference vibratePref = (ListPreference) preference;
vibratePref.setSummary(vibratePref.getEntries()[vibratePref.findIndexOfValue((String) newValue)]);
} else if(key.equals(PREF_KEY_SNOOZE_ON_RETRACE)) {
// Nothing to do.
} else {
Log.d("No behavior for " + key);
}
return true;
}