本文介绍了片段中的共享首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在Fragment中进行共享首选项,而不是在其他活动中进行读取?我试图在Fragment中做出这样的共享首选项,但是后来我无法在其他活动中获得它们的价值.
Is it possible to make shared preferences in Fragment and than to read it in another activity? I tried to make like this shared preferences in Fragment, but then I can't get the value of them in another activity.
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;
}
});
推荐答案
您可以补充:
final SharedPreferences pref = getActivity().getPreferences(0);
使用:
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
最后一个属于整个应用程序.
The last one belongs to the whole app.
这篇关于片段中的共享首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!