获取SharedPreference
getSharedPreferences(String name, int mode) — 通过名称,和访问mode来新建一个shared preference文件。mode值可以是:
1
2
3
4MODE_PRIVATE
MODE_WORLD_READABLE
MODE_WORLD_WRITEABLE
MODE_MULTI_PROCESSgetPreferences() — 创建默认的shared preference文件,app只需要一个preference文件时使用。
例子:
1
2
3Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
写Shared Preference
1
2
3
4SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();读Shared Preference
1
2
3SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
long default = getResources().getInteger(R.string.saved_high_score_default));
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), default);