I would like to do a normal PreferenceActivity (in the old style, without headers), but with fragments and without using addPreferencesFromResource(id)
(because deprecation).
Right now I achieved this by putting this in my onCreate
:
getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferencesFragment()).commit();
And my PreferencesFragment
looks something like this:
public static class PreferencesFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
Obviously I also implemented the isValidFragment
method:
@Override
protected boolean isValidFragment(String fragmentName) {
return PreferencesFragment.class.getName().equals(fragmentName)
|| InnerFragment.class.getName().equals(fragmentName);
}
And it's working just fine. However, there is a problem when having PreferenceScreen
's inside my preferences.xml
:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- ... -->
<PreferenceScreen android:fragment="net.chaozspike.batterynotifier.SettingsActivity$InnerFragment"
android:summary="@string/settings_activity_prefs_display_night_mode_sum"
android:title="@string/settings_activity_prefs_display_night_mode" />
<!-- ... -->
</PreferenceScreen>
I have the following problem: the new preference screen shows on top of the normal one, and I know it's probably because I replaced the default R.id.content
. Screenshot:
However I want to fix this problem without using deprecated stuff or headers. Is that possible to achieve?
I discovered the solution by myself. If I am not going to make a fragment-based, header-based SettingsActivity, but still want to not use deprecated methods, then I have to not use fragments at all except for the one that is used to replace the main view. In other words, I had to remove the InnerFragment
and so I could also remove the isValidFragment
method. And I moved all the code in the other XML file to the first one like this:
First file (old):
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- ... -->
<PreferenceScreen android:fragment="net.chaozspike.batterynotifier.SettingsActivity$InnerFragment"
android:summary="@string/settings_activity_prefs_display_night_mode_sum"
android:title="@string/settings_activity_prefs_display_night_mode" />
<!-- ... -->
</PreferenceScreen>
First file (new):
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- ... -->
<PreferenceScreen android:summary="@string/settings_activity_prefs_display_night_mode_sum"
android:title="@string/settings_activity_prefs_display_night_mode" >
<!-- Contents of second file here>
<CheckBoxPreference /> etc.
</PreferenceScreen>
<!-- ... -->
</PreferenceScreen>