Navigate from PreferenceScreen to another Fragment

Using the Navigation components of Android Jetpack i have a MainActivity which holds 4 different fragments. One of those fragments is the SettingsFragment which has my preferences from an xml file.

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="">

    <PreferenceCategory android:title="General settings">
            android:summary="Choose an account from your list"
            <intent android:action="@string/preferences_account_intent_action" />

    <PreferenceCategory android:title="User settings">
            android:summaryOn="Show message content on new notification"
            android:summaryOff="Hide message content on new notification"
            android:title="Message content" />

            android:summary="List of all the files of the application"


And the SettingsFragment extends the PreferenceFragmentCompat from Android. From all the other fragments i can navigate to each other through the findNavigation utility from the MainActivity. I want to navigate from SettingsFragment to GalleryFragment when i press the "Gallery" option from the settings. I have added the GalleryFragment to the MainActivity navigation graph and i have connected the SettingsFragment to GalleryFragment, which creates the action for the Navigator. But how can i catch the gallery click event? Is there a specific way to do that?


  • In your settings fragment, add a preference change listener. Then in the listener, add your navigation code. Something like this.

            val preferenceGallery = preferenceManager.findPreference<Preference>("preferenceIDGallery")!!
            preferenceGallery.let {
                it.setOnPreferenceChangeListener { preference, newValue ->
                        val f = requireActivity().supportFragmentManager.findFragmentById( as NavHostFragment
                        val navController: NavController = f.navController //for fragment switch