IllegalStateException: Fragment does not have a view - AlertDialog onCreateDialog in DialogFragment

If you override onCreateDialog with AlertDialog instead of overriding onCreateView, you shall bump into IllegalStateException: Fragment does not have a view when calling getChildFragmentManager.

To solve this issue, make sure to override onCreateView to return the view created in onCreateDialog.

class LocationPickerDialog : DialogFragment() {        lateinit var customView: View    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {        return customView    }    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {        Log.d(TAG, "onCreateDialog")        // StackOverflowError        // customView = layoutInflater.inflate(R.layout.dialog_location_picker, null)        customView = activity!!.layoutInflater.inflate(R.layout.dialog_location_picker, null)        val builder = AlertDialog.Builder(context!!)                .setView(customView)                .setPositiveButton(android.R.string.ok) { _, _ ->                    // do something                }                .setNegativeButton(android.R.string.cancel) { _, _ ->                    // do something                }        val dialog = builder.create()        return dialog    }    override fun onActivityCreated(savedInstanceState: Bundle?) {        // if onCreateView doesn't return a view         // java.lang.IllegalStateException: Fragment does not have a view        mapFragment = childFragmentManager.findFragmentByTag("map") as SupportMapFragment?    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.