Search code examples
androidandroid-fragmentsandroid-preferencesandroid-switch

Shared Preferences and Preference Fragment


Here are my questions:

  1. How can I get the value of a switch preference?
  2. Are things inside a preference fragment already a shared preference?
  3. If so, how can I access shared preferences from a preference fragment?

Solution

  • 1. To get the value of a switch:

    CompoundButton cb = (CompoundButton)view.findViewById(R.id.myswitch);
    
    if(cb.isChecked())
        cb.setChecked(false);
    else
        cb.setChecked(true);
    

    Reference: Toggle Buttons

    2. Yes, the elements in a PreferenceFragment are automatically stored.

    3. To get the SharedPreference object of a PreferenceFragment, use:

    getDefaultSharedPreferences(Context context)