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

Is it possible to invoke DialogFragment from custom view?

我尝试从自定义视图调用 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)