How to listen for preference changes within a PreferenceFragment?

前端 未结 9 2093
自闭症患者
自闭症患者 2020-11-28 19:16

As described here, I am subclassing PreferenceFragment and displaying it inside an Activity. That document explains how to listen for preference changes here, but only if yo

9条回答
  •  情话喂你
    2020-11-28 19:44

    All the other answers are correct. But I like this alternative better because you immediately have the Preference instance that caused the change.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Preference pref = findPreference(getString(R.string.key_of_pref));        
        pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                // do whatever you want with new value
    
                // true to update the state of the Preference with the new value
                // in case you want to disallow the change return false
                return true;
            }
        });
    }
    

提交回复
热议问题