问题描述
我在飞溅屏幕PreferenceManager和SharedPreferences的教程中遇到了两个类。虽然我没有从教程中获得大量关于它们的知识。
I've come across two classes being used in a tutorial on splash screens PreferenceManager and SharedPreferences. I didn't gain a great deal of knowledge about them from the tutorial though.
所以有人可以向我解释这两个类的用途或用途是什么?
So can someone explain to me what both classes do or are used for?
推荐答案
首选项是一种Android轻量级机制,用于存储和检索原始数据类型对
(也是称为地图和关联阵列。
Preferences is an Android lightweight mechanism to store and retrieve pairsof primitive data types (also called Maps, and Associative Arrays).
在表单的每个条目中,键是一个字符串,值必须是原始数据类型。
In each entry of the form the key is a string and the value must be a primitive data type.
当我们需要时
首选项通常用于保存状态信息并在应用程序的多个活动中共享数据
。
PREFERENCES are typically used to keep state information and shared dataamong several activities of an application.
共享首选项是android中的存储,可用于存储与功能,用户自定义或其配置文件相关的一些基本内容。
Shared Preferences is the storage, in android, that you can use to store some basic things related to functionality, users' customization or its profile.
假设您希望在应用中保存用户名以备将来使用。你不能在数据库中保存这么小的东西,所以你最好把它保存在你的首选项中。首选项就像一个文件,您可以在应用程序的生命周期中随时以KEY-VALUE对方式检索值。
Suppose you want to save user's name in your app for future purposes. You cant save such a little thing in database, So you better keep it saved in your Preferences. Preferences is just like a file , from which you can retrieve value anytime in application's lifetime in a KEY-VALUE pair manner.
再举一个例子,如果您使用whatsapp,我们那里有壁纸选项。无论何时打开whatsapp,应用程序如何知道哪个图像可以作为墙纸。此信息存储在首选项中。每当您清除任何应用的数据时,首选项都会被删除。
Take another example, If you use whatsapp, we have a wallpaper option there. How the application knows which image serves as wall-paper for you whenever you open your whatsapp. This information is stored in preferences. Whenever you clear data for any app, preferences are deleted.
如何使用这些偏好:
final int mode = Activity.MODE_PRIVATE;
final String MYPREFS = "MyPreferences_001";
// create a reference to the shared preferences object
SharedPreferences mySharedPreferences;
// obtain an editor to add data to my SharedPreferences object
SharedPreferences.Editor myEditor;
mySharedPreferences = getSharedPreferences(MYPREFS, 0);
// using this instance you can get any value saved.
mySharedPreferences.getInt("backColor",Color.BLACK); // default value is BLACK set here
编辑共享偏好:
myEditor = mySharedPreferences.edit();
//edit and commit
myEditor.putString("backColor", Color.RED);
myEditor.commit() //very imp.
这篇关于Android中使用的PreferenceManager和SharedPreference类是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!