android sharedpreferences 设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3328545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:44:31  来源:igfitidea点击:

android sharedpreferences set value

androidpreferences

提问by davs

I have preferences page. It has field 'Show info screen' (as checkbox).

我有偏好页面。它具有“显示信息屏幕”字段(作为复选框)。

I have also info page which also should have checkbox 'Show me again'.

我还有信息页面,其中也应该有复选框“再次显示”。

As I've understand, I can get value from preferences page via PreferencesManager.getDefaultPreferences(context)...

据我了解,我可以通过以下PreferencesManager.getDefaultPreferences(context)方式从偏好页面中获取价值...

But how I should set preferences value for the checkbox on info page?

但是我应该如何为信息页面上的复选框设置首选项值?

I tried to use context.getSharedPreferences(PREF_NAME, 0).edit(), to set value but it doesn't correlate with PreferencesManager's corresponding value.

我尝试使用context.getSharedPreferences(PREF_NAME, 0).edit(), 来设置值,但它与 PreferencesManager 的相应值无关。

What should I do??? F1

我该怎么办???F1

回答by Stephen Denne

It depends on whether you are after one set of preferences for your application, or one set per activity.

这取决于您是在为应用程序设置一组首选项,还是为每个活动设置一组首选项。

I've used code like this:

我使用过这样的代码:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putBoolean(PREF_NAME, false);
editor.commit();

and

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
if (prefs.getBoolean(PREF_NAME, true)) {
    // etc
}