views:

60

answers:

2

Have following setup:

MainActivity class - extends activity

MyLayout class - extends View

Prefs class - extends PreferenceActivity and implements OnSharedPreferenceChangeListener

MainActivity creates a MyLayout class and sets it as its contentview. Once the user presses on the menu, Prefs class starts where the user can change some settings.

What I want is that, once the user changes a setting, the overloaded OnsharedPreferenceChanged method in the Prefs class will be called and from there I would like to invoke public methods on the MyLayout class that was created in the MainActivity.

How can I do this?

+3  A: 

Don't overload onSharedPreferenceChanged method in preferenceactivity. Get an instance of the shared preference in your MainActivity, and then register an onsharedpreferencechangedlistener on that inside of your mainactivity



SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);

pref.registerOnSharedPreferenceChangeListener(prefListener);

And then you can create a new preference listener


    OnSharedPreferenceChangeListener prefListener = new OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(
                SharedPreferences sharedPreferences, String key) {
            // Do stuff
        }

    };

You should also unregister the listener in onPause() unless you need it to persist, otherwise unregister it on onStop()

Falmarri
Changed as suggested, and it works, but only once. As soon as I try to enter the menu again and change the values, the onsharedpreferencechanged is not called again. Tried with unregistering the listener but that only made it not work at all. My guess is that the listener "breaks" down after the first access to the menu and I have no idea why.
Milan
The problem above seems to have fixed itself after a restart and purge of eclipse.
Milan
Yeah, the preference listener doesn't get consumed so it must have been some other weird problem
Falmarri
A: 

Try making MainActivity implement OnSharedPreferenceChangeListener and register it on the onCreate() method as Falmarri said.

Macarse
I would recommended against implementing onSharedPreferenceChangeListener in the Activity class. Just create a new named instance of onSharedPreferenceListener instead
Falmarri
Why would you recommend against it?
HXCaine
Because it adds more complexity and violates some of the object oriented principles. Your activity shouldn't implement an interface unless it's necessary. The point of having classes and objects is to separate implementation as much as possible. Implementing interfaces on classes where it isn't required just adds complexity
Falmarri