[英]Android onSharedPreferenceChanged
我已经设法使用xml和一个扩展PreferenceActivity并实现OnSharedPreferenceChangeListener的类来创建菜单,现在我希望每次用户从首选项更改值时(例如,当用户更改用户名时)得到通知。 为此,我已经使用方法registerOnSharedPreferenceChangeListener注册了我的课程。
并实现了onSharedPreferenceChanged方法。
这样可以使我的应用程序收到更改通知,但实际上如何更改该值?
有没有关于这个的好的教程,因为我还没有找到。
如果我正确理解了您的问题,这就是我执行更改的方法:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
// Get a link to your preferences:
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
// Let's do something a preference value changes
if (key.equals("hintsPreference"))
{
// Create a reference to the checkbox (in this case):
CheckBoxPreference mHints = (CheckBoxPreference)getPreferenceScreen().findPreference("hintsPreference");
//Lets change the summary so the user knows what will happen using a one line IF statement:
mHints.setSummary(mHints.isChecked() ? "Hints will popup." : "No hints will popup.");
// Lets store the new preference:
editor.putBoolean("hintsPreference", mHints.isChecked());
}
/**
* You could perform several else if statements, or probably better use a switch block.
*/
// Save the results:
editor.commit();
}
我的XML条目如下所示:
<CheckBoxPreference android:key="hintsPreference" android:title="Show Helpful Hints:" />
这没有经过测试,我已经剥离了很多,使它更加简单,但是希望它足以帮助您。
例如,在您的onCreate方法中,您可以执行以下操作:
// Link to your checkbox:
CheckBoxPreference mHints = (CheckBoxPreference)getPreferenceScreen().findPreference("hintsPreference");
// Set the summary based on the one line IF statement:
mHints.setSummary(s.getBoolean("hintsPreference", true) ? "Hints will popup." : "No hints will popup.");
// Set the box as either ticked or unticked:
mHints.setChecked(s.getBoolean("hintsPreference", true));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.