Ksenia
Ksenia

Reputation: 3753

Is it possible to invoke DialogFragment from custom view?

I've tried to invoke DialogFragment from custom view:

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

where DetailsDialogFragment looks like this:

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
                    )
                }
        }
    }
}

But I receive the following error:

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

Is it possible to invoke DialogFragment from custom view at all?

Upvotes: 0

Views: 325

Answers (1)

Ahmed I. Khalil
Ahmed I. Khalil

Reputation: 743

The reason of this exception is that you're trying to use the childFragmentManager of your freshly newly created instance, which is of course not possible since the Dialog fragment hasn't yet has its internals initialized yet (including its childFragmentManager).

If you're using AndroidX I'd use the findFragment extension method inside your custom view and try to do:

Inside your custom view

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

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

Upvotes: 2

Related Questions