Friday, August 27, 2010

Closing an activity by touching outside

I have been working on an application that I want to close an Activity when the user touches outside the activity. Like how you can set the setCanceledOnTouchOutside(boolean cancel) in the android.app.Dialog. The activity I want to close is themed like a dialog so there is an area around the activity that is not “active”.

I was able to achieve the desired effect by overriding the activity’s onTouchEvent(MotionEvent event). This method is called when a screen touch event is not handled by any views.

@Override
public boolean onTouchEvent ( MotionEvent event ) {
// I only care if the event is an UP action
if ( event.getAction () == MotionEvent.ACTION_UP ) {
// create a rect for storing the window rect
Rect r = new Rect ( 0, 0, 0, 0 );
// retrieve the windows rect
this.getWindow ().getDecorView ().getHitRect ( r );
// check if the event position is inside the window rect
boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
// if the event is not inside then we can close the activity
if ( !intersects ) {
// close the activity
this.finish ();
// notify that we consumed this event
return true;
}
}
// let the system handle the event
return super.onTouchEvent ( event );
}

Now with that code in place, if the user touches anywhere outside of the dialog style activity, it will close.


No comments:

Post a Comment

Closing an activity by touching outside

I have been working on an application that I want to close an Activity when the user touches outside the activity. Like how you can set the setCanceledOnTouchOutside(boolean cancel) in the android.app.Dialog. The activity I want to close is themed like a dialog so there is an area around the activity that is not “active”.

I was able to achieve the desired effect by overriding the activity’s onTouchEvent(MotionEvent event). This method is called when a screen touch event is not handled by any views.

@Override
public boolean onTouchEvent ( MotionEvent event ) {
// I only care if the event is an UP action
if ( event.getAction () == MotionEvent.ACTION_UP ) {
// create a rect for storing the window rect
Rect r = new Rect ( 0, 0, 0, 0 );
// retrieve the windows rect
this.getWindow ().getDecorView ().getHitRect ( r );
// check if the event position is inside the window rect
boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
// if the event is not inside then we can close the activity
if ( !intersects ) {
// close the activity
this.finish ();
// notify that we consumed this event
return true;
}
}
// let the system handle the event
return super.onTouchEvent ( event );
}

Now with that code in place, if the user touches anywhere outside of the dialog style activity, it will close.