accessing a class from another activity

≡放荡痞女 提交于 2019-12-24 09:40:02

问题


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?


回答1:


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()




回答2:


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



来源:https://stackoverflow.com/questions/3541200/accessing-a-class-from-another-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!