kotlinandroidxdialogfragment

On touch close AndroidX DialogFragment


Any ideas...? Using import androidx.fragment.app.DialogFragment, I want to close the dialog when the user touches it. Touch outside dialog closes the dialog (good). I tried

dialog!!.setCancelable(true) // no effect
dialog!!.onTouchEvent...// not intuitive solution

There is no onClick event and I do not want a button. Thanks


Solution

  • If you want close dialog even you touch inside dialog, you can try this:

       class EnsureDialog: DialogFragment() {
            override fun onViewCreated(view: View, savedInstanceState: Bundle?){
                super.onViewCreated(view, savedInstanceState)
    
                //you can set onclick with 'view' of this dialog
                view.setOnClickListener {
                    dismiss()
                }
            }
       }
    

    And call DialogFragment from another view:

        val dialog = EnsureDialog()
        //you can manual set cancelable here:
        //dialog.isCancelable = false
        dialog.show(childFragmentManager, "")
    

    Here I'm using kotlin, convert to java if you wan't. Hope it helpful