For example, when we use the alertdialog that comes with the system, after the dialog box is displayed, we can cancel the dialog box only by pressing the button above or the return key on the mobile phone, if you want to close the dialog box by clicking somewhere outside the view area of the dialog box, you need to use the knowledge points we mentioned today. I directly post Code Analyze it!
Java code
/**
*
* Rewrite the ontouchevent method to process touch-screen events.
*/
@ Override
Public Boolean ontouchevent (motionevent event ){
Log. D ("debug", "ontouchevent ");
Rect = new rect ();
/*
* The view obtained by getwindow (). getdecorview () is the top-level view in the window, which can be obtained from the window,
* The view has a getwindowvisibledisplayframe () method to obtain Program Area displayed,
* Including the title bar, but not the status bar.
*/
Getwindow (). getdecorview (). getwindowvisibledisplayframe (rect );
/**
* The following describes how to obtain the height of the mobile phone Status Bar and the height of the title bar:
*
* 1. Retrieve the status bar height:
* As described above, we can use the rect object to get the height of the mobile phone status bar.
* Int statusbarheight = rect. Top;
*
* 2. Obtain the title bar height:
* Getwindow (). findviewbyid (window. id_android_content );
* The view obtained by this method is the part of the program that does not include the title bar, so that we can calculate the height of the title bar.
* Int contenttop = getwindow (). findviewbyid (window. id_android_content). gettop ();
* // Statusbarheight is the height of the status bar requested above.
* Int titlebarheight = contenttop-statusbarheight
*/
Log. D ("debug", "X:" + (INT) event. getrawx () + "Y:" + (INT) event. getrawy ());
/**
* The rect object rect has a contains method. As long as we pass the coordinates in, we can use the return value to determine whether the coordinates are in
* The rect object represents the rectangular area. Therefore, we can use the following method to determine and control the dialog box.
*/
Log. D ("debug", "Is contains:" +! Rect. Contains (INT) event. getrawx (), (INT) event. getrawy ()));
If (! Rect. Contains (INT) event. getrawx (), (INT) event. getrawy ())){
This. Dismiss ();
Return true;
}
Return super. ontouchevent (event );
}