刷新共享preferences的简历? (或如何刷新/重载活动)简历、preferences

2023-09-12 22:23:53 作者:小伙伴想你们了!

我怎么可以重新加载共享preferences当我从一个活动恢复到另一个?如果我恢复,有可能该用户已更改的设置。是否有可能重新载入共享preferences还是需要刷新/重载活动。如果,那么如何?

How can I reload SharedPreferences when I resume from one activity to another? If I resume, it is possible that user has changed the settings. Is it possible to reload SharedPreferences or do I need to refresh/reload activity. And if, then how?

推荐答案

有一个在你如何获得并设置没有区别共享preferences 正常,这样做在 onResume 。你将需要做的,除了获得最新的preferences,是更新你的活动的使用preference值的任何对象。这将确保您的活动正与最新的值。

There is no difference in how you get and set SharedPreferences normally and from doing so in onResume. What you will need to do in addition to getting the most recent preferences, is update any objects you have in the Activity that use preference values. This will ensure your Activity is working with the most recent values.

一个简单的例子:

protected void onResume() {
    super.onResume();
        getPrefs();

    //...Now update your objects with preference values         
}

private void getPrefs() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String myPref = prefs.getString("myPref", "");
}