如何使用共享preferences在Xamarin.Android? [英] How do I use SharedPreferences in Xamarin.Android?
问题描述
我要保存和检索我的Xamarin.Android项目的一些应用程序设置。
I want to save and retrieve some application settings in my Xamarin.Android project.
我知道,在安卓(JAVA),我用的是类共享preferences
来存储这些信息,但我不知道如何将其转换成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#.
当我键入共享preferences到Xamarin Studio IDE中,有没有自动完成,所以我不知道有什么用。
When I type "SharedPreferences" into the Xamarin Studio IDE, there is no auto-completion, so I don't know what to use.
在interwebs的初始搜索把我带到一个相关的问题,但只包含了Android的Java的:
An initial search of the interwebs took me to a related question, but only contains Android java:
- 使用共享$在xamarin 点$ pferences
- Use Shared Preferences in xamarin
总结一下:
- 什么是 Xamarin的Android C#相当于 Android的Java的
共享preferences
?
- What is the Xamarin Android C# equivalent of Android Java's
SharedPreferences
?
推荐答案
在Xamarin.Android相当于共享preferences
是名为 IShared preferences
。
The Xamarin.Android equivalent of SharedPreferences
is an interface called ISharedPreferences
.
使用它以同样的方式,你就可以轻松地跨越端口的Android code。
Use it in the same way, and you will be able to easily port Android code across.
例如,保存真/假布尔
使用一些上下文
您可以执行以下操作:
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保存的值:
Access saved values using:
ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
mBool = prefs.GetBoolean ("key_for_my_bool_value");
mInt = prefs.GetInt ("key_for_my_int_value");
mString = prefs.GetString ("key_for_my_string_value");
从这个例子中,你可以看到,一旦你知道正确的C#接口来使用,其余的很简单。有关于如何使用共享preferences
对于更复杂的情况,而这些都可以移植非常容易地使用 IShared $ P很多Android的Java示例$ pferences
。
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:
- Android的共享$ P $上Xamarin论坛 pference
- Android Shared Preference on Xamarin forum
这篇关于如何使用共享preferences在Xamarin.Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!