从不调用自定义OnPreferenceChangeListener

时间:2015-10-29 17:11:24

标签: android listener android-preferences

我编写了一个实现Preference.OnPreferenceChangeListener的类,并且在更改Preference时应该调用其OnPreferenceChange方法。虽然我设置了这些监听器,但从不调用该方法。

public abstract class Program
    implements Preference.OnPreferenceClickListener,
                Preference.OnPreferenceChangeListener {

/// reference to main activity
public static MainActivity mainActivity;
/// stores the keys to all preferences
protected final HashMap<String, String> PreferenceCodes = new HashMap<>();

public void setPreferenceListeners (PreferenceFragment Host) {
    // iterate over all Preferences
    for(HashMap.Entry<String, String> entry : PreferenceCodes.entrySet()) {
        Preference tmp = Host.findPreference(entry.getKey());
        tmp.setOnPreferenceClickListener(this);
        tmp.setOnPreferenceChangeListener(this);
    }
}

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    // TODO Here is the problem: This method never is invoked

    Toast.makeText(mainActivity, "Changed", Toast.LENGTH_LONG).show();
    return true;/        
}

@Override
public boolean onPreferenceClick(Preference preference) {
    Toast.makeText(mainActivity, "Click", Toast.LENGTH_LONG).show();

    return true;
}

正确调用OnPreferenceClick方法,只是Change方法有问题。 当我用这段代码替换setPreferenceListeners时,一切正常:

public void setPreferenceListeners (PreferenceFragment Host) {
    for(HashMap.Entry<String, String> entry : PreferenceCodes.entrySet()) {
        Preference tmp = Host.findPreference(entry.getKey());
        tmp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Toast.makeText(mainActivity, "Change", Toast.LENGTH_SHORT).show();
                Log.i("TEST", "Change");
                return true;
            }
        });

        tmp.setOnPreferenceClickListener(this);
    }

我找不到自己的错误。 OnPreferenceChange和OnPreferenceClick之间的区别在哪里。能够将这两种方法作为Program类的一部分来实现真的很不错。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您需要一个 onSharedPreferenceListener

代码示例:

OnSharedPreferenceChangeListener listener;

listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {

        //preference has been changed now, but Do your work.
    }
};

SharedPreferences prefs = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);
prefs.registerOnSharedPreferenceChangeListener(listener);