Failed to 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 the Fragment onAttach()and methods onDetach(), but do not work when the state of the property changes. And, as you can see, the preferenceChangeListener is a member of the class, not a property of the method. the preference value changes in another fragment, and when I move to another fragment and return the preference .ChangeListener is null, it is initialized again in onAttach (), I see the reason, but I don’t know how to overcome it.

+4
source share
1 answer

registerOnSharedPreferenceChangeListener() onResume() unregisterOnSharedPreferenceChangeListener() onPause(). , . .

`

 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, ""));
            }
        }

` : https://developer.android.com/guide/topics/ui/settings.html#Fragment

+3

Source: https://habr.com/ru/post/1683779/


All Articles