提问者:小点点

替换PreferencesFragment中不推荐使用的setTargetFragment()


我不知道如何在下面的代码示例中替换setTargetFragment(),这显然来自我的首选项片段

override fun onPreferenceStartFragment(
    caller: PreferenceFragmentCompat,
    pref: Preference
): Boolean {
    // Instantiate the new Fragment
    val args = pref.extras
    val fragment = supportFragmentManager.fragmentFactory.instantiate(
        classLoader,
        pref.fragment
    ).apply {
        arguments = args
        setTargetFragment(caller, 0) // <-- DEPRICATED CODE
    }

    // Replace the existing Fragment with the new Fragment
    supportFragmentManager.beginTransaction()
        .replace(R.id.settings, fragment)
        .addToBackStack(null)
        .commit()
    title = pref.title
    return true
}

对于我的Android Studio知识水平来说,有太多的未知!这个参考很有帮助,但是仍然很困惑:既然setTargetFragment()已经被弃用,如何替换它


共1个答案

匿名用户

好吧,显然这有效,但我不确定我是否真的了解发生了什么:

override fun onPreferenceStartFragment(
    caller: PreferenceFragmentCompat,
    pref: Preference
): Boolean {
    // Instantiate the new Fragment
    val args = pref.extras
    val fragment: Fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, pref.fragment)
    fragment.arguments = args
    supportFragmentManager.beginTransaction().replace(R.id.settings, fragment).addToBackStack(null).commit()
    supportFragmentManager.setFragmentResultListener("requestKey", fragment) { _, _ ->   }
return true
}