Android的SharedPreferences在片段
我正在尝试阅读Fragment内部的SharedPreferences。 我的代码就是我用来获取其他Activity的首选项。
SharedPreferences preferences = getSharedPreferences("pref", 0); 我得到错误
  Cannot make a static reference to the non-static method getSharedPreferences(String, int) from the type ContextWrapper 
我试图遵循这些链接,但没有运气通过静态方法和静态SharedPreferences 访问 SharedPreferences 。 感谢您的任何解决scheme。
  getSharedPreferences方法是Context对象的一个方法,所以只要从Fragment调用getSharedPreferences就行不通了…因为它不是Context!  (Activity是Context的扩展,所以我们可以从它调用getSharedPreferences)。 
所以你必须得到你的应用程序上下文
 // this = your fragment SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE); 
明显的答案不适用于我,我不得不使用
 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
作为谨慎的提示,上面的用户提供的答案是正确的。
 SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0); 
但是,如果您在调用onAttach之前尝试获取片段中的任何内容,getActivity()将返回null。