Fragment 中的 Android SharedPreferences [英] Android SharedPreferences in Fragment

查看:46
本文介绍了Fragment 中的 Android SharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取 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 and Static 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆