如何在Fragments中使用Android Application全局SharedPreference

时间:2015-08-10 12:29:04

标签: android android-fragments fragment sharedpreferences

我的Android应用程序类文件中有一个'SharedPreference',如下所示:

public class App extends Application {
    public static Context context;
    public static SharedPreferences preference;
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        preference = PreferenceManager.getDefaultSharedPreferences(context);
   }
}

我将值放在长时间运行的后台服务的首选项中,所以当我想从此首选项更新片段简历中的片段内容时,在第一次加载活动和片段时一切正常,但是当我切换片段时,我的片段内容不会更新。请帮助解决这个问题。

2 个答案:

答案 0 :(得分:0)

要在任何片段中获取您的首选项实例,您可以使用以下代码。

((App)getActivity().getApplication()).preference

我可以看到你的偏好引用被声明为静态。如果没有特别的理由将其保持静态,则可以删除静态修改器。

答案 1 :(得分:0)

根据此答案判断Fragment onResume() not called在交换片段并重新创建片段时,不会调用onResume()

我建议您尝试更新onCreateView()中的数据。 您可以使用getActivity().getSharedPreferences(...)

从片段中访问共享首选项