3

I need to set/unset listener dynamically in response to a Preference CheckBox user setting change.

One approach I have seen is to use onSharedPreferenceChanged() and check for that checkbox's key.

But somehow this looks to me inefficient. I was thinking more in the direction of setting some kind of listener on the class derived from PreferenceActivity. Perhaps onContentChanged()?

Which approach would you recommend and why?

Can you point to a sample working code?

Community
  • 1
  • 1
ateiob
  • 9,016
  • 10
  • 44
  • 55
  • Have you tried [`setOnCheckedChangeListener()`](http://developer.android.com/reference/android/widget/CompoundButton.html#setOnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener))? – slybloty Jun 19 '12 at 03:37
  • @slybloty See my comment to @Yawus below. How do I use `setOnCheckedChangeListener()` for a ``? Note the difference from ``. – ateiob Jun 19 '12 at 03:46

2 Answers2

4

You should implement OnSharedPreferenceChangeListener. And then set up a listener to catch key changes:

getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

The you should be able to retrieve the checked changes:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) 
{

}
slybloty
  • 6,346
  • 6
  • 49
  • 70
  • +1. Are you suggesting that the first approach I mentioned in my question is the only way to go? Or the best one? [PreferenceActivity.html#onContentChanged()](http://developer.android.com/reference/android/preference/PreferenceActivity.html#onContentChanged%28%29) won't cut it? – ateiob Jun 19 '12 at 13:14
  • It might work as well. I can't give you an exact answer since I haven't tried it myself. But I suggest implementing the listener. – slybloty Jun 19 '12 at 13:30
  • 1
    OK. I will never know whether onContentChanged() works better because I just implemented OnSharedPreferenceChangeListener() and it works fine. One day, when I have more time to experiment and benchmark... – ateiob Jun 19 '12 at 18:52
0

Here's the documentation. Using the XML file, you can set a method to be executed when the widget is clicked. Setting android:onClick = foo will execute the method foo when the widget is clicked, passing it the parameter View v, v being the View that was clicked.

Jason L
  • 1,812
  • 2
  • 22
  • 43
  • Your suggestion is great for `` in the context of layout. I am referring to `` in the context of PreferenceScreen. But I think that I just found this: http://stackoverflow.com/questions/8386832/android-checkbox-listener . Actually, even that is for the layout context, not the PreferenceScreen. – ateiob Jun 19 '12 at 03:26
  • All right, good for you that you found the answer. Guess I should've read a bit more deeply. – Jason L Jun 19 '12 at 03:27
  • Actually I didn't. I celebrated too early. – ateiob Jun 19 '12 at 03:28