Android Checkbox preference

后端 未结 3 1887
温柔的废话
温柔的废话 2020-12-23 12:11

I cannot find any tutorials on checkbox preference. I can use a listpreference, but I can\'t use checkbox preference. For now, I want that if user sets on the checbox, a toa

相关标签:
3条回答
  • 2020-12-23 12:29

    You need to add a listener to the Preference in your onCreate method

        final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
    
        checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Log.d("MyApp", "Pref " + preference.getKey() + " changed to " + newValue.toString());       
                return true;
            }
        }); 
    
    0 讨论(0)
  • 2020-12-23 12:34

    You can cast the value of the checkbox into a boolean. This might be safer and more extensible than checking the toString() value.

    final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("checkboxPref");
    
    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if(newValue instanceof Boolean){
                Boolean boolVal = (Boolean)newValue;
            }
            return true;
        }
    }); 
    
    0 讨论(0)
  • 2020-12-23 12:46
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    Log.i("LOG", String.valueOf(sp.getBoolean("key", false)));
    

    Simplest way i found of getting value if item is pressed. If log is:

    I/LOG: true

    Checkbox is pressed

    I/LOG: false

    Checkbox is not selected

    Hope this answers your question.

    0 讨论(0)
提交回复
热议问题