My goal is to build a multiple preference screen consisting of main preferences root.xml and subpreferences adv_preferences.xml using AndroidX Preferences. So far the application only consists of a MainActivity and some fragments such as a home screen fragment, MyRootFragment and AdvPreferencesFragment.
MainActivity does not contain any preferences related code.
MySettingsFragment.kt:
class MyRootFragment : PreferenceFragmentCompat() { // basic preferences
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root, rootKey)
}
}
class AdvPreferencesFragment : PreferenceFragmentCompat() { // advanced preferences
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.adv_preferences, rootKey)
}
}
root.xml (basic preferences):
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/settings">
<CheckBoxPreference
android:defaultValue="true"
android:key="display_text"
android:summaryOff="Invisible"
android:summaryOn="Visible"
android:title="blabla"/>
<Preference
app:title="Advanced Settings"
app:summary="Test for using multiple screens"
app:fragment="com.example.app.ui.settings.AdvPreferencesFragment"/>
</androidx.preference.PreferenceScreen>
adv_preferences.xml (advanced preferences):
<androidx.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Preference
android:key="preference_key"
android:title="placeholder"
android:summary="placeholder" />
</androidx.preference.PreferenceScreen>
mobile_navigation.xml:
<fragment
android:id="@+id/nav_root_preferences"
android:name="com.example.app.ui.settings.MyRootFragment"
android:label="@string/menu_preferences"
tools:layout="@xml/root" />
<fragment
android:id="@+id/nav_adv_preferences"
android:name="com.example.app.ui.settings.AdvPreferencesFragment"
android:label="@string/menu_preferences"
tools:layout="@xml/adv_preferences" />
Everytime I tap Advanced Settings the app would crash with the following logcat message:
java.lang.IllegalStateException: Fragment AdvPreferencesFragment{...} declared target fragment MySettingsFragment{...} that does not belong to this FragmentManager!
How can I fix this? Everything seems to be hooked up correctly in both fragments, xml files and navigation graph.
I already tried to add the following
supportFragmentManager
.beginTransaction()
.replace(R.id.settings, MyRootFragment())
.commit()
to the onCreate() method in MainActivity (as in the Android Jetpack Preference Guide) but this lead to the following crash and message (the app wouldn't even launch anymore):
java.lang.IllegalArgumentException: No view found for id … (com.example.app:id/settings) for fragment MySettingsFragment{...}