首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >什么是SharedPreferencesCompat?vs SharedPreferences

什么是SharedPreferencesCompat?vs SharedPreferences
EN

Stack Overflow用户
提问于 2015-11-19 16:19:49
回答 2查看 3.4K关注 0票数 17

我想知道什么是SharedPreferencesCompat?它与SharedPreferences有什么不同?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-11-19 16:29:24

所有的...Compat类都是为了向后兼容。有些为没有原生功能的旧设备带来了新功能,有些则在其他方面对旧设备的开发有所帮助。

在本例中,它提供了一种调用apply方法的简化方法,该方法是在API level 9中添加的。

如果你的应用程序不支持早于9的版本,你就不需要这个类。

如果您支持较旧的设备并执行以下操作

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("key","val");
editor.apply();

您将得到一个错误,因为该方法并不是在您支持的所有设备上都存在。解决这个问题会变得很难看。除非你使用SharedPreferencesCompat

 ...
 editor.putString("key", "val");
 SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
票数 21
EN

Stack Overflow用户

发布于 2015-11-19 16:29:45

源代码将回答您的问题:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2_r1/com/android/common/SharedPreferencesCompat.java

反射工具在可能的情况下调用SharedPreferences$Editor.apply,当apply不可用时回退到提交。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33798506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档