【问题标题】:Android onSharedPreferenceChangedAndroid onSharedPreferenceChanged
【发布时间】:2010-10-08 17:45:23
【问题描述】:

我已经设法使用 xml 和一个扩展 PreferenceActivity 并实现 OnSharedPreferenceChangeListener 的类创建了一个菜单,现在我希望在每次用户更改首选项中的值时(例如,当用户更改用户名时)得到通知。为此,我使用 registerOnSharedPreferenceChangeListener 方法注册了我的课程。

并实现了 onSharedPreferenceChanged 方法。

这使我的应用程序能够收到更改通知,但我如何才能真正更改值?

有什么好的教程吗,因为我还没有找到。

【问题讨论】:

  • @maxasp: "但是我怎样才能真正改变这个值呢?" -- 改变什么值?
  • 我猜是偏好改变的值。

标签: android


【解决方案1】:

如果我正确理解了您的问题,这就是我执行更改的方式:

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-01
    • 2019-07-11
    • 2013-06-29
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    相关资源
    最近更新 更多