gpt4 book ai didi

Android sharedPreferences设置默认值问题

转载 作者:行者123 更新时间:2023-11-29 14:38:44 24 4
gpt4 key购买 nike

我在我的项目中使用了一些 Activity 。其中之一是从 PreferenceActivity 扩展而来的。我有一个 CheckBoxPreference 和一个 EditTextPreference,我可以使用以下方法从所有其他 Activity 中获取值:

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
pref = sharedPrefs.getString("edit_text_pref", "error");

但是当我打开我的应用程序时,这些值必须设置为默认值,因此我正在使用:

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().clear().commit(); 

在我的主要 Activity 中。一切都应该没问题,但如果我在从首选项菜单中设置它之前尝试获取首选项,我会得到“错误”,而不是我在 xml 首选项文件中设置的默认值。如果我评论 getDefaultSharedPreferences 行它工作正常但显然当我打开应用程序时我得到旧的偏好。我怎样才能绕过这个问题?

最佳答案

仔细看看 http://developer.android.com/reference/android/preference/PreferenceManager.html#setDefaultValues%28android.content.Context,%20int,%20boolean%29

你必须使用这个 setDefaultValues (Context context, int resId, boolean readAgain) 类似的东西

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

好好看看参数中的注释部分。这是关于再次阅读参数

context 共享首选项的上下文。

resId 首选项 XML 文件的资源 ID。

readAgain 是否重新读取默认值。如果为 false,则只有在过去从未调用过此方法(或者默认值共享首选项文件中的 KEY_HAS_SET_DEFAULT_VALUES 为 false)时,此方法才会设置默认值。要尝试绕过此检查再次设置默认值,请将 readAgain 设置为 true。

注意:这不会将首选项重置为默认值。对于该功能,使用 getDefaultSharedPreferences(Context) 并清除它,然后调用此方法并将此参数设置为 true

所以我想在清除它之后你需要通过将 readAgain 传递为 true 将其设置为默认值

有点像

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preference, true);

关于Android sharedPreferences设置默认值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19856958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com