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

July 23, 2018

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?
    }
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.