preference activity listener in android

2019-08-27 19:25发布

I am using the following code for adding a listener in prefernceactivity. But its not working. Please give a idea for this.

public class Preference extends PreferenceActivity implements OnSharedPreferenceChangeListener {
OnSharedPreferenceChangeListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.settings);
    }
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    // TODO Auto-generated method stub

}


}

1条回答
beautiful°
2楼-- · 2019-08-27 19:57

You have to register your listener first.

The best way is to register it in onResume and unregister in onPause :

@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
}

@Override
protected void onResume() {
    super.onResume();
    prefs.registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {      
    super.onPause();
    prefs.unregisterOnSharedPreferenceChangeListener(this);
}
查看更多
登录 后发表回答