如何在 Xamarin.Android 中使用 SharedPreferences? [英] How do I use SharedPreferences in Xamarin.Android?

查看:16
本文介绍了如何在 Xamarin.Android 中使用 SharedPreferences?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Xamarin.Android 项目中保存和检索一些应用程序设置.

I want to save and retrieve some application settings in my Xamarin.Android project.

我知道在 Android (java) 中,我使用 SharedPreferences 类来存储此信息,但我不知道如何将其转换为 Xamarin C#.

I know that in Android (java), I use the class SharedPreferences to store this information, but I do not know how to convert that to Xamarin C#.

当我在 Xamarin Studio IDE 中键入SharedPreferences"时,没有自动完成功能,所以我不知道该使用什么.

When I type "SharedPreferences" into the Xamarin Studio IDE, there is no auto-completion, so I don't know what to use.

对互联网的初步搜索将我带到了一个相关问题,但只包含 Android java:

An initial search of the interwebs took me to a related question, but only contains Android java:

总结一下:

  • Android Java 的 SharedPreferencesXamarin Android C# 等价物是什么?
  • What is the Xamarin Android C# equivalent of Android Java's SharedPreferences?

推荐答案

SharedPreferences 等效的 Xamarin.Android 是一个名为 ISharedPreferences 的接口.

The Xamarin.Android equivalent of SharedPreferences is an interface called ISharedPreferences.

以同样的方式使用它,您将能够轻松地移植 Android 代码.

Use it in the same way, and you will be able to easily port Android code across.

例如,要使用某些 Context 保存真/假 bool,您可以执行以下操作:

For example, to save a true/false bool using some Context you can do the following:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutBoolean ("key_for_my_bool_value", mBool);
// editor.Commit();    // applies changes synchronously on older APIs
editor.Apply();        // applies changes asynchronously on newer APIs

使用以下方法访问保存的值:

Access saved values using:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
mBool = prefs.GetBoolean ("key_for_my_bool_value", <default value>);
mInt = prefs.GetInt ("key_for_my_int_value", <default value>);
mString = prefs.GetString ("key_for_my_string_value", <default value>);

<小时>

从这个示例中,您可以看到,一旦您知道要使用的正确 C# 接口,剩下的就很简单了.有很多关于如何将 SharedPreferences 用于更复杂情况的 Android java 示例,这些可以使用 ISharedPreferences 轻松移植.


From this sample, you can see that once you know the correct C# interface to use, the rest is easy. There are many Android java examples on how to use SharedPreferences for more complex situations, and these can be ported very easily using ISharedPreferences.

有关更多信息,请阅读此主题:

For more information, read this thread:

这篇关于如何在 Xamarin.Android 中使用 SharedPreferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆