下面列出了怎么用android.preference.Preference的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Configures a list preference.
*
* @param listPreference the list preference
* @param summary the summary array
* @param options the options array
* @param values the values array
* @param value the value
* @param listener optional listener
*/
protected void configureListPreference(ListPreference listPreference, final String[] summary,
final String[] options, final String[] values, String value,
final OnPreferenceChangeListener listener) {
listPreference.setEntryValues(values);
listPreference.setEntries(options);
listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference pref, Object newValue) {
updatePreferenceSummary(pref, summary, values, (String) newValue);
if (listener != null) {
listener.onPreferenceChange(pref, newValue);
}
return true;
}
});
updatePreferenceSummary(listPreference, summary, values, value);
if (listener != null) {
listener.onPreferenceChange(listPreference, value);
}
}
@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 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
@Deprecated
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
// TODO clean this up a bunch.
Log.i(TAG, "User clicked " + preference.getTitle());
if (preference.getKey().equals("choose_music_directory_prompt")) {
final File path = Utils.getRootStorageDirectory();
DirectoryPickerOnClickListener picker = new DirectoryPickerOnClickListener(
this, path);
picker.showDirectoryPicker();
Log.i(TAG, "User selected " + picker.path);
return true;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public boolean onPreferenceTreeClick(PreferenceScreen preferencescreen, Preference preference)
{
if (preference.getKey().equals("settings_bracelet_reset"))
{
b();
return true;
}
if (!preference.getKey().equals("settings_fw_upgrade")) goto _L2; else goto _L1
_L1:
e();
_L4:
return super.onPreferenceTreeClick(preferencescreen, preference);
_L2:
if (preference.getKey().equals("settings_push_goals_progress"))
{
c();
}
if (true) goto _L4; else goto _L3
_L3:
}
@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 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 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);
}
private void setPreferenceSummary(String key, String value) {
if (DEBUG) Log.d(TAG, "SettingsFragment.setPreferenceSummary(): Setting summary for " + key + " and value " + value);
String summary = value;
if (key.equals(AmuleRemoteApplication.AC_SETTING_AUTOREFRESH_INTERVAL)) {
summary = getString(R.string.settings_summary_client_autorefresh_interval, Integer.parseInt(value));
} else if (key.equals(AmuleRemoteApplication.AC_SETTING_CONNECT_TIMEOUT)) {
summary = getString(R.string.settings_summary_client_connect_timeout, Integer.parseInt(value));
} else if (key.equals(AmuleRemoteApplication.AC_SETTING_READ_TIMEOUT)) {
summary = getString(R.string.settings_summary_client_read_timeout, Integer.parseInt(value));
}
Preference p = mPrefGroup.findPreference(key);
if (p != null) {
// null in cas of change of a preference not displayed here
p.setSummary(summary);
}
}
@Override
public boolean onPreferenceClick(Preference preference) {
final String key = preference.getKey();
if (ONBOARDING.equals(key)) {
startActivity(TutorialActivity.newIntent(getActivity(), false));
} else if (RATE_APP.equals(key)) {
AppRate.setRateDialogAgreed(getActivity());
/**
* Launch Playstore to rate app
*/
final Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent.setData(Uri.parse(getResources().getString(R.string.url_playstore)));
startActivity(viewIntent);
} else if (TERMS.equals(key) || FAQ.equals(key) || PRIVACY.equals(key)) {
startActivity(WebViewActivity.newIntent(getActivity(), key));
}
return false;
}
@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 initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else if (p instanceof PreferenceScreen) {
PreferenceScreen pSc = (PreferenceScreen) p;
for (int i = 0; i < pSc.getPreferenceCount(); i++) {
initSummary(pSc.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
@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 value) {
try {
if ((boolean) value) {
// setting to true
if (preference.getSharedPreferences().getBoolean("bluejay_run_as_phone_collector", false)) {
JoH.static_toast_long("Must disable BlueJay using phone slot first!");
return false;
}
}
} catch (Exception e) {
//
}
return true;
}
public static boolean transferPreferences(String action,
Preference preference, Object value) {
Intent i = new Intent(action);
if (value instanceof Boolean) {
i.putExtra(preference.getKey(), (Boolean) value);
} else if (value instanceof Float) {
i.putExtra(preference.getKey(), (Float) value);
} else if (value instanceof Integer) {
i.putExtra(preference.getKey(), (Integer) value);
} else if (value instanceof Long) {
i.putExtra(preference.getKey(), (Long) value);
} else if (value instanceof String) {
i.putExtra(preference.getKey(), (String) value);
} else if (value instanceof String[]) {
i.putExtra(preference.getKey(), (String[]) value);
} else {
throw new IllegalArgumentException(value.getClass()
.getCanonicalName() + " is not a supported Preference!");
}
preference.getContext().sendBroadcast(i);
return true;
}
static void updateCustomInputStylesSummary(final Preference pref) {
// When we are called from the Settings application but we are not already running, some
// singleton and utility classes may not have been initialized. We have to call
// initialization method of these classes here. See {@link LatinIME#onCreate()}.
SubtypeLocaleUtils.init(pref.getContext());
final Resources res = pref.getContext().getResources();
final SharedPreferences prefs = pref.getSharedPreferences();
final String prefSubtype = Settings.readPrefAdditionalSubtypes(prefs, res);
final InputMethodSubtype[] subtypes =
AdditionalSubtypeUtils.createAdditionalSubtypesArray(prefSubtype);
final ArrayList<String> subtypeNames = new ArrayList<>();
for (final InputMethodSubtype subtype : subtypes) {
subtypeNames.add(SubtypeLocaleUtils.getSubtypeDisplayNameInSystemLocale(subtype));
}
// TODO: A delimiter of custom input styles should be localized.
pref.setSummary(TextUtils.join(", ", subtypeNames));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.download_settings);
Preference mediaScan = findPreference(Settings.KEY_MEDIA_SCAN);
Preference imageResolution = findPreference(Settings.KEY_IMAGE_RESOLUTION);
mDownloadLocation = findPreference(KEY_DOWNLOAD_LOCATION);
onUpdateDownloadLocation();
mediaScan.setOnPreferenceChangeListener(this);
imageResolution.setOnPreferenceChangeListener(this);
if (mDownloadLocation != null) {
mDownloadLocation.setOnPreferenceClickListener(this);
}
}
/**
* Установка заголовка списка
*/
private void setPrefenceTitle(String TAG) {
final Preference preference = findPreference(TAG);
if (preference == null) return;
if (preference instanceof ListPreference) {
if (((ListPreference) preference).getEntry() == null) return;
final String title = ((ListPreference) preference).getEntry().toString();
preference.setTitle(title);
}
}
/**
* @param key of the preference
* @return {@link Preference} matching the key or null
*/
@Nullable
public Preference findPreference(final CharSequence key) {
if (mPreferenceManager == null) {
Log.w(TAG, "PreferenceManager was NULL");
return null;
}
return mPreferenceManager.findPreference(key);
}
@Override
public void onCreate(Bundle savedInstanceState) {
appPreferences = App.getAppPreferences();
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
context = getActivity();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.registerOnSharedPreferenceChangeListener(this);
prefCustomPath = (EditTextPreference) findPreference(getString(R.string.pref_custom_path));
prefCustomFile = (ListPreference) findPreference(getString(R.string.pref_custom_file));
prefSortMethod = (ListPreference) findPreference(getString(R.string.pref_sort_method));
prefTheme = (ListPreference) findPreference(getString(R.string.pref_theme));
// removes settings that wont work on lower versions
Preference prefNavigationColor = findPreference(getString(R.string.pref_navigation_color));
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
prefNavigationColor.setEnabled(false);
}
Preference prefReset = findPreference(getString(R.string.pref_reset));
prefReset.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
sharedPreferences.edit().clear().apply();
return true;
}
});
setSortModeSummary();
setThemeSummary();
setCustomPathSummary();
setFilenameSummary();
}
private void updateDb(final Preference p, final String value,final boolean isChecked) {
class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
if(isChecked) {
List<DataItem> items = db.getAllItems();
for(DataItem item : items) {
if(item.getName().equals("'"+p.getKey()+"'")) {
db.deleteItemByName("'"+p.getKey()+"'");
}
}
db.addItem(new DataItem("'"+p.getKey()+"'", value, p.getTitle().toString(), category));
} else {
if(db.getContactsCount() != 0) {
db.deleteItemByName("'"+p.getKey()+"'");
}
}
return "Executed";
}
@Override
protected void onPostExecute(String result) {
}
}
new LongOperation().execute();
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
/**
* Handles a new user input for the HTTP(S) proxy preference.
* Returns if the changed setting requires a restart.
*/
private boolean handleHttpProxyPreferenceChange(Preference preference, String newValue) {
// Valid input is either a proxy address or an empty field to disable the proxy.
if (newValue.equals("")) {
preference.setSummary(getString(R.string.do_not_use_proxy) + " " + getString(R.string.generic_example) + ": " + getString(R.string.http_proxy_address_example));
return true;
} else if (newValue.matches("^http://.*:\\d{1,5}$")) {
preference.setSummary(getString(R.string.use_proxy) + " " + newValue);
return true;
} else {
Toast.makeText(getActivity(), R.string.toast_invalid_http_proxy_address, Toast.LENGTH_SHORT)
.show();
return false;
}
}
private void openPreferenceScreen(final String screenName) {
final Preference pref = findPreference(screenName);
if (pref instanceof PreferenceScreen) {
final PreferenceScreen preferenceScreen = (PreferenceScreen) pref;
getActivity().setTitle(preferenceScreen.getTitle());
preferenceScreen.setDependency("");
setPreferenceScreen((PreferenceScreen) pref);
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
SharedPreferences sp = getPreferenceManager().getSharedPreferences();
boolean b = (boolean) newValue;
((SwitchPreference)preference).setChecked(b);
// -----------------------------------------------------------------
// Effected preference in this fragment
findPreference(resource.getString(R.string.prefKey_Recoder_VideoRecordPath)).setEnabled(b);
findPreference(resource.getString(R.string.prefKey_Recoder_VideoRecordInterval)).setEnabled(b);
findPreference(resource.getString(R.string.prefKey_Recoder_VideoRecordFPS)).setEnabled(b);
boolean b_vehicleBusRecord = b && sp.getBoolean(resource.getString(R.string.prefKey_VehicleBus_BusStatus), false);
if(b == false) {
//Log.e("ABC", "Listener_VehicleBusRecord set " + b);
//((SwitchPreference)findPreference(resource.getString(R.string.prefKey_Recoder_VehicleBusRecord))).setChecked(b);
SwitchPreference swp = (SwitchPreference)findPreference(resource.getString(R.string.prefKey_Recoder_VehicleBusRecord));
//
swp.getOnPreferenceChangeListener().onPreferenceChange(swp, b);
}
findPreference(resource.getString(R.string.prefKey_Recoder_VehicleBusRecord)).setEnabled(b_vehicleBusRecord);
// -----------------------------------------------------------------
// Effected preference in other fragment.
// NO.
return false;
}
/**
* Reload numbers.
*/
@SuppressWarnings("deprecation")
private void reload() {
Cursor c = getContentResolver().query(
ContentUris.withAppendedId(DataProvider.HoursGroup.CONTENT_URI, gid),
DataProvider.HoursGroup.PROJECTION, null, null, null);
if (c.moveToFirst()) {
CallMeter.setActivitySubtitle(this, c.getString(DataProvider.HoursGroup.INDEX_NAME));
}
c.close();
PreferenceScreen ps = (PreferenceScreen) findPreference("container");
ps.removeAll();
c = getContentResolver().query(
ContentUris.withAppendedId(DataProvider.Hours.GROUP_URI, gid),
DataProvider.Hours.PROJECTION, null, null,
DataProvider.Hours.DAY + ", " + DataProvider.Hours.HOUR);
if (c.moveToFirst()) {
do {
Preference p = new Preference(this);
p.setPersistent(false);
final int day = c.getInt(DataProvider.Hours.INDEX_DAY);
final int hour = c.getInt(DataProvider.Hours.INDEX_HOUR);
p.setTitle(resDays[day] + ": " + resHours[hour]);
p.setKey("item_" + c.getInt(DataProvider.Hours.INDEX_ID));
p.setOnPreferenceClickListener(this);
ps.addPreference(p);
} while (c.moveToNext());
}
c.close();
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (!isValid(newValue)) {
AlertDialog.Builder builder =
new AlertDialog.Builder(PreferencesFragment.this.getActivity());
builder.setTitle(R.string.msg_error);
builder.setMessage(R.string.msg_invalid_value);
builder.setCancelable(true);
builder.show();
return false;
}
return true;
}
/**
* Binds a preference's summary to its value. More specifically, when the
* preference's value is changed, its summary (line of text below the
* preference title) is updated to reflect the value. The summary is also
* immediately updated upon calling this method. The exact display format is
* dependent on the type of preference.
*
* @see #sBindPreferenceSummaryToValueListener
*/
private static void bindPreferenceSummaryToValue(Preference preference)
{
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
switch (preference.getKey()) {
case "donation":
Config config = new Config.Builder("FKX03835LYVF3XNJFBLVB0", R.drawable.alipay,
R.drawable.wechat)
.build();
MiniPayUtils.setupPay(this, config);
break;
case "update_log":
updateLogDialog(true);
break;
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}