MarcoS
MarcoS

Reputation: 17721

Android: call a method from calling activity

In my activity, on user's request for preferences screen, I call:

startActivity(new Intent(this, Preferences.class));

Preferences class is defined like this:

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
    ...
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        ...
    }

}

I need to implement OnSharedPreferenceChangeListener in my Preferences class becase I want to be able to - for example - disable a preferences item based on a specific selection. But I would need to implement it in my main Activity, to react to the preference changes.

Unfortunately onSharedPreferenceChanged() fires only in my Preferences class, and not in my main activity: how can I force it to be fired in bot activities?

Or - how can I manually call onSharedPreferenceChanged() in my main activity from onSharedPreferenceChanged() in Preferences activity?

Upvotes: 1

Views: 852

Answers (3)

devmiles.com
devmiles.com

Reputation: 10014

Well, there's little sense in watching for preferences change in an activity that's not currently 'active'. You should handle your main activity's lifecycle events instead such as onResume, onRestart etc.

Upvotes: 1

dldnh
dldnh

Reputation: 8961

in your main activity, you can register a listener for prefs changes:

SharedPreferences prefs = PreferenceManager
    .getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);

and then you would implement SharedPreferences.OnSharedPreferenceChangeListener in your activity, with your own onSharedPreferenceChanged method.

Upvotes: 2

Malcolm
Malcolm

Reputation: 41508

If you want to make some functionality accessible from both activities, you best do this by including this code into a static method which can be called from anywhere. In Android activities are decoupled, you don't really have the access from one activity to the instance of some other activity.

Upvotes: 0

Related Questions