OnSharedPreferenceChangeListener未被调用

时间:2014-03-29 14:10:00

标签: android

我创建了一个PreferenceActivity,我已经实施了OnSharedPreferenceChangeListener()

PreferenceScreen使用PreferencesOnSharedPreferenceChangeListener()未被调用。

为什么没有调用OnSharedPreferenceChangeListener()?

MyPreferenceActivity.java

package com.example.sms_reader;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;


public class MyPreferenceActivity 
         extends PreferenceActivity implements OnSharedPreferenceChangeListener {
  SharedPreferences prefs;
  MyPreferenceActivity listener;

  @SuppressWarnings("deprecation")
  @Override
  public void onCreate(Bundle savedInstanceState)  {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);
  }


  @Override
  public void onSharedPreferenceChanged(SharedPreferences preferences,
                                        String key) {
    if(key == "RESET") {  
      Toast.makeText(getApplicationContext(), 
                     "RESET Values changed", Toast.LENGTH_LONG).show();
      Log.d("on shared preference gets a call","on shared preference gets a call" ); 
      Boolean b = preferences.getBoolean("reset", false);
      Log.d("reset value", String.valueOf(b)); 

      if (b == true) {
        Toast.makeText(getApplicationContext(), 
                     "RESET Values changed", Toast.LENGTH_LONG).show();

        preferences.edit().clear().commit();
        PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.preferences, true);
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);               
      }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

更改if条件,如下所示:

if (key.equals("RESET")) {

如果它仍然不起作用,则在其上放置一个断点(或正面的日志消息)以查看执行是否真的通过了那里。