简体   繁体   中英

Could not listen to preference changes?

class UserViewModel extends ViewModel{
    appPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener)
}}

private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;

public void subscribe() {

 preferenceChangeListener = (sharedPreferences, key) -> {

        }
    };
    appPrefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener);

};

public void unsubscribe(){
    appPrefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener);
}

subscribe() and unsubscribe() are called from Fragment onAttach() and onDetach() methods ,but not working when the state of the property is changed. And as you can see preferenceChangeListener is class member not a method property. the value of preference is changed in another fragment, and when I'm navigating to another fragment and coming back preferenceChangeListener is null it initialized again in onAttach() ,I see the reason ,but I don't know how to overcome.

I recommend to registerOnSharedPreferenceChangeListener() during fragment onResume() and unregisterOnSharedPreferenceChangeListener() at onPause() . Also check the preference key name what is observed. It could be a typo there.

`

 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
            if (key.equals(KEY_PREF_SYNC_CONN)) {
                Preference connectionPref = findPreference(key);
                // Set summary to be the user-description for the selected value
                connectionPref.setSummary(sharedPreferences.getString(key, ""));
            }
        }

` Official documentation could be found here: https://developer.android.com/guide/topics/ui/settings.html#Fragment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM