Android的共享preferences的片段 [英] Android SharedPreferences in Fragment

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

问题描述

我想读里面的片段共享preferences。我的code是什么,我用得到preferences任何其他活动。

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    

我试图按照这些链接,但没有运气<一href="http://stackoverflow.com/questions/3806051/accessing-shared$p$pferences-through-static-methods">Accessing通过静态方法共享preferences 并 静态共享preferences 的。谢谢你的任何解决方案。

I have tried to follow these links but with no luck Accessing SharedPreferences through static methods and Static SharedPreferences. Thank you for any solution.

推荐答案

方法 getShared preferences 上下文的方法对象,所以才打电话getShared $ P $从pferences一个片段将无法正常工作......因为它不是一个上下文! (活动为背景的延伸,所以我们可以从它调用getShared preferences)。

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);

这篇关于Android的共享preferences的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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