问题描述
我遇到了一个非常简单的问题:我正在尝试在应用中构建首选项"屏幕,并且希望使用新的,现在已经成为标准的PreferenceFragment方法.
I'm stuck with a pretty simple issue: I'm trying to build a Preference screen in my app and I'd like to do it with the new, now-standard PreferenceFragment method.
这是我的首选项xml:
This is my prefs xml:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="@string/prefs_interface_settings">
<SwitchPreference
android:key="show_average"
android:title="Show average length of work day"
android:defaultValue="false"
android:summary="Display the calculated average in the app title" />
<EditTextPreference
android:key="edittext_preference"
android:title="@string/workday_duration_prefs_title"
android:summary="summary_edittext_preference"
android:defaultValue="8"
android:dialogTitle="dialog_title_edittext_preference" />
</PreferenceCategory>
</PreferenceScreen>
这是我的SettingsActivity
This is my SettingsActivity
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.widget.Toast;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
}
}
最后-这是我的SettingsFragment:
and - finally - this is my SettingsFragment:
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
addPreferencesFromResource(R.xml.app_preferences); //Gets settings from XML
}
}
}
当我运行该应用程序时,如果我确实打开了上述活动,则会得到一个空的活动,就像由于某种原因该片段未初始化(或未显示)一样.但是代码是如此简单……我做错了!
When I run the application, if I do open said activity I get an empty one, just like the fragment was not initialized - or not shown - for some reason. But the code is so simple... I just can't get what I do wrong!
谢谢大家的帮助
推荐答案
getArguments()仅在创建 <preference-headers/>
时使用.在首选项XML文件的<extra/>
元素中声明的参数.声明后,将在PreferenceFragment
:
getArguments() used only when you create <preference-headers/>
. The arguments declared in <extra/>
element of the preference-header XML file. Once you declared it, you will call this code within PreferenceFragment
:
String settings = getArguments().getString("settings");
if (settings.equals("myArgument")) {
addPreferencesFromResource(R.xml.settings_wifi);
}
但是,由于您不使用<preference-headers/>
,因此只需要在PreferenceFragment
中调用此代码:
But, as you do not use <preference-headers/>
, so you only need to call this code in the PreferenceFragment
:
addPreferencesFromResource(R.xml.app_preferences);
这篇关于尽管添加了PreferenceFragment,但PreferenceActivity为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!