How to use a checkBoxPreference

1

I am trying to make an options menu with an option to deactivate / activate notifications, I have a PreferenceScreen defined in XML with a CheckBoxPreference in

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">

<CheckBoxPreference
    android:id="@+id/checkbox_Notifications"
    android:key="notifications"
    android:title="@string/preferences_notification_checkbox_title"
    android:defaultValue="true"
    android:summary="@string/preferences_notification_checkbox_summary"
    android:persistent="true"

    />

    </PreferenceScreen>

And then I have a SettingsActivity that extends from PreferenceActivity , but I do not know how to collect the CheckBoxPreference of the resources, I get an error just like I do now

SettingsActivity.java

public class SettingsActivity extends PreferenceActivity {


Context context=this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    final CheckBoxPreference notifications = (CheckBoxPreference) findPreference("checkbox_Notifications");


    notifications.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue)
            {
                boolean checked = Boolean.valueOf(newValue.toString());
                SharedPreferences prefs = context.getSharedPreferences("prefs", MODE_WORLD_READABLE);
                SharedPreferences.Editor prefsEditor = prefs.edit();
                prefsEditor.putBoolean("notifications", checked);
                prefsEditor.commit();

                return true;
            }
        });

}

}

    
asked by masterfabela 31.10.2016 в 10:15
source

1 answer

1

To obtain the reference of CheckBoxPreference is precisely how you do it by means of the defined id:

  CheckBoxPreference checkboxpref = (CheckBoxPreference) findPreference("<ID PREFERENCIA>");

The OnPreferenceChangeListener listener that you indicate is used to detect when the values saved in the preference have undergone some change:

checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Log.d("MyApp", "La Preferencia: " + preference.getKey() + " cambio a: " + newValue.toString());       
            return true;
        }
    }); 

You do not need to create preference by means of a getSharedPreferences , by defining an id or name the preference you have already created a preference for the values in CheckBoxPreference .

    
answered by 31.10.2016 / 17:49
source