它给我错误“findPreference(java.lang.CharSequence)已被弃用”。目前,我的应用程序的目标是 API 10 及更高版本。任何形式的帮助来解决这个问题将不胜感激。
公共类 SettingsActivity 扩展 PreferenceActivity
实现 Preference.OnPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
// TODO: Add preferences from XML
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key));
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
// TODO: Add preferences
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
@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 (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
}
它已被弃用,因为 Android 已转向基于片段的活动。呼唤findPreference(CharSequence) http://developer.android.com/reference/android/preference/PreferenceActivity.html#findPreference(java.lang.CharSequence)仍然可以在更高的 API 级别上工作。只是鼓励您使用片段而不是PreferenceActivity
.
弃用的原因可以在source https://github.com/android/platform_frameworks_base/blob/59701b9ba5c453e327bc0e6873a9f6ff87a10391/core/java/android/preference/PreferenceActivity.java#L1535-1536:
此函数与现代基于片段的 PreferenceActivity 无关。
在 API 11+ 中你应该使用PreferenceFragment http://developer.android.com/reference/android/preference/PreferenceFragment.html.
如果您想让 IDE 忽略该错误,只需将以下内容添加到您的方法中:@SuppressWarnings("deprecation")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)