Search code examples
androidkotlinandroid-dialogfragment

Dialog Fragment and Dismissing Touches to Activity's Views


I have an activity and a dialog fragment. What I do is when dialog fragment is being shown and user clicks outside dialog fragment, to show an Alert dialog.

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return object: Dialog(activity!!, theme) {
        override fun onTouchEvent(event: MotionEvent): Boolean {
            if (MotionEvent.ACTION_OUTSIDE == event.action) {
                presentAlertDialog()
                return true
            }

            return super.onTouchEvent(event)
        }

    }.apply {
        setCanceledOnTouchOutside(false)
        setCancelable(false)

        window?.apply {
            setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)
            setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH)
        }
    }

If at the point where user clicked there is no view at the activity, then there is no problem. However, when there is a view (e.g., button ) at the point user clicked, both alert dialog and that view's onClickListener is called. What I want to do is just to show alert dialog and make activity's view to dismiss that touch. Is there a way to do it? Thanks in advance!

Edit: To make clearer, I add a screenshot:

enter image description here

What I want is when user touches outside the dialog fragment (i.e., "Waiting" ) and inside Sign Up button (or any other), I want to show an alert dialog and want Sign Up's onClickListener to dismiss that touch.


Solution

  • Okay i guess i understood a little you have two dialogs and when someone clicks outside of first dialog you want to open another. Here is how you can achieve this.

    First set dialog.setCanceledOnTouchOutside(true); then implement cancel() listener

    dialog.setOnCancelListener(
        new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                //Open another dialog here
            }
        });
    

    It's better to use this rather than handling onTouchEvent by yourselves. Hope this helps let me know if still has any issues. I might write some code if given time. Cheers!