androidkotlinnavigationandroid-preferencesandroid-architecture-navigation

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="http://schemas.android.com/apk/res/android">

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

    <PreferenceCategory android:title="User settings">
        <SwitchPreference
            android:defaultValue="true"
            android:enabled="true"
            android:key="user_show_notif_content"
            android:summaryOn="Show message content on new notification"
            android:summaryOff="Hide message content on new notification"
            android:title="Message content" />

        <PreferenceScreen
            android:key="gallery"
            android:summary="List of all the files of the application"
            android:title="Gallery">
        </PreferenceScreen>
    </PreferenceCategory>

</PreferenceScreen>

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?


Solution

  • 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(R.id.nav_host_fragment) as NavHostFragment
                        val navController: NavController = f.navController //for fragment switch
                        navController.navigate(R.id.fragmentGallery)
                    true
                }
            }