【问题标题】:How to use Android Application global SharedPreference in Fragments如何在 Fragments 中使用 Android 应用程序全局 SharedPreference
【发布时间】:2015-08-10 12:29:04
【问题描述】:

我的 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);
   }
}

我从长期运行的后台服务中将值设置为首选项,因此,当我想从此首选项更新片段恢复上的片段内容时,在第一次加载活动和片段时一切正常,但是当我切换片段时,我的片段内容不更新。请帮忙。

【问题讨论】:

    标签: android android-fragments fragment sharedpreferences


    【解决方案1】:

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

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

    我可以看到您的偏好引用被声明为静态。如果没有特别的理由让它保持静态,您可以删除静态修饰符。

    【讨论】:

    • 我将首选项字段设置为静态以从我的应用程序中的任何位置访问它,而无需从 App 类创建实例。我想在后台服务、活动、片段和广播接收器中读取偏好数据。我只是被碎片惹上麻烦。
    【解决方案2】:

    根据Fragment onResume() not called 这个答案判断,当片段被交换并重新创建时,您的onResume() 不会被调用。

    我建议您尝试更新onCreateView() 中的数据。 您可以使用getActivity().getSharedPreferences(...)从片段访问共享首选项

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 2011-07-10
      相关资源
      最近更新 更多