是否可以从自定义视图调用DialogFragment?

问题描述

我尝试从自定义视图调用DialogFragment:

DetailsDialogFragment
    .newInstance(newSelectedDate,adapterItems[newPosition].progress)
    .apply {
         show(childFragmentManager,score_DETAILS_DIALOG_TAG)
    }

DetailsDialogFragment如下所示:

class DetailsDialogFragment : AppCompatDialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return requireActivity().let {
            val dialog = Dialog(requireContext(),R.style.CustomDialog)
            dialog.window?.setDimAmount(BaseDialogFragment.SCRIM_OPACITY)
            dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            dialog
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_details_dialog,container,false)
    }

    override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
        super.onViewCreated(view,savedInstanceState)
        view.rootView.apply {
            findViewById<TextView>(R.id.titleTextView).text = arguments?.getString(ARGS_MONTH)
            findViewById<ActionButton>(R.id.button).setonClickListener {
                dismiss()
            }
            findViewById<ImageView>(R.id.closeImageView).setonClickListener {
                dismiss()
            }
        }
    }

    companion object {
        fun newInstance(
            month: String,score: Int
        ): DetailsDialogFragment {
            return DetailsDialogFragment()
                .apply {
                    arguments = bundleOf(
                        ARGS_MONTH to month,ARGS_score to score
                    )
                }
        }
    }
}

但是我收到以下错误

IllegalStateException: Fragment DetailsDialogFragment has not been attached yet.
        at androidx.fragment.app.Fragment.getChildFragmentManager(Fragment.java:980)
        ...

是否可以从自定义视图中调用DialogFragment

解决方法

此异常的原因是您尝试使用新创建的实例的childFragmentManager,这当然是不可能的,因为Dialog片段尚未初始化其内部(包括其childFragmentManager)。

如果您使用的是AndroidX,则可以在自定义视图中使用findFragment扩展方法,然后尝试执行以下操作:

在您的自定义视图内

val dialogFragment = DetailsDialogFragment
    .newInstance(newSelectedDate,adapterItems[newPosition].progress)

dialogFragment.show(findFragment().childFragmentManager,SCORE_DETAILS_DIALOG_TAG)