在fragment中调用SharedPreferences

时间:2022-05-19 12:10:59

[o]

Activity中调用SharedPreferences的方式:

String prefsName = "mysetting";
SharedPreferences prefs = getSharedPreferences(prefsName, Context.MODE_PRIVATE);
boolean a1 = prefs.getBoolean("a1_key", false);
boolean a2 = prefs.getBoolean("a2_key", false);
...

此方法在Fragment中无效,将目标Activity引用进Fragment会报空指针异常:

MyActivity mActivity;
SharedPreferences prefs = mActivity.getSharedPreferences(prefsName,
  Context.MODE_PRIVATE);

因为SharedPreferences在Activity全局中生效,故只要使用getActivity()泛调用即可:

String prefsName = "mysetting";
SharedPreferences prefs = getActivity().getSharedPreferences(prefsName,
  Context.MODE_PRIVATE);