我正在使用 Xamarin 并开始将 iOS 应用程序转换为 Android 应用程序的过程,但我在检索和设置首选项时遇到了障碍。在 iOS 中,我只是通过使用 NSUserDefaults.StandardUserDefaults
得到一个 NSUserDefaults
然后我可以用 BoolForKey
得到一个 bool
> 并使用 SetBool
对其进行设置。但是,我找不到与 Android 相当的产品。
在 Android 中,我设置了一个 Preferences.xml 文件,如下所示:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_myPref"
android:title="My Bool Pref"
android:summary="A Boolean Preference"
android:defaultValue="true"/>
</PreferenceScreen>
然后我可以这样做:
private ISharedPreferences _sharedPref = PreferenceManager.GetDefaultSharedPreferences(Setup.GetApplicationContext());
其中 Setup.GetApplicationContext
是一个静态方法,它返回我在创建 Setup
时保存的上下文,然后我可以通过以下方式获得我的偏好:
_sharedPref.GetBoolean("pref_myPref", true);
但是 ISharedPreferences
没有任何 Set...
功能?!?如何在代码中设置首选项?
这是 MVVMCross 应用程序的一部分,设置代码应该存在于 View 模型级别(IoC 容器将根据需要提供 Android 或 iOS 版本的 Settings
服务),所以我不想在 View 中处理它。我尽量保持抽象。
我一直在看这个:
http://developer.android.com/guide/topics/ui/settings.html
但我很难将其转换为 Xamarin C# 代码并使其按我希望的方式工作。我希望能够取回我的 CheckBoxPreference
实例,这样我就可以在不创建 Activity 或 View 的情况下设置该死的东西。
最佳答案
可以。但它不仅仅是像 setBoolean() 这样的东西。
你必须这样做:
_sharedPref.Edit().PutBoolean("key","value").Commit();
// or
_sharedPref.Edit().PutBoolean("pref_myPref", true).Commit();
关于android - 在 Android 中设置用户首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074880/