huu duy
huu duy

Reputation: 2059

How to detect when user touch outside the dialog fragment?

I want to perform some tasks when user touch outside the dialog fragment. How can I do this?

Upvotes: 3

Views: 3907

Answers (2)

DYS
DYS

Reputation: 3053

Then you need to remove getDialog().setCanceledOnTouchOutside(false); and use some reflection to leverage Window's hidden method for deciding when to close dialog:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return object : Dialog(activity as Context, theme) {
        override fun onTouchEvent(event: MotionEvent): Boolean {
            if (dialogShouldCloseOnTouch(window, context, event)) {
                // do custom logic
                return true
            } else {
                return super.onTouchEvent(event)
            }
        }
    }
}

private fun dialogShouldCloseOnTouch(
    window: Window, 
    context: Context, 
    event: MotionEvent): Boolean {
    val method = window.javaClass.getMethod("shouldCloseOnTouch", Context::class.java, MotionEvent::class.java)
    return method.invoke(window, context, event) as Boolean
}

Upvotes: 2

Aman Grover
Aman Grover

Reputation: 1641

public class MyActivity extends Activity {

 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Make us non-modal, so that others can receive touch events.
    getWindow().setFlags(LayoutParams.FLAG_NOT_TOUCH_MODAL, LayoutParams.FLAG_NOT_TOUCH_MODAL);

    // ...but notify us that it happened.
    getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

    // Note that flag changes must happen *before* the content view is set.
    setContentView(R.layout.my_dialog_view);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    // If we've received a touch notification that the user has touched
    // outside the app, finish the activity.
    if (MotionEvent.ACTION_OUTSIDE == event.getAction()) {
      //outside touch event
      return true;
    }

    // Delegate everything else to Activity.
    return super.onTouchEvent(event);
  }
}

Reference: Look at the second answer here.

P.S. In the question he said he has an activity with the dialog theme.

Upvotes: 0

Related Questions