片段中的共享首选项

时间:2015-07-12 10:09:04

标签: android android-activity fragment sharedpreferences

是否可以在Fragment中创建共享首选项,而不是在另一个活动中读取它?我尝试在Fragment中制作这样的共享首选项,但后来我无法在另一个活动中获得它们的价值。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preference);

    //Shared preferences
    final SharedPreferences pref = getActivity().getPreferences(0);

    final CheckBoxPreference checkboxPref = (CheckBoxPreference)getPreferenceManager().findPreference("save_old_reminders");
    //final CheckBoxPreference mogucnostZvuka = (CheckBoxPreference) getPreferenceManager().findPreference("enable_sound");

    checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {            
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (newValue.toString().equals("false")) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle("Save old reminders")
            .setMessage("If you turn this off, old reminders won't be saved!")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 

                    SharedPreferences.Editor edt = pref.edit();
                    edt.putString("saveOldReminders", "true");
                    edt.commit();
                    Intent intent = new Intent(getActivity(),Podsetnici.class);
                    startActivity(intent);  
                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    checkboxPref.setChecked(true);
                    SharedPreferences.Editor edt = pref.edit();
                    edt.putString("saveOldReminders", "false");
                    edt.commit();
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
        }

        return true;
    }
});  

1 个答案:

答案 0 :(得分:2)

你可以补充:

final SharedPreferences pref = getActivity().getPreferences(0);

使用:

final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());

最后一个属于整个应用程序。