kotlin 从PreferenceScreen导航到另一个Fragment

i34xakig  于 2023-10-23  发布在  Kotlin
关注(0)|答案(2)|浏览(124)

使用Android Jetpack的导航组件,我有一个MainActivity,它包含4个不同的片段。其中一个片段是SettingsFragment,它包含来自xml文件的首选项。

<?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>

SettingsFragment扩展了Android的PreferenceFragmentCompat。我可以通过MainActivity中的findNavigation实用程序在所有其他片段中相互导航。当我按下设置中的“Gallery”选项时,我想从SettingsFragment导航到GalleryFragment。我已经将GalleryFragment添加到MainActivity导航图中,并将SettingsFragment连接到GalleryFragment,后者为Navigator创建了操作。但是我怎么能抓住画廊点击事件?有没有具体的方法来做到这一点?

mo49yndu

mo49yndu1#

在设置片段中,添加一个首选项更改侦听器。然后在侦听器中添加导航代码。就像这样。

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
            }
        }
gojuced7

gojuced72#

使用@Viatcheslav Ehrmann的答案,解决方案如下

<PreferenceScreen
            android:key="pref_gallery"
            android:summary="File list of application"
            android:title="Gallery" />

在SettingsFragment的onCreate中,

preferenceManager.findPreference<Preference>("pref_gallery")?.let {
            it.setOnPreferenceClickListener {
                findNavController().navigate(SettingsFragmentDirections.actionSettingsFragmentToGalleryFragment())
                true
            }
        }

相关问题