ViewPager in DialogFragment - IllegalStateException: Fragment does not have a view

后端 未结 4 1705
渐次进展
渐次进展 2020-12-08 07:24

What I want to achieve

  • From a FragmentActivity show a dialog when clicking an Action Button in the Action Bar
  • DialogFragment
4条回答
  •  粉色の甜心
    2020-12-08 08:16

    If you implement onCreateDialog to use AlertDialog, you will bump into IllegalStateException: Fragment does not have a view when accessing getChildFragmentManager or something equivalent.

    To solve this issue, implement both onCreateDialog and onCreateView, where onCreateView return the view inflated 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?
        }
    }
    

    https://code.luasoftware.com/tutorials/android/android-alertdialog-in-dialogfragment-fragment-does-not-have-a-view/

提交回复
热议问题