1

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?
Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
Lendl Leyba
  • 2,287
  • 3
  • 34
  • 49

2 Answers2

2

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)
Yash Sampat
  • 30,051
  • 12
  • 94
  • 120
0

This is an amazing example on how to make a PreferenceFragment: http://android-er.blogspot.hu/2012/07/example-of-using-preferencefragment.html

Basically the way it works is that you define the preferences with their types and keys. The preference fragment stores its data in the SharedPreferences, which you obtain via Android getDefaultSharedPreferences , and edit its values and obtain them from an Editor.

In a Preference Fragment, you automatically have the data of the prefs linked between the Fragment and the SharedPrefs.

Also look at this example code: http://www.mysamplecode.com/2011/11/android-shared-preferences-example_12.html

Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428