从片段显示对话框时未调用onAttachFragment

问题描述 投票:0回答:2

我正在从片段中显示BottomSheetDialogFragment。我的想法是在Fragment中获取BottomSheetDialogFragment的回调而不是活动,所以我希望在里面接收片段

override fun onAttachFragment(childFragment: Fragment?) {
        super.onAttachFragment(childFragment)
        callback = childFragment as? Callback
    }

此方法未被调用。我在显示对话框时尝试使用fragmentManager和childFragmentManager来查看是否可以调用onAttachFragment,但没有运气。

AccountBottomSheetDialog dialog = AccountBottomSheetDialog.Companion.newFragment();
                dialog.show(getChildFragmentManager(), AccountBottomSheetDialog.Companion.getTAG());

AccountBottomSheetDialog dialog = AccountBottomSheetDialog.Companion.newFragment();
                dialog.show(getFragmentManager(), AccountBottomSheetDialog.Companion.getTAG());

有谁知道如何调用这个?

谢谢。

android android-fragments android-dialogfragment fragmentmanager
2个回答
0
投票

无法直接回答您的问题,但这是您可以采取的解决方法:

  1. 将您的父片段作为newFragment的参数传递
  2. 使用任何请求代码将其设置在您的子片段上作为目标片段(setTargetFragment
  3. 在你的代码中使用它作为getTargetFragment()并将其转换为你喜欢的任何接口(你的父片段实现的接口当然)。

PS。:对于上面的工作,片段管理器必须对父母和孩子是相同的。


0
投票

我认为它不调用onAttachFragment的原因是因为DialogFragment控制其生命周期和其他方法的覆盖方式与正常方法不同,请参阅documentation

如果您只想回调父片段,可以覆盖onAttach中的DialogFragment方法并使用context参数作为回调(强制转换),或者在DialogFragment中设置一个公共方法来设置回调,你会在创建该片段后调用。


onAttach方法:

override fun onAttach(context: Context?) {
    super.onAttach(context)
    callback = context as? Callback
}

公共回调设置方法:

//parent fragment: after initializing it    
childFragment.setCallback(this@ParentFragment)//or pass in other callbacks

//child fragment: 
fun setCallback(callback: Callback) {
  this.callback = callback
}
© www.soinside.com 2019 - 2024. All rights reserved.