onSharedPreferenceChanged不起作用

时间:2014-01-06 13:32:40

标签: android sharedpreferences

由于某种原因onSharedPreferenceChanged函数不起作用,日志永远不会显示。我希望在夏季中展示我的选择。

public class SettingsActivity extends PreferenceActivity  implements OnSharedPreferenceChangeListener {

static ListPreference mlistMode;
static ListPreference mlistPalette;
static Preference emissivity;
static Preference ref_temp;
static Context context;

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();

     context = getApplicationContext();


}

public static class MyPreferenceFragment extends PreferenceFragment  {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);



        mlistMode = (ListPreference)findPreference("listMode");
        mlistPalette = (ListPreference)findPreference("listpalette");
        emissivity = (Preference)findPreference("emissivity");
        ref_temp = (Preference)findPreference("reflected_temp");

        if (mlistMode.getValue().toString().equals("1")) 
        {
            mlistPalette.setEnabled(false);

        }
        else if (mlistMode.getValue().equals("2"))
            mlistPalette.setEnabled(true);


    }

}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,  String key) {

Log.d("MyApp", "here");     

Preference pref = findPreference(key);
    if (pref instanceof EditTextPreference) {
        EditTextPreference etp = (EditTextPreference) pref;
        pref.setSummary(etp.getText());
    }
}
}

1 个答案:

答案 0 :(得分:4)

尝试调用这些:

@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
        .unregisterOnSharedPreferenceChangeListener(this);
}