Popupwindow is not the same as our activity, because we are often not inherited, but new, when we construct PW. Therefore, you cannot intercept keyboard events by using a method such as OnKeyDown () that overrides PW. Fortunately PW's own characteristics make it easy to use the return key to exit, of course, we can intercept keyboard events, so there are two ways.
method One: The simplest method
In new, use the following method:
Copy Code code as follows:
Popupwindow = new Popupwindow (Popupwindow_view, MB, true);
The key is the last parameter, the SDK gives the hint is focusable, as the name implies is the focusable attribute of the PW, so that it can accept the focus.
Of course you can use another constructor and then set the Focusable property manually:
Popupwindow.setfocusable (TRUE); Generally need to get the focus of the components inside the Popupwindow, often used to receive user input or action action
Note: You must join the following line of unknown statements to play a role:
Popupwindow.setbackgrounddrawable (Newbitmapdrawable ());//Response Returns the statement required by the key.
Please be assured that setting backgrounddrawable does not change the background color or image you set in the configuration file.
Method Two: The most common method
First of all, select a View that does not affect any operation in the PW layout file (*.xml) and recommend the outermost Layout.
Then set the focusable and Focusableintouchmode of the Layout to true.
Then go back to the code and get an instance of the view, and now you can rewrite the Onkeylistener () event for that view. We can manually capture Keycode_back to the dialog box dismiss (). Give an example:
Copy Code code as follows:
Privatepopupwindow PW;
Privateview View;
Privatelinearlayout Laymenu;
Layoutinflater inflater = (layoutinflater) main.getsystemservice (Context.layout_inflater_service);
View = Inflater.inflate (R.layout.popup_main_menu,null, false);
Laymenu = (linearlayout) View.findviewbyid (R.id.laymenu);
PW =new Popupwindow (view, layoutparams.wrap_content, layoutparams.wrap_content,true);
Laymenu.setonkeylistener (Newonkeylistener ()
{
publicboolean onkey (View V, Intkeycode, KeyEvent event)
{
if (event.getacti On () = = Keyevent.action_down && keycode = = keyevent.keycode_back)
& nbsp; Pw.dismiss ();
returnfalse;
}
});
The above two methods of the code can coexist, of course, if you use the first method will not need to catch the return key, but you can try to catch the other button you need