androidxmlpreference

How to use toggle/switch button in preference activity


I looked around but couldn't find a single tutorial that tells me how to use the switchpreference in my preference activity and in my main activity. I want to know how to implement it in my application using sharedpreference. Sample code would be appreciated. Thanks in advance


Solution

  • preference.xml:

    <SwitchPreference
        android:key="test"
        android:title="Test" />
    

    PreferenceActivity:

    public class TestPrefActivity extends PreferenceActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.sample);
        }
    }
    

    Register the shared preference object for the changes

        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(MainActivity.this);
        sharedPrefs.registerOnSharedPreferenceChangeListener(new OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                boolean test = sharedPreferences.getBoolean("test", false);
                Log.e(TAG, "Value:" + test);
            }
        });