Android : 从子片段访问父片段函数

Android : Acces parent fragment function from child fragment

我在 activity[=35 中有一个 父片段 =] 并在 父片段 中有一个 子片段 。两个Fragment的NavGraphs不同。我想从子片段[访问父片段中的函数=36=],但应用程序崩溃了。我该怎么做?

子片段:

class ProfilinMenu : Fragment(){

private var _binding : FragmentProfilinMenuBinding? = null
private val profilinmenubinding get() =  _binding!!

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View {
    _binding = FragmentProfilinMenuBinding.inflate(inflater,container,false)


    (parentFragment as Parent).changeName() // this is for access parent


    return profilinmenubinding.root
}}

父片段:

public class Parent : Fragment() {

private var _binding : FragmentParentBinding? = null
private val parentBinding get() = _binding!!
private var instance: Parent? = null


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

    _binding = FragmentParentBinding.inflate(inflater, container, false)
    val view = parentBinding.root

  
    return view
}

public fun changeName(){
    parentBinding.profilinIsmin.text = "Merhaba"
}

试试这个..

NavHostFragment navHostFragment = (NavHostFragment) getParentFragment();
ParentFragment parent = (ParentFragment) navHostFragment.getParentFragment();
parent.changeName()