[英]Write and read preferences from non default file
how can I write and read preferences to and from an non default file using androids preferences. 如何使用androids首选项在非默认文件中写入和读取首选项。
Following code is working but it is deprecated: 以下代码正在运行但不推荐使用:
public class MyPreferencesActivity extends PreferenceActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName("my_preferences");
prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.preferences);
}
}
In addition I need to bind the custom preference file to my Activitiy/Fragment so that any user changes in the preferences by the user are saved automatically to the custom file. 此外,我需要将自定义首选项文件绑定到我的Activitiy / Fragment,以便用户对首选项的任何更改都会自动保存到自定义文件中。
The background is following: I'm writing a widget and every instance of that widget needs its own preferences. 背景如下:我正在编写一个小部件,该小部件的每个实例都需要自己的首选项。 So I need to save and load the preference for every widget seperatly. 所以我需要分别保存和加载每个小部件的首选项。
I did not find any solution for this without using deprecated code. 没有使用已弃用的代码,我没有找到任何解决方案。 Any help is really welcome :). 任何帮助真的很受欢迎:)。
简单:
SharedPreferences prefs = context.getSharedPrefernces("fileName", 0);
To read and write settings on your own you can use the following code: 要自己读写设置,可以使用以下代码:
// Get preferences
SharedPreferences sharedPreferences = PreferenceManager.setSharedPreferencesName("SomeFilename",0);
PreferenceManager.setSharedPreferencesMode(MODE_WORLD_READABLE);
// Read some values
String name = sharedPreferences.getString("Key", "defaultValue");
[...]
//Write preferences
SharedPreferences sharedPreferences = PreferenceManager.getSharedPreferencesName("SomeFilename", 0);
// Write some values
Editor editor = sharedPreferences.edit();
editor.putString("key", "someValue");
[...]
editor.commit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.