如何在两个 PreferenceFragmentCompat 类 之间传递数据?

How to pass data between two PreferenceFragmentCompat classes?

我想将 id 之类的数据传递给另一个 PreferenceFragmentCompat class这样我就可以使用组 ID 配置该特定组。为了在 2 个首选项片段之间导航,您在首选项 xml 文件中或通过代码指定 app:fragment 并设置参数:

val bundle = Bundle()
bundle.putString("id", "group id")

val preference = Preference(context).apply {
    title = "group name"
    key = "key"
    fragment ="io.foodless.fragments.preferences.GroupPreference"
    arguments = bundle
}

但在 GroupPreference class 中,当我尝试访问参数时 id returns 空

class GroupPreference:PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.group_preference,rootKey)

        val groupId = arguments?.getString("id")
        Log.d("debug","data $groupId")
    }
}

Preference.getExtras() 中说

Return the extras Bundle object associated with this preference, creating a new Bundle if there currently isn't one. You can use this to get and set individual extra key/value pairs.

所以我没有制作新的 Bundle,而是调用了 preference.getExtras() 并且它起作用了:

val preference = Preference(context).apply {
    title = "group name"
    key = "key"
    fragment ="io.foodless.fragments.preferences.GroupPreference"

    val bundle = extras
    bundle.putString("id", "group id")
}