无法使用 PreferenceActivity 获取首选项设置
我有这个主要活动:
public class Home extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
initializeStyle();
}
private void initializeStyle() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String foobar = prefs.getString("foobar", "hi");
Log.i("MyActivity", foobar);
}
// ...
}
和这个 PreferenceActivity:
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
使用这个 XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="preferences_font"
android:title="@string/preferences_font">
<EditTextPreference
android:title="@string/preferences_font_size"
android:key="foobar"
android:defaultValue="12">
</EditTextPreference>
</PreferenceCategory>
</PreferenceScreen>
Log.i 打印“hi”,所以这意味着这个首选项不存在或者我命名得很糟糕。
你知道我做错了什么吗?
问候,
I have this main activity:
public class Home extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
initializeStyle();
}
private void initializeStyle() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String foobar = prefs.getString("foobar", "hi");
Log.i("MyActivity", foobar);
}
// ...
}
And this PreferenceActivity:
public class Preferences extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
With this XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="preferences_font"
android:title="@string/preferences_font">
<EditTextPreference
android:title="@string/preferences_font_size"
android:key="foobar"
android:defaultValue="12">
</EditTextPreference>
</PreferenceCategory>
</PreferenceScreen>
Log.i prints "hi", so it means this preference doesn't exist or I named it badly.
Any idea about what I've done wrong?
Regards,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能会帮助您回到正轨并获得工作首选项:
XML 文件:preferences.xml
JAVA 文件 1:Home.java
JAVA 文件 2:Prefernce.java
希望这可以帮助您走上正确的轨道。当然,有很多方法可以做到这些,祝你好运,希望它能有所帮助。
This might help you get back on track and having working preferences:
XML FILE: preferences.xml
JAVA FILE 1: Home.java
JAVA FILE 2: Prefernce.java
Hopefully this may help you get on the right track. Of course there are many ways to do these things so, good luck hope it helps.