Christopher Masser
Christopher Masser

Reputation: 829

Android Activity: Listener for outside touch event

I have an Activity shown as a Dialog:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setTheme(android.R.style.Theme_Dialog);
    setFinishOnTouchOutside(true);
}

When the user closes the Activity-Dialog by touching outside the Activity-Dialog window, the Activity finishes.

How can I set a Listener on this event?

This is important because I want to be able to call

setResult(intResultCode, intent);

right before finishing.

Calling setResult() in onPause() can be too late already.

Upvotes: 1

Views: 2649

Answers (3)

Sergey Glotov
Sergey Glotov

Reputation: 20346

It's possible. You can override onTouchEvent()

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (MotionEvent.ACTION_OUTSIDE == event.getAction()) {
        // Your logic
        // return true if you don't want to pass event further
    }
    return super.onTouchEvent(event);
}

If you don't get ACTION_OUTSIDE event, possibly you need to add FLAG_NOT_TOUCH_MODAL and FLAG_WATCH_OUTSIDE_TOUCH window flags. Works for me without it.

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

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
    ...
}

Upvotes: 0

Gopal Gopi
Gopal Gopi

Reputation: 11131

why to struggle that much? just override finish() method in Avtivity...

@Override
public void finish() {
    setResult(int resultCode, Intent data);
    super.finish();
}

Upvotes: 4

Praveen Sharma
Praveen Sharma

Reputation: 4348

first put

dialog.setCanceledOnTouchOutside(true) 

and after that use

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Rect dialogBounds = new Rect();
    getWindow().getDecorView().getHitRect(dialogBounds);

    if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
        // Tapped outside so we finish the activity
        this.finish();
    }
    return super.dispatchTouchEvent(ev);
}

Upvotes: 0

Related Questions