问题
I have this custom dialog
inside an Activty
which is inside ActivityGroup
.
I want the dialog to dismiss when clicked outside, and tried everything i found online to make it work..
I've tried the setCanceledOnTouchOutside(true)
- didn't work
I've tried:
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 );
Log.i(r.toShortString(),r.toShortString());
// 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.dismiss ();
// notify that we consumed this event
return true;
}
}
and it didn't work too..
as i see in the LogCat - i think that from some reason the dialog window size is full screened that why i have no "outside" to touch..
i think it might have to do something with the activity group.. any suggestions ?
回答1:
Ok so after lots of thinking i found out the most simple solution:
The Problem:
From some reason - although the theme I've used is a dialog and not a full screen display - the getWindow().getDecorView()
returns a View which covers the whole screen.
The Solution:
in my XML file I gave the root element an id and I've changed the function above as follow:
private View rootView;
public BaseDialog(Context context, int theme) {
super(context, theme);
//I don't think the next 2 lines are really important - but I've added them for safety
setCancelable(true);
setCanceledOnTouchOutside(true);
}
public void setRootView(int resourceId)
{
this.rootView = findViewById(resourceId);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Rect rect = new Rect();
rootView.getHitRect(rect);
if (!rect.contains((int)event.getX(), (int)event.getY()))
{
this.dismiss();
return true;
}
return false;
}
Hope it will help someone... :)
来源:https://stackoverflow.com/questions/14549133/android-dialog-set-cancel-on-touch-out-side