google android studio的标准设置活动现在显示第一个标题" General"。所以我修改了代码但是在第一次出现getPreferenceScreen()时我得到了java.lang.NullPointerException。addPreference(fakeHeader);
private void setupSimplePreferencesScreen() {
if (!isSimplePreferences(this)) {
return;
}
PreferenceCategory fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_notifications);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_general);
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_notifications);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_notification);
bindPreferenceSummaryToValue(findPreference("username"));
bindPreferenceSummaryToValue(findPreference("password"));
bindPreferenceSummaryToValue(findPreference("server"));
}
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void onBuildHeaders(List<Header> target) {
if (!isSimplePreferences(this)) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
}
<header
android:fragment="com.example.eslam.rottapharm.SettingsActivity$GeneralPreferenceFragment"
android:title="@string/pref_header_general" />
</preference-headers>
答案 0 :(得分:12)
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
</PreferenceScreen>
然后,在SettingsActivity.java中我有:
// Add container
addPreferencesFromResource(R.xml.pref_container);
// Add 'general' preferences, and a corresponding header.
PreferenceCategory fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_general);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_general);
// Add 'backup' preferences, and a corresponding header.
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_backup);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_backup);
这对我有用。