The problem is that a Toast appears as many times as you open Settings activity, while I need it only once after each click on CheckBox.
Thanks in advance to everyone, who tried to improve my code.
More detailed description of how the code works:
And so on
public class PrefActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_screen);
Context context = getApplicationContext();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
settings.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
Toast mToast;
mToast = Toast.makeText(this, "toast text", Toast.LENGTH_SHORT);
if(key.equals("checkbox_key")){
mToast.show();
}
}
}
You should call settings.unregisterOnSharedPreferenceChangeListener()
in your onPause()
method when you leave the Activity. And I suggest to call settings.registerOnSharedPreferenceChangeListener()
in your onResume() callback
rather than onCreate()
.