问题描述
我正在尝试读取 Fragment 中的 SharedPreferences.我的代码用于在任何其他活动中获取首选项.
I am trying to read SharedPreferences inside Fragment. My code is what I use to get preferences in any other 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.感谢您提供任何解决方案.
I have tried to follow these links but with no luck Accessing SharedPreferences through static methods andStatic SharedPreferences. Thank you for any solution.
推荐答案
getSharedPreferences
方法是 Context
对象的一个方法,所以只需从 中调用 getSharedPreferences>Fragment
将不起作用...因为它不是上下文!(Activity 是 Context 的扩展,因此我们可以从中调用 getSharedPreferences).
The method getSharedPreferences
is a method of the Context
object, so just calling getSharedPreferences from a Fragment
will not work...because it is not a Context! (Activity is an extension of Context, so we can call getSharedPreferences from it).
所以你必须通过
// this = your fragment
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
这篇关于Fragment 中的 Android SharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!