Navigating to preference fragment using navigation component

but if your preferences are hierarchical you get Fragment <insert fragment name here> declared target fragment <guid> that does not belong to this FragmentManager! when you click on a child preference.

i have not found a solution to this yet.


I can navigate to another fragment or preference fragment using following approach:

Global Settings Fragment:

<PreferenceCategory
    app:title="@string/global_settings_header">
    <Preference
        app:key="fragment_a"
        app:title="A"
        app:fragment="....settings.SettingsFragmentA" />
    <Preference
        app:key="fragment_b"
        app:title="B"
        app:fragment=".....settings.SettingsFragmentB" />
</PreferenceCategory>

Implemented PreferenceFragmentCompat.OnPreferenceStartFragmentCallback in activity.

public class MainActivity extends AppCompatActivity implements PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {
....

@Override
public boolean onPreferenceStartFragment(PreferenceFragmentCompat caller, Preference pref) {
    NavController navController = Navigation.findNavController(MainActivity.this, R.id.nav_host_fragment);
    if (pref.getKey().equals("fragment_a")) {
        navController.navigate(R.id.nav_settings_fragment_a);
    } else if (pref.getKey().equals("fragment_b")) {
        navController.navigate(R.id.nav_settings_fragment_b);
    }
    return true;
}

....
}

I can also navigate to any fragment that is defined in the navigation graph using NavController.

Any fragment can be used in app:fragment=".....settings.SettingsFragment". The idea is to trigger the onPreferenceStartFragment callback.


To deal with your problem, you can use global actions. To use them you need to define action inside <navigation> tag, not inside <fragment> as you usually do. Your nav graph will contain the next code

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!--Your other fragments-->

    
    <!--Settings fragment-->
    <fragment
        android:id="@+id/settingsFragment"
        android:name="com.example.oleksii.stackoverflow.SettingsFragment"/>

    <!--Global action-->
    <action android:id="@+id/open_settings_fragment"
        app:destination="@id/settingsFragment"/>
</navigation>

In the graph editor it will be displayed in the next way (just arrow in the left of destination):

enter image description here

More details: https://developer.android.com/topic/libraries/architecture/navigation/navigation-global-action