【发布时间】:2013-07-24 06:23:41
【问题描述】:
我正在尝试从 XML 中获取首选项,但不使用 PreferenceActivity。 我只想在创建主要活动时从文件中加载并从首选项中获取一个值。但问题是吐司是空的(null?)。我有一个加载首选项的类。
这里是主Activity的onCreate方法
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Preferences prefs = new Preferences();
}
Preferences 类(仅构造函数...)
public Preferences(Context context) {
PreferenceManager.setDefaultValues(context, "MyPrefs", 0, R.xml.preferences, false);
SharedPreferences sharedPreferences = context.getSharedPreferences("MyPrefs", 0);
Editor editor = sharedPreferences.edit();
String myValue = sharedPreferences.getString("myKey", null); // I don't know if null is OK
Toast.makeText(context.getApplicationContext(), myValue, Toast.LENGTH_SHORT).show();
}
还有 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<Preference android:key="myKey" android:defaultValue="hello" />
</PreferenceScreen>
第一次启动应用程序时,我希望设置默认值。所以在这里我希望应用程序在我没有使用 editor.putString(key, value) 设置值的情况下祝酒“你好”。
你知道可能出了什么问题吗? 谢谢
【问题讨论】:
-
您应该将 Preferences 类称为 'Preferences prefs = new Preferences(this);'
-
我试过但没有改变任何东西。
标签: android xml sharedpreferences