javaandroidkotlinandroid-dialogfragment

Dialog Fragment and Detecting Touches to the Outside of Its Window


I have a DialogFragment which contains a ProgressBar. What I want to do is to show an AlertDialog whenever user clicks outside the window of dialog fragment. In onCreateView of the dialog fragment, I can detect touch events inside the dialog fragment by calling setOnTouchListener to view that is about to be created. How can I detect touches to the outside?

By following a suggestion from another stackoverflow question, I tried to set flags:

    val dialogWindow = dialog.window
    dialogWindow?.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
    dialogWindow?.setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH)

But couldn't detect touches in setOnTouchListener.


Solution

  • class MyDialogFragment : DialogFragment() {                   
    
        override fun onCreateDialog(savedInstanceState: Bundle?)  
                : Dialog {                                        
    
            return object : Dialog(activity, theme){              
    
                override fun onTouchEvent(event: MotionEvent?)    
                        : Boolean {                               
                    // Here you can handle the touch event        
                    return super.onTouchEvent(event)              
                }                                                 
            }                                                     
        }                                                         
    }                   
    

    Also call the setCanceledOnTouchOutside(false), because touching outside the dialog will automatically dismiss it.